简体   繁体   中英

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 ?

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);

也许从边界制作一个多边形并通过turf.js内部函数检查关系。

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM