I’m having an html file location.html and a file with data location.data both on the same webserver in the same directory. the contens of location.data is always the current location data in the form
{"lat":"44.17027","lon":"15.595542","timestamp":"1723663819127","hdop":"2.394","altitude":"510.35","speed":"0.73396146"}
it is written via json_encode() in another php file.
Now I need to read this data in a javascript in location.html into an array to display it on a map via leaflet. (It has to be html)
I just can’t manage to get this done. I tried XMLHttpRequest() with no success. Would appreciate any other (elegant) method.
<script>
var locx = new XMLHttpRequest();
locx.open('GET', 'location.data');
locx.onreadystatechange = function () {
if (locx.readyState === 4 && locx.status === 200) {
var locationData = locx.responseText;
}
};
locx.send();
</script>
2
Answers
If the fetch works (and it should), then the rest will look like this
Working example using PHP to generate JSON
https://plungjan.name/SO/leafletjson
You should be using
fetch()
to get the data via an HTTP GET request from the server and then parse the JSON into a JavaScript object. Then use the information in that object to display a marker on the map (or whatever you want to do) using leaflet.In
fetchLocation()
above there is some stuff I just needed to include to get a working example here on this page (e.g. use POST instead of GET, to allow for the API to return the data I give it etc.). In your case you can leave all that out and just use below code: