David
David

Reputation: 835

Mapbox GL-JS: How do I update a marker position?

I have created a marker instance on my map using the following code, but I am unable to figure out how to update the position. I have gotten help here on SO as well as trying to look though Mapbox documentation at no avail. Here is my current code :

var el = document.createElement('div');
el.className = 'marker';
el.id = 'marker1';
el.style.backgroundImage ='url(images/marker.png)';
el.style.width = '10px';
el.style.height = '10px';

new mapboxgl.Marker(el)
.setLngLat([-99, 30])
.addTo(map);

Here is my function that would update the position of the marker on the map :

function setMarker()
{
    marker1.setLngLat([-93.50, 30]);
}

However, when calling the function I only get the following error in the console :

marker1.setLngLat is not a function

What am I doing wrong?

Upvotes: 1

Views: 4547

Answers (1)

jscastro
jscastro

Reputation: 3780

You are not defining marker1 variable. You have to do it like this. Be sure the scope you define marker1 variable is the same the method is

let marker1 = new mapboxgl.Marker(el)
.setLngLat([-99, 30])
.addTo(map);

Then your method setMarker will work

Upvotes: 2

Related Questions