0

I want to get the value of "city" and "country".

Here's my HTML and javascript code.

I've tried:

  • results.city
  • results["city"] but they don't seem to work; giving me undefined value.
  <pre id="json-result"></pre>
  <p><span id="city"></span></p>
  <p><span id="country"></span></p>

  <script>
    var result = document.getElementById("json-result");
    const Http = new XMLHttpRequest();

    window.addEventListener("load", function () {
      console.log("getLocation Called");
      var bdcApi = "https://api.bigdatacloud.net/data/reverse-geocode-client"

      navigator.geolocation.getCurrentPosition(
        (position) => {
          bdcApi = bdcApi +
            "?latitude=" + position.coords.latitude +
            "&longitude=" + position.coords.longitude +
            "&localityLanguage=en";
          getApi(bdcApi);

        },
        (err) => {
          getApi(bdcApi);
        }, {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0
        });
    })

    function getApi(bdcApi) {
      Http.open("GET", bdcApi);
      Http.send();
      Http.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          result.innerHTML = this.responseText;
          var results = this.responseText
          document.getElementById("city").innerHTML = results.city
        }
      };
    }
  </script>
  • Does this answer your question? [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – SuperStormer Apr 25 '21 at 18:33

1 Answers1

0

You need to convert the API's text response into an actual Javascript object before you attempt to access its members. You can convert JSON text into a Javascript object by using JSON.parse().

Try this instead:

const results = JSON.parse(this.responseText);

(As a side note, if you don't need to support Internet Explorer, you will likely be better off using the newer and easier-to-use fetch instead of XMLHttpRequest.)

Elan Hamburger
  • 2,042
  • 9
  • 14