Last active
July 24, 2020 01:37
-
-
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.
This file contains 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
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); | |
} | |
}; |
This file contains 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
<input type="text" data-bind="addressAutocomplete: FullAddress, route: Street, locality: Suburb, administrative_area_level_1: State" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?