kev-dub
kev-dub

Reputation: 41

Mapbox GL JS - Add new marker and remove previous marker

My function is supposed to display a marker over an existing icon (US Cities) when clicked/selected. The marker is an image file. Then when the user clicks on another icon, the previous marker should disappear.

It seems to work fine at first. The first marker is created when the icon is clicked. When the second icon is clicked, the marker is created and the original marker disappears. When a third icon is clicked, the marker does not appear. The console says "marker is not defined".

Here is my code:

map.on('click', 'usa_cities', function(highlightMarker) {
            var markerCoordinates = highlightMarker.features[0].geometry.coordinates.slice();    
            var markerElement = document.createElement('div');
            markerElement.id = 'marker';
            // create the marker
            new mapboxgl.Marker(markerElement)
                .setLngLat(markerCoordinates)
                .addTo(map);
            map.on('click', 'usa_cities', function() {
                marker.remove()
            });      
        }),

Thank you

Upvotes: 0

Views: 1173

Answers (1)

Steve Bennett
Steve Bennett

Reputation: 126687

You don't need to create a new marker each time the user clicks. You can simply call marker.setLngLat(markerCoordinates).

Upvotes: 2

Related Questions