Search code examples
google-mapsgoogle-maps-api-3google-maps-api-2

Google Maps API Fetch Country Code


I'm using Google Autocomplete and would like to pull the Country Code (GB, IE, FR, etc... ) from the location entered on the site.

  AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
    var me = this;
    autocomplete.bindTo('bounds', this.map);
    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
    if (mode === 'ORIG') {
      me.originPlaceId = place.place_id;
      document.getElementById("orig_latitude").value= place.geometry.location.lat();
      document.getElementById("orig_longitude").value= place.geometry.location.lng();
      document.getElementById("country_from").value = place.address_components[1].short_name;
    } else {
      me.destinationPlaceId = place.place_id;
      document.getElementById("dest_latitude").value= place.geometry.location.lat();
      document.getElementById("dest_longitude").value= place.geometry.location.lng();
      document.getElementById("country_to").value = place.address_components[2].short_name;
    }
    me.route();

    });

  };

Unfortunately here the

place.address_components[1].short_name;

is returning the local area where this city/town is located.

How can I get the country code?

Thank you all for your input on this matter, greatly appreciated ;-)


Solution

  • For more details see Place Autocomplete from google

    Fiddle demo

    JS Code:

    var input = document.getElementById('searchTextField');
    var options = {
      types: ['geocode']
    };
    
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      var place = autocomplete.getPlace();
      for (var i = 0; i < place.address_components.length; i += 1) {
        var addressObj = place.address_components[i];
        for (var j = 0; j < addressObj.types.length; j += 1) {
          if (addressObj.types[j] === 'country') { /*outputs result if it is country*/
            document.getElementById('country_shortName').innerHTML = addressObj.short_name
          }
        }
      }
    
    });
    

    Html

    <label for="searchTextField">Please Insert an address:</label>
    <br>
    <input id="searchTextField" type="text" size="50">
    <p >Country Short Code: <span id="country_shortName"></span></p>