Gmaps Address component types get the name of the country

iam tries to get the country name using the address types available from gmaps V3.

I do not know how I can do it right. http://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingAddressTypes

iam is trying to warn the name of the country that you like here:

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

and here is the code. any help really appreciated. thank

  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);
        }
      });
    }
  }
+3
source share
1 answer

You need to go through the address_component array to find a country type entry. So something like:

// this is just looking at the first result - > results[0]
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") 
        alert (addr.long_name);
}
+4
source

Source: https://habr.com/ru/post/1748690/


All Articles