Search code examples
javascriptmapsgisleaflet

Leaflet: panTo Web Mercator coordinates (EPSG 3857)


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!


Solution

  • 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.

    UPDATE
    

    Check @Moos'SamuelSilver 's comment for this answer for another way to do this in leaflet without proj4js:

    Leaflet.CRS.EPSG3857.unproject(Leaflet.point(x,y)) does the job pretty well. Source and further informations: leafletjs.com/reference.html#crs