0

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

mapboxgl.Marker how to remove

but the purpose here is to remove multiple markers one by one and update markers array on click.

iliya
  • 514
  • 6
  • 19

1 Answers1

0

It looks like the problem is likely arising from the fact that you could be trying to index into an empty array. I'd recommend logging the values of counter to the console to make sure it is what you expect it to be. Also, with markers[markers.length-1].remove() you're removing the last marker object from the markers array, but with markers.splice(0,1) you're removing the first element from the markers array. Using markers.splice(-1,1) instead should remove the last marker from the array.

I'd also recommend that you consider storing your marker information in a GeoJSON object, rather than in the DOM tree itself. Here is one of many Mapbox GL JS examples which makes use of GeoJSON, for reference.

Adriana Babakanian
  • 1,239
  • 6
  • 8