1

I've got real time gps positions for a few cars and I want to create a map with updating markers. My code works but it doesn't "update" the markers, instead it adds new objects with new coordinates to the leaflet map. After few minutes my map is full of markers. What I'm doing wrong? Here is my basic concept.

var intervalV = document.getElementById("intervalValue").value * 1000;
document.getElementById("setIntervalButton").onclick = startData;
function startData() {
DataInterval = window.setInterval(getNewData, intervalV);
};

function getNewData() { $.getJSON(server, { fun : "GetGpsData", userId : "user", sessionId : $("#sessionId").val() }, fillMap); } function fillMap(json) { for (var i = 0; i < json.devicesData.length; i++) { var positions = json.devicesData[i].positions.length; var devicepostiion; if (json.devicesData[i].connected == false ) { var devicepostion = L.marker([json.devicesData[i].positions[positions - 1].lat, json.devicesData[i].positions[positions - 1].lon], { icon : offlineCarIcon }, { draggable : false }).addTo(map); } else { devicepostion = new L.marker(, { icon : onlineCarIcon }); devicepostion.addTo(map).setLatLng([json.devicesData[i].positions[positions - 1].lat, json.devicesData[i].positions[positions - 1].lon]).update();

} }

}

1

2 Answers 2

4

It seems you are running the update() on a new marker each time. You should store the marker after you've created it; And then run the update function on this same marker-object every time.

This means you have to store the markers outside of fillMap(). Also, you need to handle the changes in connectivity: when a car goes offline, you have to remove the online marker and create the offline icon, and vv.

1

Making real-time maps is bit complicated by there is a very good library for it here https://github.com/perliedman/leaflet-realtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.