I have a standard leaflet map showing a tile layer. Now leaflet only lets you use panTo
method using LatLng for example,
map.panTo(new L.LatLng(40.17, -98.12));
How will I use above panTo method if my coordinates are in EPSG:3857
for example (3679364.68,-9096106.74)
?
This is quite simple to to in Openlayers as once you define a map projection everything works in that projection. But Leaflet always works on latlng on the outside.
Any simple way to accomplish this using leaflet library?
Thanks!
Leaflet lets you use panTo method by unproject 3857 point. If you don't want to use proj4js library it also achieve in leaflet.
var point = new L.Point(3679364.68,-9096106.74); // Lon/Lat
var earthRadius = 6378137;
var latlng = L.Projection.SphericalMercator.unproject(point.divideBy(earthRadius));
map.panTo(new L.LatLng(latlng.lat, latlng.lng));
I can get it working if I use proj4js library to transform the coordinates by doing this:
var source = new Proj4js.Proj('EPSG:3857');
var dest = new Proj4js.Proj('EPSG:4326');
var p = new Proj4js.Point(-9096106.74,3679364.68); //this takes x,y
Proj4js.transform(source, dest, p);
this.map.setView(new L.LatLng(p.y, p.x),zoom);
But this is still not an ideal solution as it taxes me a Megabyte for for including the library. I am still looking for a leaflet solution. Knowing that internally leaflet already uses EPSG:3857 to fetch tiles, this shouldn't be this difficult.
Update
To do this purely in Leaflet, look at @ARsl's answer. Only reason I still accept this as my answer because, still feel uncomfortable doing the projection calculations like that (not that they are wrong), and just for that reason I don't accept this answer. Plus proj4js as added advantages of supporting many more datums.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With