Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox GL - how to check if a point is inside a rotated bounding box?

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 ?

like image 996
Dylan Avatar asked Jan 31 '26 05:01

Dylan


1 Answers

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);
like image 58
Clay Avatar answered Feb 01 '26 21:02

Clay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!