3

I use Mapbox GL to display a map, which can be rotated and zoomed.

I need to add markers, but for speed I only want to add markers that are within the bounding box of the current view, and redraw if the view changes. (The bounding box is NOT axis-aligned, but can be a rotated rectangle!)

I can get the bounding box of the current view with map.getBounds(). This returns 2 LngLat coordinates for the NE-corner and SW-corner.

How can I check if the LngLat coordinates of a marker are inside this box ?

Dylan
  • 9,129
  • 20
  • 96
  • 153
  • 3
    Possible duplicate of [Determine if point is within bounding box](https://stackoverflow.com/questions/18295825/determine-if-point-is-within-bounding-box) – xmojmr Aug 24 '17 at 15:04
  • Not a duplicate, that answer only works for an axis-aligned bounding box – Dylan Aug 25 '17 at 10:53

3 Answers3

1

Install the dependency @turf/boolean-point-in-polygon then create a polygon based on the bounding box points.

import booleanPointInPolygon from '@turf/boolean-point-in-polygon';
const bounds = map.getBounds();
const boundsGeometry = polygon([
  [
    [bounds.getNorthWest().lng, bounds.getNorthWest().lat],
    [bounds.getNorthEast().lng, bounds.getNorthEast().lat],
    [bounds.getSouthEast().lng, bounds.getSouthEast().lat],
    [bounds.getSouthWest().lng, bounds.getSouthWest().lat],
    [bounds.getNorthWest().lng, bounds.getNorthWest().lat]
  ]
]);
booleanPointInPolygon(yourPoint, boundsGeometry);
Clay
  • 4,700
  • 3
  • 33
  • 49
0

Maybe make a polygon from bounds and check relation by turf.js with inside function.

0

Once you've made your box into a polygon, test your point using booleanPointInPolygon:

const inside = turf.booleanPointInPolygon(point, polygon);

IMPORTANT: For best performance be sure to set your polygon's bbox property which booleanPointInPolygon uses internally for quick elimination:

let polygon = turf.polygon(coordinates, properties);
if (polygon) {
    // booleanPointInPolygon quickly eliminates if point is not inside bbox
    polygon.bbox = turf.bbox(polygon);
}
Ken Lin
  • 1,819
  • 21
  • 21