I been struggling for few weeks now.
I've done this with point-geometry and turf libraries. Get your viewport width (x) and viewport height / 2 (y) for the edge then...
const point = map.unproject(new Point(x, y));
const center = map.getCenter();
const distanceInMetres = turf.distance(
[point.lng, point.lat],
[center.lng, center.lat],
'meters',
);
This should return the distance from edge of the screen to the center in meters.
@alex3165 @4xDMG I was able to calculate radius. But for the data i am working with, viewport based polyon is better option for me. How do i get lat:lng of 4 corners of the viewport screen?
I think you can use mapbox gl-js's map.getBounds() method to get SW and NE lngLat of the viewport.
To get the remaining two corners you can just take the lng from SW and the lat from NE for the SE point and the opposite for the NW point.
@4xDMG THAT WORKED GREAT. THANKS.
Now how do i get the center of Polygon ? haha sorry
@suyesh, You can use the turf.js centerOfMass function to get the centerOfMass of a polygon.
I've done this with point-geometry and turf libraries. Get your viewport width (x) and viewport height / 2 (y) for the edge then...
const point = map.unproject(new Point(x, y)); const center = map.getCenter(); const distanceInMetres = turf.distance( [point.lng, point.lat], [center.lng, center.lat], 'meters', );This should return the distance from edge of the screen to the center in meters.
In case anyone comes across this, the third parameter for the distance() method in the latest version of turf is an options object, so you'll want to replace 'meters' with {units: 'meters'}.
Most helpful comment
In case anyone comes across this, the third parameter for the
distance()method in the latest version of turf is anoptionsobject, so you'll want to replace'meters'with{units: 'meters'}.