Reputation: 38
I was trying to make a leaflet map, that gets latitude and longitude data of points and draw them onto the map, then refreshes them.
I am working with Leaflet 1.5.1 and so far I have tried creating a layer, putting the markers inside the layer and cleaning the layer when refreshing the markers.
var map;
var markers = [];
var live_data = [];
var markersLayer = new L.LayerGroup(); // NOTE: Layer is created here!
var updateMap = function(data) {
console.log('Refreshing Map...');
markersLayer.clearLayers();
for (var i = 0; i < live_data.length; i++) {
var heading = live_data[i][3];
var latitude = live_data[i][1];
var longtitude = live_data[i][2];
var aircraft_id = live_data[i][0];
var popup = L.popup()
.setLatLng([latitude, longtitude])
.setContent(aircraft_id);
marker = L.marker([latitude, longtitude], {clickable: true}).bindPopup(popup, {showOnMouseOver:true});
markersLayer.addLayer(marker);
}
}
function GetData() {
$.ajax({
type : 'GET',
url : 'www.filesource.com/file.txt'
})
.done(function(data) {
var lines = data.split('\n'); //Split the file into lines
$.each(lines, function(index, value) { //for each line
if(value.indexOf(':') > 0) { //Go if the line has data in it.
var line_data = value.split(':');
var data_marker = [line_data[0], line_data[5], line_data[6], line_data[45]];
live_data.push(data_marker);
}
});
updateMap();
});
}
$(document).ready(function(){
map = L.map('LiveMap', {
'center': [39.50157442645549, 35.190536499023445],
'zoom': 6,
'layers': [
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
})
]
});
markersLayer.addTo(map);
GetData();
setInterval(GetData, 60000); //every minute
});
The code works fine at first, creates all the markers. However, when data refreshes, more markers are being added without clearing the previous markers. Where am I doing wrong?
Upvotes: 1
Views: 741
Reputation: 53185
While you correctly clear your previous Layers / Markers, you still keep your previous live_data
intact since you only push new data into it and never flush it. Therefore the next call to updateMap will re-create those previous Markers...
Simply set live_data = []
at the beginning of the callback of your GetData request.
Upvotes: 1