React-mapbox-gl: Does anyone have experience getting viewport radius?

Created on 20 Oct 2017  路  6Comments  路  Source: alex3165/react-mapbox-gl

I been struggling for few weeks now.

Question

Most helpful comment

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'}.

All 6 comments

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'}.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

loverdeveloper picture loverdeveloper  路  3Comments

13milliseconds picture 13milliseconds  路  4Comments

jesster2k10 picture jesster2k10  路  3Comments

faiq picture faiq  路  4Comments

StevanCakic picture StevanCakic  路  3Comments