I have been working on a Leaflet map project with markers. The markers' latlng data is fetched from JSON and displayed correctly.
I tried using setInterval to refresh the method every 5 seconds to update the latlng positions, ensuring that old markers are hidden and new position markers are shown without duplicates. However, despite trying various options, I have not been successful in achieving this.
The image below illustrates the issue of duplicate aircraft markers on the map when using setInterval to update the positions. Can anyone offer assistance?
https://i.sstatic.net/BH7I4.png
Below is my code:
$(document).ready(function () {
var markers = {}; // Dictionary to store markers in an outer scope.
// Map initialization
var coords = [33, 44]; // the geographic center of our map
var zoomLevel = 6; // the map scale.
var map = L.map('map').setView(coords, zoomLevel);
L.tileLayer('https://{s}.tile.thunderforest.com/transport-dark/{z}/{x}/{y}.png', {
attribution: 'Map data ©',
maxZoom: 18
}).addTo(map);
// Aircraft data
setInterval(function () {
$.ajax('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', {
type: 'GET',
dataType: 'jsonp',
timeout: 5000
}).done(function (data, textStatus, jqXHR) {
Object.keys(data)
.map(key => data[key])
.map((position) => ({
lat: position[1],
lng: position[2],
})).filter(position =>
position.lat &&
position.lng &&).forEach(i => {
if (!markers[i.lat, i.lng]) {
// Create a new marker if there is no existing one with this id.
markers[i.lat, i.lng] = L.marker([i.lat, i.lng]).addTo(map);
}
markers[i.lat, i.lng].setLatLng(i.lat, i.lng);
})
}, 5000)
});
});