I am trying to remove my markers in a MapboxGL map following this question but It doesn't work, it throws:
var marker = new mapboxgl.Marker().addTo(map);
marker.remove();
TypeError: e is undefined
My workflow is to throw a javascript function to remove markers and add new markers,:
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); });
In my last effort I tried this to remove with this but It doesn't work well (The workflow updates randomly markers):
/* remove markers */ var markers = document.getElementsByClassName('marker'); for (i = 0; i < markers.length; i++) { var marker = markers[i]; marker.remove(); }
UPDATE
I tried the suggested solution, but It doesn't work....:
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);
});