I'm using overpass api to fetch informations about hospitals in a certain area. This is the url I use to get the data:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[amenity=hospital](41.862018386633096,12.380561828613283,41.9435317956981,12.612133026123049);way[amenity=hospital](41.862018386633096,12.380561828613283,41.9435317956981,12.612133026123049););out;
Since the hospitals can be also way other than simple nodes, I have to treat them differently so I do this:
fetch(url).then(response => {
return response.json();
}).then(results => {
results.elements.forEach(e => {
console.log('Name '+e.tags["name"])
if(e.type == "way"){
console.log('ID: ' + e.id)
let urlWay = `https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(way[amenity=hospital](${e.id}););out%20center%20meta;`;
fetch(urlWay).then(response=> {
return response.json()
}).then(result => {
lat = result.elements[0].center["lat"]
lon = result.elements[0].center["lon"]
})
} else {
//get lat lon info normally
}
Then I use lat and lon to put a marker on the map.
The explanation for this is that a "way" does not have a single lat-lon information, but it is formed by several nodes. This is an example:
{
"type": "way",
"id": 107248762,
"nodes": [
1233017145,
1233017732,
1233017520,
1233017183,
1233018290,
2144891055,
1233017895,
1233017145
],
"tags": {
"amenity": "hospital",
"wheelchair": "yes"
}
},
So, to get the lat lon informations, I use the "id" property to get the center of the building, by using the urlWay
in the code above, specifying out center meta
. I use elements[0]
because the array has only one element. You can see an example of output by clicking here.
The problem is that, at some point while fetching the informations about the ways and putting markers on the map, the program stops and gives me the error:
SyntaxError: Unexpected token < in JSON at position 0 in overpass api request
I'm assuming (don't know if I'm right) that there is one of these JSON files I get that is not correctly written, so I'm wondering how can I prevent this exception, maybe by just ignoring a bad formatted file.
EDIT: I've modified the code as proposed by user mmd in the answers and worked correctly, so it probably was an error linked to rate limiting.