Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set map center in leaflet with 3857 lat/lon

I'm trying to set map center with lat/lon of 3857 projection in leaflet. By using lat/lon of projection 4326 its working fine.

var map = L.map('map', {
        crs: L.CRS.EPSG3857
    }).setView([51.40457186188496, -2.3741738081973844], 13);

But it dose not working if i provide 3857 lat/lon.

var map = L.map('map', {
            crs: L.CRS.EPSG3857
        }).setView([6693172.2381477, -264291.81938326], 13);

Please help me where i am wrong.

Thanks

like image 207
ARsl Avatar asked Mar 19 '14 11:03

ARsl


1 Answers

Leaflet's API uses lat/lng for all its operations, so you should never use projected coordinates when calling Leaflet.

If you have projected coordinates, which strictly speaking isn't latitude and longitude, you can turn them into lat/lng by unprojecting them. Since current stable versions of Leaflet has a slightly different definition of EPSG:3857, you will have to divide your coordinate by the EPSG:3857's sphere radius. Also, your coordinate appears to have x and y swapped. Anyway, here's code to perform the conversion:

function toLatLng(x, y, map) { var projected = L.point(y, x).divideBy(6378137); return map.options.crs.projection.unproject(projected); }

Call it like this:

var latLng = toLatLng(6693172.2381477, -264291.81938326, myMap);

You could also work with a library like Proj4js to do projection/unprojection: http://proj4js.org/

like image 135
Liedman Avatar answered Nov 14 '22 01:11

Liedman