0

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?

  • Welcome to JSE Marcel. Please take our tour. As an aside, when you are merely fetching data from a server request use GET; using POST 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 at 10:20
1

After a long period of time, I have managed to find a solution to my problem. I have decided to rewrite the code from scratch.

The code is the following:

<script type="text/javascript">

var vehicles = new Array();

var markersLayer;

function initializeGoogleMap()
{

    var googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}&hl=document.getElementById([<?php echo $lang;?>])',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });

    var googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}&hl=document.getElementById([<?php echo $lang;?>])',{
        maxZoom: 20,
        subdomains:['mt0','mt1','mt2','mt3']
    });

    var map = L.map('map_canvas', {center: [<?php echo $startLat; ?>, <?php echo $startLng; ?>], layers: [googleStreets,googleSat], zoom: 13.5});
    var baseMaps = {
        "Satellite": googleSat,
        "Map": googleStreets
    };

    L.control.layers(baseMaps).addTo(map);
    googleStreets.addTo(map);

    markersLayer = L.layerGroup();
    map.addLayer(markersLayer);


    globalMap = map;

    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;
}

function updateVehiclePositions() {

    var siteurlvehicles = "<?php echo JURI::root(); ?>"; 

    var pageUrl = "http://site-otl-joomla/index.php/ro/allcategories-ro-ro/uncategorised/3n/templates/protostar/php";

    var pageFinalUrl = pageUrl.replace(pageUrl, siteurlvehicles);

    jQuery.ajax({ 
        type: "GET",
        url: pageFinalUrl + "templates/protostar/php/get_vehicles_xml.php?line=<?php echo $line; ?>",
        success: function(vehicleList) {

            vehicles = JSON.parse(vehicleList);
            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;

                var 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 = new 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);

 
                markersLayer.addLayer(vehicles[vehicleId]);
            }
        }
    });
 
    setTimeout(function() { 
        markersLayer.clearLayers(); 
        updateVehiclePositions();
    }, 20000);
}
</script>
| improve this answer | |
0

I suspect it's a problem with the scope of the variable vehicles which you seem to be using as a global variable and also as the parameter to your function which is called on success of the ajax call.

Try replacing the lines:

success: function(vehicles) {

            vehicles = JSON.parse(vehicles);

with

success: function(vehicleList) {

            vehicles = JSON.parse(vehicleList);

UPDATE:

The other problem I think is with your code at

for (var i in vehicles)
{
    vehicles[i].remove();
}

This is iterating over the properties of the vehicles object, and I don't think that that will be the same as iterating through the vehicles array. Try replacing this with

for (var i = 0; i < vehicles.length; i++) {
    vehicles[i].remove();
}

Also you can do a console.log(vehicles) just above these lines to confirm that this variable holds what you expect.

| improve this answer | |
  • Thank you for your answer @Robbie Jackson! I tried your solution, but it doesn't work. – Marcel Stiube Oct 16 at 4:07
  • @MarcelStiube - ok I found another issue and have added that into the answer – Robbie Jackson Oct 16 at 7:53
  • I have made the requested modifications, but it still doesn't work. – Marcel Stiube Oct 19 at 4:05
  • ok, I'll think you'll have to do some javascript debugging - see eg developer.mozilla.org/en-US/docs/Tools/Debugger. Did console.log() give you what you expected? If you get the correct data returned in the ajax call then it's probably not a Joomla issue at all, so posting on this forum may not help. – Robbie Jackson Oct 19 at 8:11
  • I am getting the correct data in the ajax call. I believe that the issue is in these line of code: if(vehicles[vehicleId]) { globalMap.removeLayer(vehicles[vehicleId]); }. The markers doesn't want to be removed by using this function. – Marcel Stiube Oct 21 at 6:45

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.