我正在从事一个项目,在该项目中,我使用了与PG中的空间数据库进行通信的node.js服务器,而我的客户端使用mapbox 对他这一边的地图进行可视化处理。按下按钮后,请求将发送到服务器,服务器发送到psql,psql作为结果查询发送到服务器,然后通过socket.io返回客户端,其中我想将我的geoJSON /新几何作为新层放在他的客户端单击按钮后进行映射。 HTML中的客户端地图运行良好,我可以与其进行交互。我在客户端的HTML页面内使用JS。点击按钮后,我需要从那里使用新的几何体更新mapbox地图。
但是我尝试了这段代码,但这在单击按钮后没有任何作用,并且在devTool Chrome控制台中不会显示任何错误:
Equity
即使这不起作用-即使我以静态方式在click函数中设置数据,但此数据以后也会动态更改。如果我将该图层添加到click事件功能范围之外,则该图层可以正常工作,并且该图层会加载到客户端地图上。
请问有什么方法可以动态地向mapbox地图添加图层吗?以后删除而不刷新页面? (我仍然找不到答案,甚至here)
答案 0 :(得分:2)
好吧,我发现了以前从未见过的东西,具体是this。
我最好阅读documentation,并且不可能动态设置新层,但是现在它的工作方式如下/您需要:
您可以根据需要预先设置多个图层,以后可以对其进行更新。
<script>
mapboxgl.accessToken = 'token-from-your-registered-account';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v10',
center: [17.10, 48.14], // starting position on Bratislava
zoom: 11 // starting zoom
});
var geojson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.48369693756104, 37.83381888486939],
[-122.48348236083984, 37.83317489144141],
[-122.48339653015138, 37.83270036637107],
[-122.48356819152832, 37.832056363179625],
[-122.48404026031496, 37.83114119107971]
]
}
}]
};
var geojson2 = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.48369693756104, 37.83381888486939],
[-122.48348236083984, 37.83317489144141],
[-122.48339653015138, 37.83270036637107],
[-122.48356819152832, 37.832056363179625],
[-122.48404026031496, 37.83114119107971],
[-122.48404026031496, 37.83049717427869],
[-122.48348236083984, 37.829920943955045],
[-122.48356819152832, 37.82954808664175],
[-122.48507022857666, 37.82944639795659],
[-122.48610019683838, 37.82880236636284],
[-122.48695850372314, 37.82931081282506],
[-122.48700141906738, 37.83080223556934],
[-122.48751640319824, 37.83168351665737],
[-122.48803138732912, 37.832158048267786],
[-122.48888969421387, 37.83297152392784],
[-122.48987674713133, 37.83263257682617],
[-122.49043464660643, 37.832937629287755],
[-122.49125003814696, 37.832429207817725],
[-122.49163627624512, 37.832564787218985],
[-122.49223709106445, 37.83337825839438],
[-122.49378204345702, 37.83368330777276]
]
}
}]
};
map.on('load', function () {
map.addLayer({
"id": "data-update",
"type": "line",
"source": {
"type": "geojson",
"data": geojson // your previously defined variable
},
"layout": {
"line-join": "round",
"line-cap": "round"
},
"paint": {
"line-color": "#888",
"line-width": 8
}
});
});
$(document).ready(function(){
$('#buttonRun').click(function(e){
map.getSource('data-update').setData(geojson2);
});
});
</script>