Search code examples
javascriptjqueryjsongoogle-maps-api-3google-geocoder

Read attributes of json external link with javascript


Hi I want to do a reverse geocodoing from longitude and lontitude google map api to do that I should add the LonLat to a link to get a JSON structure this the link of JSON file http://maps.googleapis.com/maps/api/geocode/json?latlng=34.0235202,-6.8317697&sensor=true from this link I want to read the attribute

formatted_address

this how I get the JSON file

$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+loca.toString()+'&sensor=true', function(data) { alert(data.results.formatted_address[0]); }); }

but it shows me this error Uncaught TypeError: Cannot read property '0' of undefined

and thank you for helping me


Solution

  • The response from the api looks something like this:

    {
      results: [{
        ...
        formatted_address: "39 Tirle Bank Way, Tewkesbury, Gloucestershire GL20 8ES, UK"
        ...
      },
      ...
      ],
      status: "OK"
    }
    

    You're trying to access formatted_address like an array with [0], when it is actually a string. It's results that is an array. This should work for you if you only care about the first result:

    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+loca.toString()+'&sensor=true', function(data) { 
      if (data.status === 'OK') {
         alert(data.results[0].formatted_address); 
      }
      else {
        alert('Error! ' + data.status)
      }
    });