Get data from Google Autocomplete with JS

Yossef Benharosh is an apt web developer and the author of the eBook The essentials of object oriented PHP.

Yossef Benharosh web developer profile linkedin twitter github

Extract data from google autocomplete

The script populates the fields of an HTML form with the data that comes back from google autocomplete.

The HTML

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YourApiKey&libraries=places"></script>

<form>
  <div class="form-group input-group">
    <label>Start typing the address</label>
    <input type="text" class="form-control" id="formControl" name="full_address" value="" placeholder="Location" autocomplete="off">
    <input type="hidden" id="locality" name="city" value="">
    <input type="hidden" id="route" name="street" value="">
    <input type="hidden" id="street_number" name="data[street_number]" value="">
    <input type="hidden" id="lat" name="data[lat]" value="">
    <input type="hidden" id="lng" name="data[lng]" value="">
  </div>

</form>

 

The JavaScript

<script>
var autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('formControl')),
    {
        types: ['geocode'],
        componentRestrictions: { 'country': 'il' }
    }
);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
	// get the data from google
    var place = autocomplete.getPlace();
	 
	var components={}; 
    jQuery.each(place.address_components, function(k,v1) {jQuery.each(v1.types, function(k2, v2){components[v2]=v1.long_name});});
	
	// populate the fields
	var list = ['locality', 'route', 'street_number'];
	list.forEach(function(fieldName){
		var fieldVal = typeof components[fieldName] !== 'undefined'? components[fieldName] : '';
		jQuery('#'+fieldName).val(fieldVal);
	});
	
	jQuery("#lat").val(place.geometry.location.lat());
    jQuery("#lng").val(place.geometry.location.lng());
	
	// populate the fields
	// pretty address for the user
	var fullAddressStr = '';
	if(typeof components.locality !== 'undefined' && typeof components.route !== 'undefined' && typeof components.street_number !== 'undefined'){
		fullAddressStr = 'street ' + components.route + ' ' + components.street_number + ', ' + components.locality;
	} else if(typeof components.locality !== 'undefined' && typeof components.route !== 'undefined'){
		fullAddressStr = 'street ' + components.route + ', ' + components.locality;
	} else if(typeof components.locality !== 'undefined'){
		fullAddressStr = components.locality;
	}
	
	jQuery('#formControl').val(fullAddressStr);
});
</script>