Skip to content

Instantly share code, notes, and snippets.

@Braunson
Created February 4, 2018 19:46
Show Gist options
  • Save Braunson/b1286c2d56e4e0509ea67d19b269cfb3 to your computer and use it in GitHub Desktop.
Save Braunson/b1286c2d56e4e0509ea67d19b269cfb3 to your computer and use it in GitHub Desktop.
jQuery Wrapper for @dericcain's google-address-autocomplete
/*!
* jQuery Google autocomplete plugin
* Description: THis is just a jQuery wrapper for @dericcain's method helper linked below
* Author: @braunson
* Requirements: https://github.com/dericcain/google-address-autocomplete
* Licensed under the MIT license
*/;
(function($) {
// Usage $('[data-google-autocomplete]').googleAutocomplete();
$.fn.extend({
googleAutocomplete: function(options) {
this.defaultOptions = {
debug: true,
callback: function(result, geo, raw) {
var json = JSON.stringify({
street_number: result.streetNumber,
street_name: result.streetName,
street_1: result.streetNumber + ' ' + result.streetName,
postal_code: result.zipCode,
city: result.cityName,
province: result.state,
country: result.country,
// Additional details
lat: geo.latitude(),
lng: geo.longitude(),
url: raw.url,
google_id: raw.id,
place_id: raw.place_id,
vicinity: raw.vicinity,
utc_offset: raw.utc_offset,
reference: raw.reference
}),
name = $(this.element).attr('name') + '_googleaddress';
if (!$('body').find('input[name="' + name + '"]:hidden').length) {
// Append the field and add the data
$(this.element).append('<input type="hidden" name="' + name + '" value="' + json + '"');
if (settings.debug) console.log('>>> Appending a hidden field (' + name + ') and setting json data');
} else {
// Update the existing field
$('body').find('input[name="' + name + '"]:hidden').val(json);
if (settings.debug) console.log('>> Existing field (' + name + '), updating the data');
}
}
};
var settings = $.extend({}, this.defaultOptions, options);
return this.each(function(i, element) {
if (settings.debug) console.log('> Found an instance (#' + $(this).attr('id') + ')');
var initClass = 'google-autocomplete-init';
// Does this element already have the init class?
if ($(element).hasClass(initClass)) {
if (settings.debug) console.log('!!! Already initiated', $this);
return;
}
var newClass = 'google-autocomplete-' + Math.floor((Math.random() * 1000) + 1);
// Add a random class as the method below requires a class or id.
$(element).addClass(initClass + ' ' + newClass)
.removeAttr('data-google-autocomplete');
// Init our autocomplete function
// This assumes you have street_1 on the page along with the rest
// of the inputs listed below to work
new AddressAutocomplete('.' + newClass, settings.callback);
if (settings.debug) console.log('>>>> Initialized (#' + $(this).attr('id') + ')');
});
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment