[英]Mapbox GL - how to check if a point is inside a rotated bounding box?
我使用 Mapbox GL 來顯示地圖,可以旋轉和縮放。
我需要添加標記,但為了速度,我只想添加當前視圖邊界框內的標記,並在視圖更改時重繪。 (邊界框不是軸對齊的,但可以是一個旋轉的矩形!)
我可以使用map.getBounds()
獲取當前視圖的邊界框。 這將返回 NE 角和 SW 角的 2 個 LngLat 坐標。
如何檢查標記的 LngLat 坐標是否在此框中?
安裝依賴項@turf/boolean-point-in-polygon
然后根據邊界框點創建一個多邊形。
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);
一旦你把你的盒子變成了一個polygon
,使用booleanPointInPolygon
測試你的point
:
const inside = turf.booleanPointInPolygon(point, polygon);
重要提示:為了獲得最佳性能,請確保設置您的多邊形的bbox
屬性, booleanPointInPolygon
內部使用該屬性來快速消除:
let polygon = turf.polygon(coordinates, properties);
if (polygon) {
// booleanPointInPolygon quickly eliminates if point is not inside bbox
polygon.bbox = turf.bbox(polygon);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.