My goal is to obtain the longitude, latitude and name of every country and territory in the world, with the help of Nominatim's API, using JavaScript, in order to add them as tiny and clickable points in a Leaflet world map.
Accessing the url using a browser works fine:
https://nominatim.openstreetmap.org/search?country=SG&format=json
It appears that I am unable to receive any of the console.log
statements, even with one country:
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function () {
if (XHR.readyState == 4 && XHR.status == 200) {
console.log(XHR.responseText);
}
};
XHR.open("GET", "https://www.nominatim.openstreetmap.org/search?country=SG&format=json");
XHR.send();
console.log(XHR);
So, I tried a different method, which failed:
let url = 'https://www.nominatim.openstreetmap.org/search?country=SG&format=json';
fetch(url)
.then(response => response.json())
.then(function (data) {
latitude = data.lat;
longitude = data.lon;
});
console.log(latitude);
console.log(longtitude);
Please guide me on where I went wrong or what other API I can use to achieve my aforementioned target. Thank you.
CodePudding user response:
Lose the www
at the beginning of your URL, nominatim
is a subdomain of openstreetmap
. This is usually done by the web browser automatically, that's why it doesn't happen when you enter the URL in the browser
Working code:
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function () {
if (XHR.readyState == 4 && XHR.status == 200) {
console.log(XHR.responseText);
}
};
XHR.open("GET", "https://nominatim.openstreetmap.org/search?country=SG&format=json");
XHR.send();
console.log(XHR);