成果图
参考博客
https://blog.csdn.net/ScapeD/article/details/89158755
原理与源码
利用mapbox的queryRenderedFeatures方法可以获取范围内的要素,但是这个只能是点和矩形和范围内的全屏要素,并不支持多边形,所以实现这个的思路就是画完框子的时候,取框的外接矩形来获取要素,缩小范围,然后再从获取到的所有要素里面逐一和多边形对比,利用turf的是否包含和相交来判断,进一步缩小范围,得到我们最终的要素。
最后再设置一下框选到的要素的样式就可以了。
let polygonBoundingBox = turf.bbox('你的geojson')
let southWest = [polygonBoundingBox[0], polygonBoundingBox[1]];
let northEast = [polygonBoundingBox[2], polygonBoundingBox[3]];
let northEastPointPixel = map.project(northEast);
let southWestPointPixel = map.project(southWest)
const features = map.queryRenderedFeatures(
[southWestPointPixel, northEastPointPixel]
);
let filter = []
features.forEach(e=>{
if(turf.booleanContains('你的geojson',e.geometry)==true||turf.booleanDisjoint('你的geojson',e.geometry)==false){
filter.push(e)
}
})
if(filter.length>0){
filter.forEach(res=>{
map.setFeatureState(
{ source: res.source, id: res.id },
{ select: true }
);
})
}