Loki
Loki

Reputation: 1205

Leaflet meters to pixels per zoom level

I'm creating an app using Leaflet library

I have a field radius that contains distance in meters (m).

const radius = 1000;

I would need to convert this field to pixels, but on different zoom levels

For zoom levels, I get values from 8 till 18

I have this function that converts successfully on the current zoom level

function disToPixeldistance(distance){
  var l2 = L.GeometryUtil.destination(map.getCenter(),90,distance);
  var p1 = map.latLngToContainerPoint(map.getCenter())
  var p2 = map.latLngToContainerPoint(l2)
  return p1.distanceTo(p2)
}

But I would need to pass different zoom levels as an additional parameter and then convert them from meters to pixels

Like:

function disToPixeldistance(distance, zoomLevel)

Does anyone knows how could I achieve this ? Thank you in advance :)

Upvotes: 0

Views: 657

Answers (1)

Falke Design
Falke Design

Reputation: 11338

Change the map.latlngToContainerPoint(latlng) to map.project(latlng,zoom)

function disToPixeldistance(distance, zoom){
  zoom = zoom || map.getZoom();
  var l2 = L.GeometryUtil.destination(map.getCenter(),90,distance);
  var p1 = map.project(map.getCenter(), zoom)
  var p2 = map.project(l2,zoom)
  return p1.distanceTo(p2)
}

Upvotes: 2

Related Questions