1

I added Mapbox's Geocoder control and the function to have a marker appear in the found location to a map. My problem is that every new search now renders a new marker. What I would like is that once you prompt a new search the old marker disappears and you get a new one. Does this work somehow?

Here is the code I used to add the marker.

var geocoderControl = L.mapbox.geocoderControl('mapbox.places', {keepOpen: false, autocomplete: true});
geocoderControl.addTo(map);


geocoderControl.on('select', function(object){
   var coord = object.feature.geometry.coordinates;
   L.marker([coord[1], coord[0]]).addTo(map);
});
3

You can create a marker first without any location information (and without adding it to the map), then just use .setLatLng to change its location:

var marker = L.marker(false);

geocoderControl.on('select', function(object){
   var coord = object.feature.geometry.coordinates;
   marker.setLatLng([coord[1], coord[0]]).addTo(map);
});

The marker is only created once, and it will be moved each time the geocoder picks a location.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.