Created
February 3, 2014 19:15
-
-
Save jabes/8790381 to your computer and use it in GitHub Desktop.
Populate a form input using Twitter Bootstrap's typeahead and the Google places autocomplete service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getAddressComponents(address_components) { | |
var result = {}, | |
allowable_types = ['country', 'locality', 'postal_code', 'route', 'street_number', 'administrative_area_level_1'], | |
type_aliases = { | |
administrative_area_level_1: "region" | |
}; | |
$.each(address_components, function (index, value) { | |
var type = value.types[0]; | |
if (allowable_types.indexOf(type) >= 0) { | |
if (type_aliases.hasOwnProperty(type)) { | |
type = type_aliases[type]; | |
} | |
result[type] = value.long_name; | |
} | |
}); | |
return result; | |
} | |
function registerLocationAutoFill(input_selector, cb) { | |
var input_elm = $(input_selector), | |
init_value = input_elm.val(); | |
input_elm.typeahead({ | |
source: function(query, process) { | |
window.googleApi.autocompleteService.getPlacePredictions({ | |
types: ['geocode'], | |
input: query | |
}, function(predictions, status) { | |
if (status === google.maps.places.PlacesServiceStatus.OK) { | |
process($.map(predictions, function(prediction) { | |
return prediction.description; | |
})); | |
} | |
}); | |
}, | |
updater: function (item) { | |
cb.call(input_elm[0], item); | |
return item; | |
} | |
}); | |
if (init_value) { | |
cb.call(input_elm[0], init_value); | |
} | |
} | |
if (typeof(google) !== 'undefined') { | |
window.googleApi = {}; | |
window.googleApi.autocompleteService = new google.maps.places.AutocompleteService(); | |
window.googleApi.geocoder = new google.maps.Geocoder(); | |
registerLocationAutoFill("input[name=address]", function (selected_address) { | |
var input_elm = $(this); | |
window.googleApi.geocoder.geocode({ address: selected_address }, function(results, status) { | |
if (status === google.maps.GeocoderStatus.OK) { | |
var components = getAddressComponents(results[0].address_components), | |
container = $("#container"); | |
$("input[name='city']", container).val(components.hasOwnProperty('locality') ? components.locality : null); | |
$("select[name='country']", container).selectOptionByLabel(components.hasOwnProperty('country') ? components.country : undefined); | |
$("select[name='region']", container).selectOptionByLabel(components.hasOwnProperty('region') ? components.region : undefined); | |
$("input[name='postal']", container).val(components.hasOwnProperty('postal_code') ? components.postal_code : null); | |
input_elm.val(null); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment