I'm using Leaflet JS to build an interactive map viewer that can track movement of multiple devices. And i'm using JSON data to set Latitude and Longitude for every marker.
The JSON data look like this:
{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.248008","long":"107.004158"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}
The data contain position information from 3 devices.
I already succeed to set marker based on latitude and longitude of devices with for loop. But i can't manage to update the movement of marker with setLatLng and with for
loop. I don't want using clear layer function to add new marker
everytime i get location update, because i need to save movement history
of each devices later. What should i do to make it work? Any suggestion
will be appreciated.
Here is my code. setInterval is meant to run the code
continously. And i tried to use array variable to be marker variable,
and to tag every marker (since using windows[variable_name] is bad
practice).
window.setInterval(function(){
++z;
//alert(z);
function doSomething(data){
jsonBmsData = JSON.parse(data);
}
$.get('get_jsondata.php', doSomething);
if(z == 1){
for(var i=0; i<jsonBmsData.BMS.length; ++i){
marker[i][0] = jsonBmsData.BMS[i].id;
marker[i][1] = jsonBmsData.BMS[i].type;
marker[i][2] = jsonBmsData.BMS[i].lat;
marker[i][3] = jsonBmsData.BMS[i].long;
markerMove[i] = L.marker([marker[i][2],marker[i][3]])
.bindPopup('ID Prajurit = ' + marker[i][0] + '<br>Tipe = ' + marker[i][1]
+ '<br>Lat = ' + [marker[i][2] + '<br>Long = ' + marker[i][3])
.addTo(map);
}
} else if(z > 1){
for(var j=0; i<jsonBmsData.BMS.length; ++i){
marker[j][0] = jsonBmsData.BMS[i].id;
marker[j][1] = jsonBmsData.BMS[i].type;
marker[j][2] = jsonBmsData.BMS[i].lat;
marker[j][3] = jsonBmsData.BMS[i].long;
var newLatLng = new L.latLng(marker[j][2],marker[j][3]);
markerMove[j].setLatLng(newLatLng).update();
markerMove[j]._popup.setContent('ID Prajurit = ' + marker[i][0] + '<br>Tipe = ' + marker[i][1]
+ '<br>Lat = ' + [marker[i][2] + '<br>Long = ' + marker[i][3]);
}
}
},50);