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 ?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With