Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to get JSON data from Nominatim's API

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading