【问题标题】:In Mapbox.js, how to switch between different map style?在 Mapbox.js 中,如何在不同的地图样式之间切换?
【发布时间】:2015-03-13 09:00:08
【问题描述】:
【问题讨论】:
标签:
javascript
dictionary
mapbox
【解决方案1】:
需要明确的是,使用栅格切片图层切换“地图样式”意味着加载全新的切片图层。您在 MapBox 的浏览器编辑器上看到的是 15 种不同的可能的切片图层(一次只渲染一个)。因此,创建一个新样式意味着创建一个全新的项目(即,取决于你如何实现它,一个新的.mbtiles 文件,或者你的 tileserver 上的一个新项目)。
因此,为了回答您的问题,可以使用 map.removeLayer() 和 map.addLayer() 方法 (see the docs) 从地图中添加/删除新的切片图层。
基于浏览器的渲染,使用客户端应用的样式,而不是硬烘焙到瓦片集中,可以使用矢量瓦片和mapbox-gl 库,尽管mapbox-gl 还没有leaflet 成熟/mapbox.js.
【解决方案2】:
我使用类似下一段代码来更改地图样式。此代码在加载新地图样式的第一个图块后切换当前地图样式并删除旧地图。
L.Map.include({
_mapStyleLayerTileLoad:function(){
this._stylesLayer.getLayers()
.filter(function(layer){
return this._currentStyleLayer!==layer;
},this)
.forEach(function(layer){
if (layer!==this._currentStyleLayer) {
this._stylesLayer.removeLayer(layer);
}
},this);
this._currentStyleLayer.off("tileload",this._mapStyleLayerTileLoad,this);
},
setMapStyle:function(style) {
if (!style) {
return;
}
if (!this._stylesLayer) {
this._stylesLayer=L.layerGroup([]).addTo(this);
}
if (this._currentStyleLayer) {
this._currentStyleLayer.off("tileload",this._mapStyleTileLoad);
}
var layer=L.mapbox.tileLayer(style)
if (this._currentStyleLayer) {
layer.on("tileload",this._mapStyleLayerTileLoad,this);
}
layer.addTo(this._stylesLayer);
this._currentStyleLayer=layer;
return this;
}
});