简体   繁体   中英

Leaflet calculating meters per pixel at zoom level

I am trying to determine a way to calculate the number of meters represented by 1 pixel at a given zoom level and geo centerpoint in Leaflet. Could anyone direct me to the math involved or if there is a way to do this out of the box in leaflet? I am not finding much out there.

You can use the containerPointToLatLng conversion function of L.Map to get the latLngcoordinates for a given pixelcoordinate. If you take one of the first pixel, and one of the next, you can use the distanceTo utility method of L.LatLng to calculate the distance in meters between them. See the following code (assuming map is an instance of L.Map):

var centerLatLng = map.getCenter(); // get map center
var pointC = map.latLngToContainerPoint(centerLatLng); // convert to containerpoint (pixels)
var pointX = [pointC.x + 1, pointC.y]; // add one pixel to x
var pointY = [pointC.x, pointC.y + 1]; // add one pixel to y

// convert containerpoints to latlng's
var latLngC = map.containerPointToLatLng(pointC);
var latLngX = map.containerPointToLatLng(pointX);
var latLngY = map.containerPointToLatLng(pointY);

var distanceX = latLngC.distanceTo(latLngX); // calculate distance between c and x (latitude)
var distanceY = latLngC.distanceTo(latLngY); // calculate distance between c and y (longitude)

That should work, thanks to Jarek Piórkowski for pointing my mistake before the edit.

您可以使用它来计算每像素的米数:

metresPerPixel = 40075016.686 * Math.abs(Math.cos(map.getCenter().lat * Math.PI/180)) / Math.pow(2, map.getZoom()+8);

Take a look at openstreetmap.org page on zoom levels . It gives this formula for calculating the meters per pixel:

The distance represented by one pixel (S) is given by

S=C*cos(y)/2^(z+8) where...

C is the (equatorial) circumference of the Earth

z is the zoom level

y is the latitude of where you're interested in the scale.

Correct me if I am wrong, IMHO, the number of meters per pixel = map height in meters / map height in pixels

function metresPerPixel() {
    const southEastPoint = map.getBounds().getSouthEast();
    const northEastPoint = map.getBounds().getNorthEast();
    const mapHeightInMetres = southEastPoint.distanceTo(northEastPoint);
    const mapHeightInPixels = map.getSize().y;

    return mapHeightInMetres / mapHeightInPixels;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM