我正在尝试在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(); }
更新
我尝试了建议的解决方案,但是它不起作用。...:
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);
});
答案 0 :(得分:0)
发生错误是因为您需要指定标记的坐标:
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>);