Apologies for the basic question, but I'm struggling with understanding JavaScript and json files. I have a .json file that updates server object locations every 5 seconds, and I want to plot these coordinates on a map using leaflet for staff access.
Currently, I've used PHP to decode the json file, extract the coordinates, and plot markers on the map. However, I'd like to implement live marker updates without refreshing the page when the json file changes.
This is the PHP code I'm currently using:
<?php
$count = 0;
$str = file_get_contents('coords.json');
$json = json_decode($str, true);
foreach($json['coords'] as $coords) {
$count++;
${'yCord_'.$count} = $coords['y'];
${'xCord_'.$count} = $coords['x'];
};
for ($i = 1; $i <= $count; $i++) {
echo "L.marker([" . ${'xCord_'.$i} . "," . ${'yCord_'.$i} . "], {icon: icon_door}).addTo(map);";
}
?>
However, after researching, it seems updating live with just PHP isn't possible, so I've started working on a solution using JS. Here's what I have so far:
$.getJSON( "coords.json", function(json1) {
for (var i = 0; i < json1.coords.length; i++) {
var place = json1[i];
// Creating a marker and putting it on the map
var customIcon = L.icon({
iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
iconSize: [38, 40],
iconAnchor: [10, 40],
popupAnchor: [5, -40]
});
var marker = L.marker([place.x, place.y], {icon: customIcon});
}
});
It seems I'm having trouble extracting specific data from my json file, as other examples I've found online have different structures. My json file (coords.json) looks like this:
{
"coords": {
"1": {
"x": 21249,
"y": 7135
},
"2": {
"x": 21249,
"y": 7125
},
"3": {
"x": 21244,
"y": 7140
}
}
}
The number of coordinates in the json file may vary depending on the number of objects. Any guidance would be greatly appreciated.