Search code examples
javascriptjsongeolocationopenstreetmapnominatim

Parsing and Displaying the values from JSON response into HTML


I am trying to find out current city based on the coordinates obtained from Geolocation API of HTML. Here I have hardcoded the coordinates however I am unable to parse and obtain current city.

The API I am using for obtaining the city name is Nominatim. I am not sure where I am going wrong with the code.

<html>
<body>
    <!--<div><button name="locationdiv" onclick="getLocation()">Get Location</button> </div>-->
    <div><button name="citydiv" onclick="getCity()">Current City</button> </div>
</body>    
<script>


    function getCity(){

        const url = "https://nominatim.openstreetmap.org/reverse?format=json&lat=12.93&lon=80.17&zoom=18&addressdetails=1";
        const req = new XMLHttpRequest();
        req.responseType = 'json';
        req.open("GET", url, true);
        req.send();
        var jsonResponse = JSON.parse(req.responseText);
        var newElement2  = document.createElement("div");
        newElement2.innerHTML = Http.responseJSON.address.country;
        document.body.appendChild(newElement2);}

</script>

Solution

  • You seem not to be familiar with the asynchronous nature of a AJAX call. You cannot just post a AJAX call and then expect the XMLHttpRequest object to have it all. You need to define a callback function for the event onreadystatechange in which all the action should take place.

    const url =
      "https://nominatim.openstreetmap.org/reverse?format=json&lat=12.93&lon=80.17&zoom=18&addressdetails=1";
    const req = new XMLHttpRequest();
    req.responseType = "json";
    req.open("GET", url, true);
    req.send();
    req.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var jsonResponse = this.response;
        var newElement2 = document.createElement("div");
        newElement2.innerHTML = jsonResponse.address.country;
        document.body.appendChild(newElement2);
      }
    }

    BTW: There are more modern approaches to 'AJAX' calls then old XMLHttpRequest, namely fetch()