本文共 1510 字,大约阅读时间需要 5 分钟。
Mapbox GL JS 对于按空间选择提供了 queryRenderedfeature函数,但是此函数仅支持按点选和标准矩形的框选,不支持按多边形选择。帮助文档中是这样说的:
查询区域的几何图形:描述边界框的单个点或西南和东北点。
因此,想要查询需要借助其他开源库,本文使用Mapbox推荐的turf.js实现
本文实现效果如下:
核心代码:
map2.addControl(draw);map2.on('draw.create', updateArea);map2.on('draw.delete', updateArea);map2.on('draw.update', updateArea);function updateArea(e) { var data = draw.getAll(); var answer = document.getElementById('calculated-area'); if (data.features.length > 0) { var userPolygon = e.features[0]; // generate bounding box from polygon the user drew var polygonBoundingBox = turf.bbox(userPolygon); var southWest = [polygonBoundingBox[0], polygonBoundingBox[1]]; var northEast = [polygonBoundingBox[2], polygonBoundingBox[3]]; var northEastPointPixel = map2.project(northEast); var southWestPointPixel = map2.project(southWest); var features = map2.queryRenderedFeatures([southWestPointPixel, northEastPointPixel], { layers: ['pointslayer'] }); var filter = features.reduce(function(memo, feature) { if (! (undefined === turf.intersect(feature, userPolygon))) { // only add the property, if the feature intersects with the polygon drawn by the user memo.push(feature.properties.FID); } return memo; }, ['in', 'FID']); map2.setFilter("selected", filter); } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert("Use the draw tools to draw a polygon!"); }}
转载地址:http://jgxbi.baihongyu.com/