【问题标题】:How to hide point labels at certain zoom levels in mapbox-gl-js?如何在 mapbox-gl-js 中以某些缩放级别隐藏点标签?
【发布时间】:2017-03-02 09:37:32
【问题描述】:

我正在使用 mapbox-gl-js 将 geojson 文件中的点渲染到地图上。

对于每个点,我还在标记图标下方显示一个标签。我目前使用以下代码执行此操作:

map.addSource("mypoints", {
    type: "geojson",
    data: "mypoints.geojson",
});

map.addLayer({
    "id": "layer-mypoints",
    "type": "symbol",
    "source": "mypoints",
    "layout": {
        "icon-image": "marker-15",
        "text-field": "{name}",
        "text-anchor": "top"
    }
});

这按预期工作,点被添加到地图中,标签在每个点下呈现。

为了使地图不那么混乱,我想在地图缩小到某个缩放级别时隐藏标签(反之亦然,在地图放大时显示标签)。无论缩放级别是多少,我总是想显示点图标。

【问题讨论】:

    标签: mapbox mapbox-gl-js


    【解决方案1】:

    如果您不想要多层,我可以使用另一种解决方法。

    根据您的原始代码,您可以将text-size 属性与缩放相关stops 一起使用:

    map.addSource("mypoints", {
        type: "geojson",
        data: "mypoints.geojson",
    });
    
    map.addLayer({
        "id": "layer-mypoints",
        "type": "symbol",
        "source": "mypoints",
        "layout": {
            "icon-image": "marker-15",
            "text-field": "{name}",
            "text-anchor": "top",
            "text-size": {
                "stops": [
                    [0, 0],
                    [3, 0],
                    [4, 10]
                ]
            }
        }
    });
    

    该值在停靠点之间插值,因此在缩放 0 和 3 之间,text-size 在 0 和 0 之间插值,导致... 0(即不存在)。从缩放 3 开始,它使文本具有放大到缩放 4 的效果(我喜欢这种效果,但这是个人的)。从缩放 4 开始,text-size 将保持在 10。如果您不希望在缩放 3 和 4 之间产生“扩大”效果,您还可以指定小数缩放:只需将 4 更改为 3.1。

    【讨论】:

    • 为我工作!此时,无法分层,因此,求最优解!谢谢!
    • 同样适用于“text-opacity”“paint”属性,这对我来说是最好的解决方案。 ??
    【解决方案2】:

    在做了更多思考/阅读/测试之后,我想我找到了解决问题的方法。

    我现在添加一个仅显示图标的图层,并添加第二个仅包含标签的图层。在第二层中,我将“minzoom”属性设置为用户放大地图时希望标签出现的缩放级别。

    map.addSource("mypoints", {
        type: "geojson",
        data: "mypoints.geojson",
    });
    
    
    // Layer with icons that should always be visible
    map.addLayer({
        "id": "layer-mypoints",
        "type": "symbol",
        "source": "mypoints",
        "layout": {
            "icon-image": "monument-15",
            "icon-allow-overlap": true
        }
    });            
    
    // Layer with just labels that are only visible from a certain zoom level
    map.addLayer({
        "id": "layer-mypoints-label",
        "type": "symbol",
        "source": "mypoints",
        "minzoom": 12, // Set zoom level to whatever suits your needs
        "layout": {
            "text-field": "{name}",
            "text-anchor": "top",
            "text-offset": [0,0.5]
        }
    });
    

    这似乎非常适合我的需求。

    【讨论】:

      猜你喜欢
      • 2020-07-16
      • 1970-01-01
      • 2019-10-28
      • 2015-08-12
      • 2016-12-23
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2020-01-08
      相关资源
      最近更新 更多