Skip to content

Instantly share code, notes, and snippets.

@chadedrupt
Last active July 24, 2020 01:37
Show Gist options
  • Save chadedrupt/5974524 to your computer and use it in GitHub Desktop.
Save chadedrupt/5974524 to your computer and use it in GitHub Desktop.
Knockout Binding for Google Places autocomplete input. Also populates sibling bindings that match address component types of the places api. That part depends on underscore.js.
ko.bindingHandlers.addressAutocomplete = {
init: function (element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
var options = { types: ['geocode'] };
ko.utils.extend(options, allBindings.autocompleteOptions)
var autocomplete = new google.maps.places.Autocomplete(element, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
result = autocomplete.getPlace();
value(result.formatted_address);
// The following section poplutes any bindings that match an address component with a first type that is the same name
// administrative_area_level_1, posatl_code etc. these can be found in the Google Places API documentation
var components = _(result.address_components).groupBy(function (c) { return c.types[0]; });
_.each(_.keys(components), function (key) {
if (allBindings.hasOwnProperty(key))
allBindings[key](components[key][0].short_name);
});
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
ko.bindingHandlers.value.update(element, valueAccessor);
}
};
<input type="text" data-bind="addressAutocomplete: FullAddress, route: Street, locality: Suburb, administrative_area_level_1: State" />
@samanax
Copy link

samanax commented Feb 28, 2016

Hey,

thank you for your code. I have a problem with your code. As the api refenrence I have the following code:
src="https://maps.googleapis.com/maps/api/js?key=[MYCODE]&signed_in=true&libraries=places&callback=addressAutocomplete" async defer but im getting the following error: ReferenceError: google is not defined var autocomplete = new google.maps.places.Autocomplete(element, options);. I guess the problem is with the async script loading and the callback method? Any idea how to solve the problem?

@Martian2Lee
Copy link

try window.onload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment