Removing all data/markers in Leaflet map before calling another JSON

You should not be re-creating the markersLayer object. What you want is to create it once, and then continue to add/remove markers from it.

In your line where you define the markersLayer at the top of the file, you now also want to define it here as an L.LayerGroup. We will not be re-creating this object.

When you want to update the map, you will clear all the existing markers from the markersLayer. This is accomplished by calling markersLayer.clearLayers(). This will not remove the markersLayer from the map. It will only remove the markers this layer contains.

Once all of the markers have been removed from this layer, you are now free to add new layers to markersLayer.

Your code will look like this:

var map;
var markers = [];
var markersLayer = new L.LayerGroup(); // NOTE: Layer is created here!
var updateMap = function() {
  // NOTE: The first thing we do here is clear the markers from the layer.
  markersLayer.clearLayers();

  var uri = $('input.location:checked').val() + '.json';
  $.getJSON(uri, function(response){
    $('ul#location-list').empty();


    var locationCoor = []; 
    var marker;

    for(var i=0; i < response.length; i++){

        var lat = response[i].latitude;
        var lon = response[i].longitude;
        $('ul#location-list').append('<li>(' + lat + ', ' + lon + ')</li>');
        //console.log(lat, lon);
        locationCoor[i] = [lat, lon];
        //console.log(locationCoor);

        var popup = L.popup()
            .setLatLng([lat, lon])
            .setContent('<h3 style="margin:0 0 3px 0;"><a href="' + response[i].link + '">' + response[i].title + '</a></h3><img width="180px" height="auto" src="' + response[i].imageUrl + '">');

        marker = L.marker([lat, lon], {
            clickable: true
        }).bindPopup(popup, {showOnMouseOver:true});

        markersLayer.addLayer(marker); 
        console.log(markers);
    }

    // NOTE: We are no longer recreating the layer here. Remove these lines of code.
    //markersLayer = L.layerGroup(markers);
    //markersLayer.addTo(map);




    var bounds = new L.latLngBounds(locationCoor);
    map.fitBounds(bounds, {padding: [50,50]});
    markers.length = 0;
});
};

$(document).ready(function(){
map = L.map('map');
L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i87786ca/{z}/{x}/{y}.png', {
    maxZoom: 18,
    id: 'examples.map-20v6611k'
}).addTo(map);

// NOTE: We add the markersLayer to the map here. This way, the layer is only added once.  
markersLayer.addTo(map);

$('input.location').on('change', updateMap);
updateMap();
});

Refer : Removing leaflet layers and L.marker method

Basic concept : Instead of adding all markers directly on the map, you can add the markers on a separate layer (i.e. var markers = new L.FeatureGroup();) and then add that layer on the map (map.addLayer(markers);) outside the loop.

JSFiddle

Tags:

Json

Leaflet