user3569641
user3569641

Reputation: 922

Getting formatted_address with neighborhood type in Google Maps api - Reverse geocoding

how can I get the formatted_address in Google Maps API with neighborhood type? I'm using Google Maps for reverse geocoding but unfortunately the closest address to my location is the formatted_address with a neighborhood type. Which very hard for me to parse the JSON array since it has many content.

Here's the sample JSON that I got from Google Maps . https://gist.github.com/anonymous/8d5250cfc37a8cef9ab2

when I try to use this:

var geocoder = new google.maps.Geocoder();  

              var point = new google.maps.LatLng(localStorage.latitude, localStorage.longitude);
              geocoder.geocode({ 'latLng': point }, function (results, status) {
                if (status !== google.maps.GeocoderStatus.OK) {
                  alert(JSON.stringify(status));
                }
                // This is checking to see if the Geoeode Status is OK before proceeding
                if (status == google.maps.GeocoderStatus.OK) {
                  console.log(results);
                  var address = (results[0].formatted_address);
                  alert(JSON.stringify(address));
                }
              });

It doesn't give me the closest address. Note: The data on that gist varies on the latitude/longitude but when I check the other address, only the formatted_address with type neighborhood gives me the closest address from the Lat and Lang.

Upvotes: 0

Views: 2649

Answers (1)

darnmason
darnmason

Reputation: 2732

My Javascript is ropey but I guess this is how I would do it:

function getAddress(results) {
    if(results && results.length) {
        for (var i=0; i<results.length; i++) {
            if (results[i].types.indexOf('neighborhood') != -1) {
                return results[i].formatted_address;
            }
        }
        return results[0].formatted_address;
    }
    return '';
}

Upvotes: 2

Related Questions