Mapboxgl JS不会删除标记
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mapboxgl JS不会删除标记相关的知识,希望对你有一定的参考价值。
我试图在这个question之后删除我在MapboxGL地图中的标记,但它不起作用,它抛出:
var marker = new mapboxgl.Marker().addTo(map);
marker.remove();
TypeError: e is undefined
我的工作流程是抛出一个javascript函数来删除标记并添加新标记,:
geojson.features = new_features; /* here code to remove!! */ HERE CODE TO REMOVE! /* add markers to map */ geojson.features.forEach(function(marker) { // create a html element for each feature var el = document.createElement('div'); el.className = 'marker'; // make a marker for each feature and add it to the map var new_marker = new mapboxgl.Marker(el) .setLngLat(marker.geometry.coordinates) .setPopup(new mapboxgl.Popup({offset: 25}) // add popups .setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>')) .addTo(map); });
在我上次的努力中,我尝试使用此删除但它不能正常工作(工作流更新随机标记):
/* remove markers */ var markers = document.getElementsByClassName('marker'); for (i = 0; i < markers.length; i++) { var marker = markers[i]; marker.remove(); }
UPDATE
我尝试了建议的解决方案,但它不起作用....:
let markers = [];
geojson.features.forEach((feature) => {
let marker = new mapboxgl.Marker().setLngLat(feature.geometry.coordinates).addTo(map);
markers.push(marker);
});
// clear markers array
markers.forEach((marker) => marker.remove())
geojson.features = features;
geojson.features.forEach(function(marker) {
// create a HTML element for each feature
var el = document.createElement('div');
el.className = 'marker';
//el.setAttribute("longitude",marker.geometry.coordinates[0].toString());
//el.setAttribute("latitude",marker.geometry.coordinates[1].toString());
// make a marker for each feature and add it to the map
var new_marker = new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({offset: 25}) // add popups
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
});
答案
发生错误是因为您需要指定标记的坐标:
let marker = new mapboxgl.Marker().setLngLat([30.5, 50.5]).addTo(map);
之后,您可以删除标记:
marker.remove();
在您的情况下,您可以将所有标记保存到阵列,然后删除每个标记:
var markers = [];
function drawMarkers(features){
clearMarkers();
features.forEach((feature) => {
let marker = new mapboxgl.Marker()
.setLngLat(feature.geometry.coordinates)
.setPopup(new mapboxgl.Popup()
.setHTML(`<h3>${feature.properties.title}</h3><p>${feature.properties.description}</p>`))
.addTo(map);
markers.push(marker)
});
}
function clearMarkers(){
markers.forEach((marker) => marker.remove());
markers = [];
}
drawMarkers(<YOUR FEAUTURES>);
以上是关于Mapboxgl JS不会删除标记的主要内容,如果未能解决你的问题,请参考以下文章