mapbox根据多边形选择点要素

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

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值