Google Address AutoComplete

by douglasloyo

HTML

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;libraries=places&amp;key=AIzaSyAAPSF-20T1zv73ucdh_EzWXm0pHhZM3GE"></script>
<input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text" />

<p>
    <label>Street address</label>
    <input id="street_number" disabled="true" />
    <input id="route" disabled="true" />
</p>
<p>
    <label>City</label>
    <input id="locality" disabled="true" />
</p>
<p>
    <label>State</label>
    <input id="administrative_area_level_1" disabled="true" />
    <label>Zip code</label>
    <input id="postal_code" disabled="true" />
</p>
<p>
    <label>Country</label>
    <input id="country" disabled="true" />
</p>

<p>
    <h2>JSON result</h2>
    <textarea id="log" style="width:300px; height:200px;"></textarea>
</p>

JavaScript

// This example displays an address form, using the autocomplete feature of the Google Places API to help users fill in the information.

var placeSearch, autocomplete;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

//This would go on <body onload="initialize()"
initialize();

function initialize() {
  // Create the autocomplete object, restricting the search to geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      (document.getElementById('autocomplete')),
      { types: ['geocode'] }
  );
    
  // Add event handler...
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    fillInAddress();
  });
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
  document.getElementById("log").value = JSON.stringify(place);

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
      autocomplete.setBounds(new google.maps.LatLngBounds(geolocation,
          geolocation));
    });
  }
}