Mapbox图层具有重复的ID

时间:2019-06-07 11:02:42

标签: javascript mapbox mapbox-gl-js

我正在使用Mapbox-GL-JS构建一个Web应用程序,它使用Mapbox Studio拼贴集来添加图层作为图层。但是,当我访问该图层时,多个功能似乎正在接收相同的ID。

https://github.com/mapbox/mapbox-gl-js/issues/8284 这里提到这是由于我的数据,但是数据集中没有ID字段: https://www.dropbox.com/s/5ci0hosqakvdahx/townships.json?dl=0

https://jsbin.com/cuhewomepo/1/edit?html,js,output

map.on("mousemove", "gemeentes", function (e) {
    if (e.features.length > 0) {
        if (hoverGemeenteId) {
            map.setFeatureState({
                source: 'gemeentes-src',
                sourceLayer: 'townships-0u4ffk',
                id: hoverGemeenteId
            }, {hover: false});
        }
        hoverGemeenteId = e.features[0].id;
        console.log(hoverGemeenteId);
        map.setFeatureState({
            source: 'gemeentes-src',
            sourceLayer: 'townships-0u4ffk',
            id: hoverGemeenteId
        }, {hover: true});
    }
});

遵循以下项目示例: https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/

每当一个乡镇悬停时,它都会更改颜色,但是,由于有多个具有相同ID的乡镇,因此多个区域会亮起,而不仅仅是被悬停的乡镇。

编辑: 当我运行以下代码时:

const filtered = map.querySourceFeatures('gemeentes-src', {
        sourceLayer: 'townships-0u4ffk',
        filter: ['>=', ['id'], 0]
    });

清楚地表明,有多个具有相同ID的功能,并且没有ID超过249。这几乎就像是有250个上限,而新功能又从0开始。

1 个答案:

答案 0 :(得分:2)

添加源时,可以使用选项promoteId为基于属性的功能分配唯一ID。

https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId

例如(from the PR that added this feature to MapboxGL):

map.addSource('counties', {
    "type": "vector",
    "url": "mapbox://mapbox.82pkq93d",
    "promoteId": {"original": "COUNTY"}
});
...
map.setFeatureState({
    source: 'counties', 
    sourceLayer: 'original', 
    id: 'Marin County' // reference a feature by a county name for feature-state
}, {hover: true});
相关问题