1

Actually, I am using leaflet map to display city markers when country is clicked. Everything works fine. But, when I click on new country, the previous country markers remain on its position. Now, what I want is that, when I click on a new country, the previous markers has to be removed.

JS code:

function cityMarkers() {
var countryCode = $('#chooseCountry option:selected').val();
$.ajax({
    url: "libs/php/cityMarkers.php", //Getting country specific city data 
    type: 'POST',
    dataType: 'json',
    data: {
        country: countryCode
    },
    success: function(result) {
        
        for(var i=0; i<result.data.length; i++) {
        //it creates array of latitude and longitude of country selected city
            
           let latlng = [result.data[i].lat, result.data[i].lng] 
           
        
        var redMarker = L.ExtraMarkers.icon({
            icon: 'fa-city',
            markerColor: 'red',
            shape: 'square',
            prefix: 'fa'
          });  
          L.marker(latlng, {icon: redMarker}).addTo(mymap); //it populates the city markers

                 
        }
        

    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
    }
})};
2
  • Create separate L.layerGroup for markers and add markers to the group instead of map. Then you can simply use .clearLayers() method to remove old markers before adding the new ones.
    – TomazicM
    Oct 14 at 10:16
  • Thanks. That work for me. @TomazicM Oct 14 at 13:46

Your Answer

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

Browse other questions tagged or ask your own question.