我尝试在运行时使用无线电盒将街道地图样式更改为卫星,黑暗,明亮等。但是当我将geojson文件加载到地图时,它仅显示在所选的当前地图样式上。当我更改地图样式时,geoJson文件消失了。有没有办法,即使我改变了样式,我仍可以在所有地图样式中保留geoJson文件?
var map;
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FkaXF1ZSIsImEiOiJjajlrc3V0bjkxaGxlMzNzMjBwdmZ3NmF1In0.KOe_ASpXmNUF_TmN6h2CHw';
map = new mapboxgl.Map({
container: 'map', // container element id
style: 'mapbox://styles/mapbox/light-v9',
center: [90.899, 26.372], // initial map center in [lon, lat]
zoom: 7
});
var layerList = document.getElementById('menu');
var inputs = layerList.getElementsByTagName('input');
function switchLayer(layer) {
var layerId = layer.target.id;
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v9');
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
function loadRails() {
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FkaXF1ZSIsImEiOiJjajlrc3V0bjkxaGxlMzNzMjBwdmZ3NmF1In0.KOe_ASpXmNUF_TmN6h2CHw';
map.addLayer({
id: 'collisions',
type: 'line',
source: {
type: 'geojson',
data: 'testRails.geojson' // replace this with the url of your own geojson
}
}, 'admin-2-boundaries-dispute');
}
&#13;
<html>
<head>
<title>Change a map's style</title>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.1/mapbox-gl.css' rel='stylesheet' />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<br><div id='map'></div><br>
<button style="position:relative;" onclick="loadRails()">load geoJson</button>
<div id='menu' style="position:relative;">
<input id='basic' type='radio' name='rtoggle' value='basic' checked='checked'>
<label for='basic'>basic</label>
<input id='streets' type='radio' name='rtoggle' value='streets'>
<label for='streets'>streets</label>
<input id='bright' type='radio' name='rtoggle' value='bright'>
<label for='bright'>bright</label>
<input id='light' type='radio' name='rtoggle' value='light'>
<label for='light'>light</label>
<input id='dark' type='radio' name='rtoggle' value='dark'>
<label for='dark'>dark</label>
<input id='satellite' type='radio' name='rtoggle' value='satellite'>
<label for='satellite'>satellite</label>
</div>
</body>
</html>
&#13;
答案 0 :(得分:1)
您必须使用新样式再次实例化地图。
// Initially
var map = new mapboxgl.Map({
// Whatever options
style: 'some-style'
});
// On style change, remove map and re-initialize
map.remove();
map = new mapboxgl.Map({
// Options,
style: 'some-other-style'
});
答案 1 :(得分:-1)
我认为,虽然这听起来有点反直觉,但最好还是重绘一下。我在这里引用海报
我已经删除了类级别样式图层和源变量,并且正在重新加载mapViewDidFinishLoadingMap中每个样式更改的数据。虽然不方便,但至少它是这样稳定的。对不起噪音。期待这个功能。
答案 2 :(得分:-1)
我们可以使用“Mapbox js”来更改样式,而无需更改其中的geoJson文件。
添加样式:https://www.mapbox.com/mapbox.js/example/v1.0.0/toggle-baselayers/
添加geoJson文件:https://www.mapbox.com/mapbox.js/example/v1.0.0/geojson-marker-from-url/