I'm having a problem with my code. I'm displaying markers on my map, but instead of changing marker positions, it will just add new marker on my map.
I have a printscreen of my problem.
How do I remove the previous marker?
Here's my code:
var latB = 0;
var lonB = 0;
var mark = 0;
var marker = null;
function showOnMap(a){
convert_location(a);
marker = L.marker([latB, lonB]).bindPopup(a);
map.removeLayer(marker)
map.addLayer(marker);
}
function convert_location(a){
var toData = (function (){
var toData = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://nominatim.openstreetmap.org/search?format=json&limit=5&q='+a,
'dataType': 'json',
'success': function(data){
toData = data;
}
});
return toData;
})();
$.each(toData, function(key, val){
latB = val.lat;
lonB = val.lon;
});
}
You are erasing marker after you set a reference to a new one, so basically you are removing non-existing new marker, and then adding it to the map. Marker should be removed from map before it is reassigned.
function showOnMap(a){
convert_location(a);
if (marker != null) map.removeLayer(marker);
marker = L.marker([latB, lonB]).bindPopup(a);
map.addLayer(marker);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.