I am working on a project and I want to remove the markers from a leaflet map that were added to the map previously.
The problem is that when I want to remove the markers that were added to the map, instead of removing the markers, they are added every time when the function is called over and over again and the old markers are not removed from the map. The function in which the markers are added is a function in which I want to update the markers with the new positions on the map, deleting the old positions of the markers just before adding the new positions. The function uses ajax to position the markers on the map.
Here is the function:
function updateVehiclePositions()
{
var activeInfoWindow;
var InfoWindow;
for (var i in vehicles)
{
vehicles[i].remove();
}
var siteurlvehicles = "<?php echo JURI::root(); ?>";
var pageUrl = "http://site-otl-joomla/index.php/ro/allcategories-ro-ro/uncategorised/3n/templates/protostar/php";
pageFinalUrl = pageUrl.replace(pageUrl, siteurlvehicles);
$.ajax({
type: "POST",
url: pageFinalUrl + "templates/protostar/php/get_vehicles_xml.php?line=<?php echo $line; ?>",
success: function(vehicles) {
vehicles = JSON.parse(vehicles);
for (var i = 0; i < vehicles.length; i++) {
var icon = vehicles[i].icon;
var iconUrl = "http://site-otl-joomla/index.php/ro/allcategories-ro-ro/uncategorised/3n/templates/protostar/php/img/" + icon;
iconFinalUrl = iconUrl.replace(iconUrl, siteurlvehicles + "templates/protostar/php/img/" + icon);
var image = new L.icon({
iconUrl: iconFinalUrl,
iconSize: [16, 16],
iconAnchor: [8, 8],
popupAnchor: [8, 8]
});
var latLng = L.latLng(vehicles[i].lat, vehicles[i].lng);
var title = vehicles[i].title;
var vehicleId = vehicles[i].vehicleid;
vehicles[vehicleId] = createVehicle(latLng, image, i, title);
if(vehicles[vehicleId]) {
globalMap.removeLayer(vehicles[vehicleId]);
console.log(vehicles[vehicleId]);
}
vehicles[vehicleId].addTo(globalMap);
console.log(vehicles[vehicleId]);
delete image;
}
}
});
setTimeout(function() { updateVehiclePositions(); }, 20000);
}
function createVehicle(point, image, number, title) {
var activeInfoWindow;
var InfoWindow;
var marker = new L.Marker(point, {icon:image});
marker.value = number;
marker.on("click", function() {
var myHTML = title;
if (activeInfoWindow) { activeInfoWindow.close(); }
var infoWindow = L.popup()
.setLatLng(point)
.setContent(myHTML)
.openOn(globalMap);
activeInfoWindow = InfoWindow;
});
return marker;
}
Can you help me with the problem that I have? Where is the mistake in my code?
GET
; usingPOST
should be reserved for times when you are writing/modifying data to your server (there are a few minor exceptions to this rule, of course). Are you possibly able to craft a small reproducible jsfiddle with some static sample data? Ultimately, we want to help you sort this out, but if you manage to self-solve this, please post an answer and explain what you did. – mickmackusa♦ Oct 15 '20 at 10:20