I'm trying to add and remove markers dynamically (by clicking on a button) by the following code :
$("#add-marker").click(function () {
var counter = document.getElementById('add-location-field').lastChild.previousSibling;
counter = Number(counter.getAttribute("counter")) + 1;
var latitude_name = "latitude_"+counter;
var longitude_name = "longitude_"+counter;
$("#add-location-field").append(
"<input name="+latitude_name+" type=\"hidden\" counter="+counter+" id="+latitude_name+ " "+ "step=\"any\" id=\"id_latitude\"/>" +
"<input name="+longitude_name+" type=\"hidden\" counter="+counter+" id="+longitude_name+ " " +"step=\"any\" id=\"id_longitude\"/>"
);
markers[counter-1] = new mapboxgl.Marker({draggable: true
})
.setLngLat([0, 0])
.addTo(map);
map.on('mousemove', function (e) {
//TypeError: markers[(counter - 1)] is undefined
var lng_lat = markers[counter-1].getLngLat();
document.getElementById(longitude_name).value= lng_lat.lng;
document.getElementById(latitude_name).value= lng_lat.lat;
});
markers[counter-1].on('dragend', onDragEnd);
});
It is working fine on adding markers and fields to keep lat and long values for each marker. However, removing markers using following code will remove the last marker, raise an error and lock down all the markers:
$("#remove-marker").click(function () {
if (markers.length !== 0){
markers[markers.length-1].remove();
markers.splice(0,1);
}
});
and here is the error :
TypeError: markers[(counter - 1)] is undefined
I've already read the following links :
MapBox clear all current markers
but the purpose here is to remove multiple markers one by one and update markers array on click.