js-address-autofill
Advanced tools
Comparing version 1.0.1 to 1.1.0
@@ -100,4 +100,2 @@ var AddressAutofill = | ||
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AddressAutofill; }); | ||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } | ||
@@ -109,2 +107,4 @@ | ||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
@@ -124,14 +124,12 @@ | ||
// Fills out form with configured selectors on selection of google address | ||
useBrowserGeolocation: true, | ||
// Uses the browser's geolocation API to ask the user for her current location (makes predictions more precise) | ||
inputSelector: '[data-autocomplete]', | ||
googleScriptParams: { | ||
key: 'AIzaSyBDTdKd1_rCVcZhGzSaAMqYY7LDy9YaLl8', | ||
callback: 'initAutocomplete', | ||
language: 'de' | ||
// This configuration will be passed to Google Places API as urlParams | ||
key: 'YOUR_KEY_IS_REQUIRED_HERE' // This is required! | ||
}, | ||
googlePlacesConfig: { | ||
types: ['address'], | ||
componentRestrictions: { | ||
country: 'de' | ||
} | ||
}, | ||
googlePlacesConfig: {}, | ||
// This configuration will be passed to Google Places API | ||
mapResult: { | ||
@@ -177,5 +175,9 @@ streetName: { | ||
} | ||
}; // Bias the autocomplete object to the user's geographical location, | ||
// as supplied by the browser's 'navigator.geolocation' object. | ||
}; | ||
/** | ||
* Stores all instances of AddressAutofill | ||
*/ | ||
var instances = []; | ||
var AddressAutofill = | ||
@@ -185,4 +187,2 @@ /*#__PURE__*/ | ||
function AddressAutofill(context) { | ||
var _this = this; | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
@@ -192,34 +192,62 @@ | ||
if (_typeof(context) !== 'object' || !(context instanceof HTMLElement) && !(context instanceof HTMLDocument)) { | ||
console.error('Please choose a valid context for AddressAutofill! Given:', context); | ||
return null; | ||
} | ||
this.context = context; | ||
this.inputElement = this.context.querySelector('[data-autocomplete]'); | ||
if (!(this.inputElement instanceof HTMLInputElement)) { | ||
console.error('Please choose a valid input field for AddressAutofill! Given:', this.inputElement); | ||
return null; | ||
} | ||
this.options = _objectSpread({}, defaultOptions, {}, options); | ||
this.inputElement = document.querySelector('[data-autocomplete]'); | ||
this.autocomplete = null; | ||
this.result = null; | ||
this.instance = instances.push(this) - 1; // Check for configs | ||
window.initAutocomplete = function () { | ||
// Create the autocomplete instance with custom options | ||
_this.autocomplete = new google.maps.places.Autocomplete(_this.inputElement, _this.options.googlePlacesConfig); | ||
if (this.inputElement.getAttribute('data-autocomplete') !== null) { | ||
this.options.googleScriptParams.key = this.inputElement.getAttribute('data-autocomplete'); | ||
} // Check if the script is already injected | ||
_this.geolocate(); // When the user selects an address from the dropdown, populate the address fields in the form. | ||
if (!window.hasGoogleAutocomplete) { | ||
if (typeof window.initAutocomplete !== 'function') { | ||
// Creates new instance of autocomplete for each already existing AddressAutofill instance | ||
window.initAutocomplete = function () { | ||
return instances.forEach(function (instance) { | ||
return initAutocomplete(instance); | ||
}); | ||
}; | ||
} | ||
_this.autocomplete.addListener('place_changed', function () { | ||
return _this.setAddress(); | ||
}); | ||
}; | ||
injectMapsScript(this.options.googleScriptParams); | ||
} else { | ||
initAutocomplete(this); | ||
} // Capture Enter Press | ||
injectMapsScript(this.options.googleScriptParams); // Injects Google Api Script | ||
console.log('INIT:', this); | ||
this.inputElement.addEventListener('keydown', function (event) { | ||
if (event.keyCode == 13) { | ||
event.preventDefault(); | ||
event.stopPropagation(); | ||
} | ||
}); | ||
return this; | ||
} | ||
/** | ||
* Sets the address found by the Places API to the configured fields. | ||
*/ | ||
_createClass(AddressAutofill, [{ | ||
key: "setAddress", | ||
value: function setAddress() { | ||
var _this2 = this; | ||
var _this = this; | ||
this.result = {}; | ||
var resultMap = this.options.mapResult; | ||
var place = this.autocomplete.getPlace(); | ||
console.log('Place', place); // Map the result data | ||
var place = this.autocomplete.getPlace(); // Map the result data | ||
@@ -239,11 +267,15 @@ var _loop = function _loop(itemName) { | ||
default: | ||
itemValue = place.address_components.filter(function (component) { | ||
// TODO: Fix error on empty entries like street number, etc... | ||
var address_component = place.address_components.filter(function (component) { | ||
return component.types.includes(resultMap[itemName].resultType); | ||
})[0][resultMap[itemName].use]; | ||
}); | ||
if (address_component.length > 0) { | ||
itemValue = address_component[0][resultMap[itemName].use]; | ||
} | ||
} // Optional: Fill out the form | ||
if (_this2.options.enableInputFillIn) { | ||
var element = document.querySelector(resultMap[itemName].targetSelector); | ||
if (_this.options.enableInputFillIn) { | ||
var element = _this.context.querySelector(resultMap[itemName].targetSelector); | ||
@@ -253,3 +285,3 @@ if (!element) { | ||
} else { | ||
_this2.result[itemName] = itemValue; | ||
_this.result[itemName] = itemValue; | ||
element.value = itemValue; | ||
@@ -263,26 +295,3 @@ } | ||
} | ||
console.log('Result', this.result); | ||
} | ||
}, { | ||
key: "geolocate", | ||
value: function geolocate() { | ||
var _this3 = this; | ||
if (navigator.geolocation) { | ||
navigator.geolocation.getCurrentPosition(function (position) { | ||
var geolocation = { | ||
lat: position.coords.latitude, | ||
lng: position.coords.longitude | ||
}; | ||
var circle = new google.maps.Circle({ | ||
center: geolocation, | ||
radius: position.coords.accuracy | ||
}); | ||
console.log('I found your location!', geolocation, circle); | ||
_this3.autocomplete.setBounds(circle.getBounds()); | ||
}); | ||
} | ||
} | ||
}]); | ||
@@ -308,6 +317,6 @@ | ||
if (!params.key) { | ||
return console.error('Please add a valid API key for "AddressAutofill.key" to run AddressAutofill!'); | ||
return console.error('Please add a valid API key for "AddressAutofill" to run AddressAutofill!'); | ||
} | ||
var mapsUrl = "https://maps.googleapis.com/maps/api/js?libraries=places"; | ||
var mapsUrl = "https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete"; | ||
var mapsScript = document.createElement("script"); | ||
@@ -321,4 +330,44 @@ | ||
document.body.appendChild(mapsScript); | ||
window.hasGoogleAutocomplete = true; | ||
} | ||
/** | ||
* Instanciates a new google autocomplete object and binds it to the given AddressAutofill instance. | ||
* @param {AddressAutofill} instance - Any instance of the AddressAutofill module. | ||
*/ | ||
function initAutocomplete(instance) { | ||
// Create the autocomplete instance with custom options | ||
instance.autocomplete = new google.maps.places.Autocomplete(instance.inputElement, instance.options.googlePlacesConfig); | ||
if (instance.options.useBrowserGeolocation) { | ||
geolocate(instance.autocomplete); | ||
} // When the user selects an address from the dropdown, populate the address fields in the form. | ||
instance.autocomplete.addListener('place_changed', function () { | ||
return instance.setAddress(); | ||
}); | ||
} | ||
/** | ||
* Tries to get the user's geolocation using the browser's Geolocation API. | ||
*/ | ||
function geolocate(reference) { | ||
if (navigator.geolocation) { | ||
navigator.geolocation.getCurrentPosition(function (position) { | ||
var location = { | ||
lat: position.coords.latitude, | ||
lng: position.coords.longitude | ||
}; | ||
var circle = new google.maps.Circle({ | ||
center: location, | ||
radius: position.coords.accuracy | ||
}); | ||
reference.setBounds(circle.getBounds()); | ||
}); | ||
} | ||
} | ||
/***/ }), | ||
@@ -325,0 +374,0 @@ |
@@ -1,2 +0,2 @@ | ||
var AddressAutofill=function(e){var t={};function o(r){if(t[r])return t[r].exports;var n=t[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,o),n.l=!0,n.exports}return o.m=e,o.c=t,o.d=function(e,t,r){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(o.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)o.d(r,n,function(t){return e[t]}.bind(null,n));return r},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=0)}([function(e,t,o){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function n(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,r)}return o}function l(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function a(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}o.r(t);var u={autoConstruct:!1,enableInputFillIn:!0,inputSelector:"[data-autocomplete]",googleScriptParams:{key:"AIzaSyBDTdKd1_rCVcZhGzSaAMqYY7LDy9YaLl8",callback:"initAutocomplete",language:"de"},googlePlacesConfig:{types:["address"],componentRestrictions:{country:"de"}},mapResult:{streetName:{use:"long_name",resultType:"route",targetSelector:'[name="streetName"]'},streetNumber:{use:"short_name",resultType:"street_number",targetSelector:'[name="streetNumber"]'},city:{use:"long_name",resultType:"locality",targetSelector:'[name="city"]'},country:{use:"long_name",resultType:"country",targetSelector:'[name="country"]'},postalCode:{use:"short_name",resultType:"postal_code",targetSelector:'[name="postalCode"]'},lat:{use:"geo",resultType:"lat",targetSelector:'[name="lat"]'},lng:{use:"geo",resultType:"lng",targetSelector:'[name="lng"]'}}},c=function(){function e(t){var o=this,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.options=function(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?n(o,!0).forEach((function(t){l(e,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):n(o).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))}))}return e}({},u,{},a),this.inputElement=document.querySelector("[data-autocomplete]"),this.autocomplete=null,this.result=null,window.initAutocomplete=function(){o.autocomplete=new google.maps.places.Autocomplete(o.inputElement,o.options.googlePlacesConfig),o.geolocate(),o.autocomplete.addListener("place_changed",(function(){return o.setAddress()}))},function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if("object"!==r(e))return console.error('"googleScriptParams" are required for AddressAutofill configuration!');if(!e.key)return console.error('Please add a valid API key for "AddressAutofill.key" to run AddressAutofill!');var t="https://maps.googleapis.com/maps/api/js?libraries=places",o=document.createElement("script");for(var n in e)t+="&".concat(n,"=").concat(e[n]);o.src=t,document.body.appendChild(o)}(this.options.googleScriptParams),console.log("INIT:",this),this}var t,o,c;return t=e,(o=[{key:"setAddress",value:function(){var e=this;this.result={};var t=this.options.mapResult,o=this.autocomplete.getPlace();console.log("Place",o);var r=function(r){var n=null;switch(t[r].resultType){case"lat":n=o.geometry.location.lat();break;case"lng":n=o.geometry.location.lng();break;default:n=o.address_components.filter((function(e){return e.types.includes(t[r].resultType)}))[0][t[r].use]}if(e.options.enableInputFillIn){var l=document.querySelector(t[r].targetSelector);l?(e.result[r]=n,l.value=n):console.warn("AddressAutofill: Could not find in element ".concat(t[r].targetSelector," in DOM, please check your config!"))}};for(var n in t)r(n);console.log("Result",this.result)}},{key:"geolocate",value:function(){var e=this;navigator.geolocation&&navigator.geolocation.getCurrentPosition((function(t){var o={lat:t.coords.latitude,lng:t.coords.longitude},r=new google.maps.Circle({center:o,radius:t.coords.accuracy});console.log("I found your location!",o,r),e.autocomplete.setBounds(r.getBounds())}))}}])&&a(t.prototype,o),c&&a(t,c),e}();o.d(t,"init",(function(){return i}));var i=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new c(e,t)}}]); | ||
var AddressAutofill=function(e){var t={};function o(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,o),r.l=!0,r.exports}return o.m=e,o.c=t,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(e,t){if(1&t&&(e=o(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)o.d(n,r,function(t){return e[t]}.bind(null,r));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=0)}([function(e,t,o){"use strict";function n(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),o.push.apply(o,n)}return o}function r(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function l(e){return(l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var o=0;o<t.length;o++){var n=t[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}o.r(t);var a={autoConstruct:!1,enableInputFillIn:!0,useBrowserGeolocation:!0,inputSelector:"[data-autocomplete]",googleScriptParams:{key:"YOUR_KEY_IS_REQUIRED_HERE"},googlePlacesConfig:{},mapResult:{streetName:{use:"long_name",resultType:"route",targetSelector:'[name="streetName"]'},streetNumber:{use:"short_name",resultType:"street_number",targetSelector:'[name="streetNumber"]'},city:{use:"long_name",resultType:"locality",targetSelector:'[name="city"]'},country:{use:"long_name",resultType:"country",targetSelector:'[name="country"]'},postalCode:{use:"short_name",resultType:"postal_code",targetSelector:'[name="postalCode"]'},lat:{use:"geo",resultType:"lat",targetSelector:'[name="lat"]'},lng:{use:"geo",resultType:"lng",targetSelector:'[name="lng"]'}}},u=[],c=function(){function e(t){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),"object"===l(t)&&(t instanceof HTMLElement||t instanceof HTMLDocument)?(this.context=t,this.inputElement=this.context.querySelector("[data-autocomplete]"),this.inputElement instanceof HTMLInputElement?(this.options=function(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?n(o,!0).forEach((function(t){r(e,t,o[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):n(o).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))}))}return e}({},a,{},o),this.autocomplete=null,this.result=null,this.instance=u.push(this)-1,null!==this.inputElement.getAttribute("data-autocomplete")&&(this.options.googleScriptParams.key=this.inputElement.getAttribute("data-autocomplete")),window.hasGoogleAutocomplete?s(this):("function"!=typeof window.initAutocomplete&&(window.initAutocomplete=function(){return u.forEach((function(e){return s(e)}))}),function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;if("object"!==l(e))return console.error('"googleScriptParams" are required for AddressAutofill configuration!');if(!e.key)return console.error('Please add a valid API key for "AddressAutofill" to run AddressAutofill!');var t="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete",o=document.createElement("script");for(var n in e)t+="&".concat(n,"=").concat(e[n]);o.src=t,document.body.appendChild(o),window.hasGoogleAutocomplete=!0}(this.options.googleScriptParams)),this.inputElement.addEventListener("keydown",(function(e){13==e.keyCode&&(e.preventDefault(),e.stopPropagation())})),this):(console.error("Please choose a valid input field for AddressAutofill! Given:",this.inputElement),null)):(console.error("Please choose a valid context for AddressAutofill! Given:",t),null)}var t,o,c;return t=e,(o=[{key:"setAddress",value:function(){var e=this;this.result={};var t=this.options.mapResult,o=this.autocomplete.getPlace(),n=function(n){var r=null;switch(t[n].resultType){case"lat":r=o.geometry.location.lat();break;case"lng":r=o.geometry.location.lng();break;default:var l=o.address_components.filter((function(e){return e.types.includes(t[n].resultType)}));l.length>0&&(r=l[0][t[n].use])}if(e.options.enableInputFillIn){var i=e.context.querySelector(t[n].targetSelector);i?(e.result[n]=r,i.value=r):console.warn("AddressAutofill: Could not find in element ".concat(t[n].targetSelector," in DOM, please check your config!"))}};for(var r in t)n(r)}}])&&i(t.prototype,o),c&&i(t,c),e}();function s(e){var t;e.autocomplete=new google.maps.places.Autocomplete(e.inputElement,e.options.googlePlacesConfig),e.options.useBrowserGeolocation&&(t=e.autocomplete,navigator.geolocation&&navigator.geolocation.getCurrentPosition((function(e){var o={lat:e.coords.latitude,lng:e.coords.longitude},n=new google.maps.Circle({center:o,radius:e.coords.accuracy});t.setBounds(n.getBounds())}))),e.autocomplete.addListener("place_changed",(function(){return e.setAddress()}))}o.d(t,"init",(function(){return p}));var p=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new c(e,t)}}]); | ||
//# sourceMappingURL=addressAutofill.min.js.map |
{ | ||
"name": "js-address-autofill", | ||
"version": "1.0.1", | ||
"version": "1.1.0", | ||
"description": "An ES6 Module using the Google Places Autocomplete API for address completion in forms.", | ||
@@ -5,0 +5,0 @@ "browserslist": [ |
@@ -52,5 +52,9 @@ /** | ||
let instances = window.instances = [] | ||
/** | ||
* Stores all instances of AddressAutofill | ||
*/ | ||
let instances = [] | ||
export default class AddressAutofill { | ||
@@ -72,18 +76,27 @@ constructor (context, options = {}) { | ||
this.instance = instances.push(this) - 1 | ||
if (typeof window.initAutocomplete !== 'function') { | ||
window.initAutocomplete = () => { | ||
instances.forEach(instance => { | ||
// Create the autocomplete instance with custom options | ||
instance.autocomplete = new google.maps.places.Autocomplete(instance.inputElement, instance.options.googlePlacesConfig) | ||
if (instance.options.useBrowserGeolocation) { | ||
instance.geolocate() | ||
} | ||
// When the user selects an address from the dropdown, populate the address fields in the form. | ||
instance.autocomplete.addListener('place_changed', () => instance.setAddress()) | ||
}) | ||
// Check for configs | ||
if (this.inputElement.getAttribute('data-autocomplete') !== null) { | ||
this.options.googleScriptParams.key = this.inputElement.getAttribute('data-autocomplete') | ||
} | ||
// Check if the script is already injected | ||
if (!window.hasGoogleAutocomplete) { | ||
if (typeof window.initAutocomplete !== 'function') { | ||
// Creates new instance of autocomplete for each already existing AddressAutofill instance | ||
window.initAutocomplete = () => instances.forEach(instance => initAutocomplete(instance)) | ||
} | ||
if (!window.mapsScript) { | ||
injectMapsScript(this.options.googleScriptParams) // Injects Google Api Script | ||
injectMapsScript(this.options.googleScriptParams) | ||
} else { | ||
initAutocomplete(this) | ||
} | ||
// Capture Enter Press | ||
this.inputElement.addEventListener('keydown', event => { | ||
if (event.keyCode == 13) { | ||
event.preventDefault() | ||
event.stopPropagation() | ||
} | ||
} | ||
}) | ||
return this | ||
@@ -100,4 +113,2 @@ } | ||
const place = this.autocomplete.getPlace() | ||
console.log('Place', place) | ||
// Map the result data | ||
@@ -117,4 +128,2 @@ for (const itemName in resultMap) { | ||
itemValue = address_component[0][resultMap[itemName].use] | ||
} else { | ||
console.log(itemName, 'skipped') | ||
} | ||
@@ -133,25 +142,3 @@ } | ||
} | ||
console.log ('Result', this.result) | ||
} | ||
/** | ||
* Tries to get the user's geolocation using the browser's Geolocation API. | ||
*/ | ||
geolocate() { | ||
if (navigator.geolocation) { | ||
navigator.geolocation.getCurrentPosition((position) => { | ||
const geolocation = { | ||
lat: position.coords.latitude, | ||
lng: position.coords.longitude | ||
} | ||
const circle = new google.maps.Circle({ | ||
center: geolocation, | ||
radius: position.coords.accuracy | ||
}) | ||
console.log('User\'s location has been detected!', geolocation) | ||
this.autocomplete.setBounds(circle.getBounds()) | ||
}) | ||
} | ||
} | ||
} | ||
@@ -169,3 +156,3 @@ | ||
if (!params.key) { | ||
return console.error('Please add a valid API key for "AddressAutofill.key" to run AddressAutofill!') | ||
return console.error('Please add a valid API key for "AddressAutofill" to run AddressAutofill!') | ||
} | ||
@@ -179,3 +166,38 @@ let mapsUrl = "https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" | ||
document.body.appendChild(mapsScript) | ||
window.mapsScript = true | ||
window.hasGoogleAutocomplete = true | ||
} | ||
/** | ||
* Instanciates a new google autocomplete object and binds it to the given AddressAutofill instance. | ||
* @param {AddressAutofill} instance - Any instance of the AddressAutofill module. | ||
*/ | ||
function initAutocomplete (instance) { | ||
// Create the autocomplete instance with custom options | ||
instance.autocomplete = new google.maps.places.Autocomplete(instance.inputElement, instance.options.googlePlacesConfig) | ||
if (instance.options.useBrowserGeolocation) { | ||
geolocate(instance.autocomplete) | ||
} | ||
// When the user selects an address from the dropdown, populate the address fields in the form. | ||
instance.autocomplete.addListener('place_changed', () => instance.setAddress()) | ||
} | ||
/** | ||
* Tries to get the user's geolocation using the browser's Geolocation API. | ||
*/ | ||
function geolocate(reference) { | ||
if (navigator.geolocation) { | ||
navigator.geolocation.getCurrentPosition((position) => { | ||
const location = { | ||
lat: position.coords.latitude, | ||
lng: position.coords.longitude | ||
} | ||
const circle = new google.maps.Circle({ | ||
center: location, | ||
radius: position.coords.accuracy | ||
}) | ||
reference.setBounds(circle.getBounds()) | ||
}) | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
69309
592