如何从Mapbox GL JS中的geojson源获取唯一要素属性? [英] How to get unique feature properties from geojson source in Mapbox GL JS?

查看:563
本文介绍了如何从Mapbox GL JS中的geojson源获取唯一要素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个地图框 geojson 来源:

I've defined a mapbox geojson source:

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

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

My geojson source file has this structure:

{
"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]
    }},
    ...]
}

我想获得'icon'属性的唯一名称(此处是剧院和音乐).如何遍历源代码以获得这些唯一值?此处的目的是从这些唯一的名称中添加一个图层,以进行过滤.

I would like to get the unique names of the 'icon' properties (here: theatre and music). How can I loop over source to get these unique values? The objective here is to add a layer from these unique names for filtering purposes.

推荐答案

我发现

I found here the answer to my question. Basically, add a layer to the source, use mapbox function queryRenderedFeatures to get the features and then get unique features with the help of dedicated function getUniqueFeatures. After I can loop over uniqueFeatures to print the elements:

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函数:

The getUniqueFeatures function:

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;
}

这篇关于如何从Mapbox GL JS中的geojson源获取唯一要素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆