javascript - 如何从 Mapbox GL JS 中的 geojson 源获取独特的特征属性?

标签 javascript mapbox mapbox-gl-js

我定义了一个 map 框 geojson来源:

map.addSource("places", {
    type: "geojson",
    data: "http://example.com/myfile.geojson",
});

我的 geojson 源文件具有以下结构:

{
"type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "properties": {
        "icon": "theatre"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-77.038659, 38.931567]
    }},

    {
    "type": "Feature",
    "properties": {
        "icon": "music"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-77.020945, 38.878241]
    }},
    ...]
}

我想获得“图标”属性(此处:剧院和音乐)的唯一名称。我如何遍历源代码以获得这些唯一值?此处的目标是从这些唯一名称中添加一个层以用于过滤目的。

最佳答案

我找到了 here我的问题的答案。基本上,向源添加一个层,使用 mapbox 函数 queryRenderedFeatures 获取特征,然后借助专用函数 getUniqueFeatures 获得独特的特征。在我可以遍历 uniqueFeatures 来打印元素之后:

var features = map.queryRenderedFeatures({layers: ['my_layer']});
var uniqueFeatures = getUniqueFeatures(features, "icon"); 

uniqueFeatures.forEach(function(feature) {
        var prop = feature.properties;
        console.log(prop.icon);
})

getUniqueFeatures 函数:

function getUniqueFeatures(array, comparatorProperty) {
    var existingFeatureKeys = {};
    // Because features come from tiled vector data, feature geometries may be split
    // or duplicated across tile boundaries and, as a result, features may appear
    // multiple times in query results.
    var uniqueFeatures = array.filter(function(el) {
        if (existingFeatureKeys[el.properties[comparatorProperty]]) {
            return false;
        } else {
            existingFeatureKeys[el.properties[comparatorProperty]] = true;
            return true;
        }
    });

    return uniqueFeatures;
}

关于javascript - 如何从 Mapbox GL JS 中的 geojson 源获取独特的特征属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632629/

相关文章:

javascript - 有没有办法随机播放碎片化的 mp4?

javascript - 如何将折线添加到 mapbox.js map ?

javascript - Node.js 中的未知编码错误

javascript - parsley.js 选择列表值为零 - 不起作用

ios - Mapbox iOS 移动归属地按钮

swift - 如何将自定义注释的底部放置在 Mapbox iOS 中的特定坐标上

javascript - MapBox GL CSP 版本不渲染图 block

javascript - 在mapbox-gl-js中,是否可以让 map 的中心不是 Canvas 的中心?

javascript - 如何在mapbox中添加动态标记?

javascript - 正则表达式搞乱了语法突出显示