kamfulebu kamfulebu - 4 days ago 5
Javascript Question

Leaflet: delete layer after 'moveend' command, then that this same layer re-added

How to delete layer after 'moveend' command, then that this same layer re-added?

Details:

I want to add over 60,000 points in the leaflet from MySQL, using getJSON. Considering to the large number of points I want to display only points in the BBOX. First sends BBOX coordinates in MySQL:

map.on('moveend', function() {
$.ajax({
type: "POST",
url: "storeCoordinateBBOX.php",
data: { sjever: map.getBounds()._northEast.lat, jug: map.getBounds()._southWest.lat, zapad: map.getBounds()._southWest.lng, istok: map.getBounds()._northEast.lng}
}).done(function( msg ) {
//alert( msg );
});
});


Then select only the points that are located within the BBOX.

PHP (get_address.php)

$sql = "SELECT objectid, ulica, kb, ( Y(SHAPE)) AS lat, ( X(SHAPE)) AS lng FROM bl_tacke_adrese WHERE ( Y(SHAPE) ) > $jug AND ( Y(SHAPE) ) < $sjever AND ( X(SHAPE) ) > $zapad AND ( X(SHAPE) ) < $istok;";


After that, the selected data add to leaflet:

address = new L.LayerGroup();
[...]

function getUsers_ostalo() {
map.on('moveend', function(){
// map.removeLayer(address) ;
$.getJSON("get_address.php", function podaci(data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var objectid = "<div style='font-size: 12px; text-align: left; margin-left: auto; margin-right: auto;'><b style='font-size: 12px;'>ID Lokacije: </b>"+ data[i].objectid +"</div>";
var ulica = "<div style='font-size: 12px; text-align: left; margin-left: auto; margin-right: auto;'><b style='font-size: 12px; text-align: left;'>Ulica: </b>"+ data[i].ulica +"</div>";
var kb = "<div style='font-size: 12px; text-align: left; margin-left: auto; margin-right: auto;'><b style='font-size: 12px; text-align: left;'>Kb: </b>"+ data[i].kb +"</div>";

var marker = new L.Marker(location, {
title: data[i].tipovi,
icon: ostalo_icon
});
marker.bindPopup("<div>"+ objectid + ulica + kb + "</div>", {maxWidth: '400', maxHeight: '400'});
marker.addTo(address);
}
})
});
}


All this is working properly. The problem is that when moving map added a new points but are not deleted already existing (which are loaded previous moving map). I wish that every time moving the map first clean up map (removeLayer), then I add again the same layer. Is that possible?
I have tried insert 'map.removeLayer (address);' after 'map.on ('Moveendi', function () {...' but then deletes layer and does not add it back.

Answer

When the map starts moving clear the layer:

map.on("movestart", function() {
   address.clearLayers();
});

than when the move ends add the new markers:

map.on("moveend", function() {
   // ..
   marker.addTo(address);
});
Comments