Jimmy
Jimmy

Reputation: 12527

Google Geocoding - Grab Address along with coordinates

So this is what I am after, and I've been told it isn't possibly but I am not going to give up just yet!

Let's say the user types in "London" into my location search box and clicks "Geocode" I am able to get the co-ordinates of that location a bit like this example:

http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/v3-geocoder-tool.html

But lets say that I have the following fields:

Town:
City:
Country:
Long:
Lat:

Is it possible to have all these fields filled in by this request, not just the co-ordinates? For example, I would have the following information which I could then store in a cookie:

Town: -
City: London
Country: UK
Long: 123.45
Lat: 123.45

Upvotes: 2

Views: 1018

Answers (1)

Yaqub Ahmad
Yaqub Ahmad

Reputation: 27659

try this:

function getLatLongDetail(latLng) {

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'latLng': latLng },
      function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              if (results[0]) {

                  var address = "", city = "", state = "", zip = "", country = "";


                  for (var i = 0; i < results[0].address_components.length; i++) {
                      var addr = results[0].address_components[i];
                      // check if this entry in address_components has a type of country
                      if (addr.types[0] == 'country')
                          country = addr.long_name;
                      else if (addr.types[0] == 'street_address') // address 1
                          address = address + addr.long_name;
                      else if (addr.types[0] == 'establishment')
                          address = address + addr.long_name;
                      else if (addr.types[0] == 'route')  // address 2
                          address = address + addr.long_name;
                      else if (addr.types[0] == 'postal_code')       // Zip
                          zip = addr.short_name;
                      else if (addr.types[0] == ['administrative_area_level_1'])       // State
                          state = addr.long_name;
                      else if (addr.types[0] == ['locality'])       // City
                          city = addr.long_name;
                  }


                  alert('City: '+ city + '\n' + 'State: '+ state + '\n' + 'Zip: '+ zip + '\n' + 'Country: ' + country);

              }

          }

      });
}

EDIT:

Sample example is here.

Upvotes: 6

Related Questions