views:

300

answers:

3

hi .. iam trying to get the country name using the Address Component Types available from gmaps V3.

i dont know how i can get it the right way.. http://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingAddressTypes

iam trying to alert the country name liks here :

alert(results[1].address_component[country]);

and here`s the code.. any help is really appreciated..thanks

function codeLatLng() { 
    var input = document.getElementById("latlng").value; 
    var latlngStr = input.split(",",2); 
    var lat = parseFloat(latlngStr[0]); 
    var lng = parseFloat(latlngStr[1]); 
    var latlng = new google.maps.LatLng(lat, lng); 
    if (geocoder) { 
      geocoder.geocode({'latLng': latlng}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
          if (results[1]) { 
          alert(results[1].address_component[country]); 
          } else { 
            alert("No results found"); 
          } 
        } else { 
          alert("Geocoder failed due to: " + status); 
        } 
      }); 
    } 
  } 
A: 

alert(results[1].address_component['country']); // country is a string

bogdanvursu
A: 

hi, this wont work alert(results[1].address_component['country']);

could this be a bug? or am i missing something? does results[1] includes the country name ?!

thanks

gmapsuser
+2  A: 

For one thing, address_components should be plural. The Google documentation is misleading on that due to a typo.

The address_components array has an item for each component of the address. The types array within each item tells you all of the types that apply to each address component (eg: country, locality, etc.) - So what you really want to do is find the address_components array item that has "country" as one of its types, and then take either the short_name or long_name for that array item.

Also, you may not always have a value for results[1]. That would assume there are at least 2 search results returned. results[0] would be the first one.

here's an example:

var country;

for (i=0;i<results[0].address_components.length;i++){
    for (j=0;j<results[0].address_components[i].types.length;j++){
       if(results[0].address_components[i].types[j]=="country")
          country = results[0].address_components[i].long_name
    }
}
Rob Cooney