Skip to content

Instantly share code, notes, and snippets.

@emrecamasuvi
Created August 8, 2022 07:45
Show Gist options
  • Save emrecamasuvi/b52d7aeed010af011be1d8bd7c9657c2 to your computer and use it in GitHub Desktop.
Save emrecamasuvi/b52d7aeed010af011be1d8bd7c9657c2 to your computer and use it in GitHub Desktop.
Google Maps autocomplete resolver module
export class MapsResolver {
constructor(domEl, changeEventNamespace) {
this.input = domEl
this.changeEventNamespace = changeEventNamespace
this.loadMapsAPI()
window.initMap = this.listenMapEvents.bind(this)
}
loadMapsAPI() {
if (window.google && window.google.maps) return
let s = document.createElement('script')
s.type = 'text/javascript'
s.async = true
s.src = `//maps.googleapis.com/maps/api/js?key=${this.input.dataset.apiKey}&libraries=places&callback=initMap`
const h = document.getElementsByTagName('head')[0]
h.appendChild(s)
}
listenMapEvents() {
const options = {
componentRestrictions: { country: ['de', 'at', 'ch', 'fr', 'it'] },
types: ['address'],
}
const autocomplete = new google.maps.places.Autocomplete(this.input, options)
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace()
if (place.address_components) this.determineViableAddressPayload(place.address_components)
})
this.disableEnterKeyNotSubmitForm()
}
determineViableAddressPayload(addressParticles) {
const requiredFields = ['postal_code', 'locality', 'route', 'street_number', 'country']
const parsedFields = addressParticles.reduce((acc, curr) => {
const currentType = curr.types[0]
if (requiredFields.includes(currentType)) {
acc[currentType] = currentType === 'country' ? curr.short_name : curr.long_name
}
return acc
}, {})
this.emitAddressChangeEvent(parsedFields)
}
emitAddressChangeEvent(payload) {
this.input.dispatchEvent(
new CustomEvent(this.changeEventNamespace, {
detail: { ...payload },
})
)
}
disableEnterKeyNotSubmitForm() {
this.input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') e.preventDefault()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment