Mapbox-GL setStyle removes layers

为君一笑 提交于 2020-03-17 06:55:50

问题


I'm building a mapping web application using Mapbox-GL. It has a lot of cool features. I've set up the buttons to switch base maps (ie. satellite, terrain, etc) following the example on the Mapbox website.

The problem that I am having is that when I change the style it removes my polygons that are loaded as layers and reloads the map. I load in polygons from a Mongo database as layers based on user queries. I want to be able to change the base map and keep those layers.

Is there a way to change the style without reloading the map, or at least not droping the layers?

Here is my code for the switcher, its the same as the example but I added a condition for a custom style:

 var layerList = document.getElementById('menu');
    var inputs = layerList.getElementsByTagName('input');

    function switchLayer(layer) {
        var layerId = layer.target.id;
        if (layerId === 'outdoors') {
            map.setStyle('/outdoors-v8.json');
        } else {
        map.setStyle('mapbox://styles/mapbox/' + layerId + '-v8');
        }
    }

    for (var i = 0; i < inputs.length; i++) {
        inputs[i].onclick = switchLayer;
    }

回答1:


Here's an example demonstrating that: http://bl.ocks.org/tristen/0c0ed34e210a04e89984

Unlike a mapping library like Leaftlet, Mapbox GL JS doesn't have a concept of "basemap" vs "other layers." All layers are part of the same entity: the style. So you need to keep some state of the data layer around and call its source/addLayer on each change.




回答2:


Maybe I am late, but just for the record:

  • style.load is not part of the public API
  • use map.on('styledata') to monitor the style change

Please reference:

  • https://github.com/mapbox/mapbox-gl-js/issues/6210
  • https://github.com/mapbox/mapbox-gl-js/issues/3970#issuecomment-275722197


来源:https://stackoverflow.com/questions/36168658/mapbox-gl-setstyle-removes-layers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!