Mapbox GL js,通过变量图标有效地表示一个 geojson 源

Mapbox GL js, effectively represent a geojson source by a variable icon

我有一个由 geojson 点列表组成的 mapbox 源,这个源的每个元素都有一个键 icon 引用一个图标 URL:

var featureCollection = {
    "type": "FeatureCollection",
    "features": [
        {
            "geometry":{
                "type": "Point",
                "coordinates": [1,1]
            },
            "properties": {
                "id": 1,
                "name": "name1",
                "address": "address1",
                "icon": "icon1"
            }
        },
        {
            "geometry":{
                "type": "Point",
                "coordinates": [2,2]
            },
            "properties": {
                "id": 2,
                "name": "name2",
                "address": "address2",
                "icon": "icon2"
            }
        },
        {
            "geometry":{
                "type": "Point",
                "coordinates": [3,3]
            },
            "properties": {
                "id": 3,
                "name": "name3",
                "address": "address3",
                "icon": "icon3"
            }
        },
        {
            "geometry":{
                "type": "Point",
                "coordinates": [4,4]
            },
            "properties": {
                "id": 4,
                "name": "name4",
                "address": "address4",
                "icon": "icon1"
            }
        }
    ]
}

map.addSource("shops", {
    type: "geojson",
    data: featureCollection,
    cluster: true,
    clusterMaxZoom: 14,
    clusterRadius: 50
});

我想通过 icon 变量来表示我的特征,一种方法是添加尽可能多的层,因为我有不同的图标:

map.addLayer({
    id: currentLayer,
    type: "symbol",
    source: "featureCollection",
    filter: ["!has", "point_count"],
    "layout": {
        "icon-image": currentIcon,
        "icon-size":1.5
    }
});

问题是我有 200 多个不同的图标(800 个观察结果),我真的怀疑创建 200 个不同的图层是否是绘制我的观察结果的最有效方法。特别是当我在用户点击一个图层时触发一个功能时,所以我还必须多次定义这样的功能,因为我有不同的图标。

您可以而且应该只创建一层。 icon-image 支持数据驱动的样式,因此您可以使用 "icon-image": "{icon}"

http://jsbin.com/yofiwizuca/1/edit?html,output

这当然假设您的 Style 中有名为 icon1 的图标,icon2',icon3based on the values of theicon` 属性在您的 GeoJSON 中。

如果需要操作值,也可以使用 https://www.mapbox.com/mapbox-gl-js/style-spec#expressions