Skip to content

Instantly share code, notes, and snippets.

@phylsys
Created June 24, 2016 00:05
Show Gist options
  • Save phylsys/31d3344bfdc80efc3fd9ed161c5fbfff to your computer and use it in GitHub Desktop.
Save phylsys/31d3344bfdc80efc3fd9ed161c5fbfff to your computer and use it in GitHub Desktop.
/*========================================================
GOOGLE ADDRESS AUTOCOMPLETE
========================================================*/
$(function(){
var autocomplete,
input = $('#shipping-line1');
// Only IE 9+
if ($.browser.msie && $.browser.version.substr(0,1) < 10)
return false;
// Create the autocomplete object, restricting the search to geographical location types.
autocomplete = new google.maps.places.Autocomplete(input[0], {
types: ['address'],
componentRestrictions: {country: 'us'}
});
// When the user selects an address from the dropdown, populate the address fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace(),
components = place.address_components;
// Function to find an address component by type and short_name/long_name
var find = function (type, name) {
if (typeof name === 'undefined')
name = 'short_name';
var component = components.filter(function(obj) {
return $.inArray(type, obj['types']) !== -1;
});
if (component.length > 0) {
return component[0][name];
}
return '';
};
// Result MUST have a street_number
var street_number = find('street_number');
if (!street_number || street_number === '') {
// HERE'S THE HACK:
// Sometimes Google doesn't return street_number field, but address is correct in the auto-completer
// Use the value from autocomplete to get the street address
street_number = input.val().split(',')[0];
}
else {
// has street number, append route for full street address
street_number += ' ' + find('route');
}
// Trim street address
street_number = $.trim(street_number);
// Autocomplete shipping address fields
input.val(street_number);
$('#shipping-city').val(find('locality', 'long_name'));
$('#shipping-state').val(find('administrative_area_level_1'));
$('#shipping-zip').val((find('postal_code') + '-' + find('postal_code_suffix')).replace(/-\s*$/, ''));
// Phone number?
if (place.formatted_phone_number)
$('#shipping-phone').val(place.formatted_phone_number);
// Company name?
if (place.types && place.name && $.inArray('establishment', place.types) !== -1)
$('#shipping-company').val(place.name);
// Clear and auto-focus on line 2
$('#shipping-line2').val('').focus();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment