Created
May 18, 2020 15:29
Google Maps Address Autocomplete
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
function initAutoComplete() { | |
var input = document.getElementById("grid-address"); | |
var autocomplete = new google.maps.places.Autocomplete(input); | |
autocomplete.addListener("place_changed", function () { | |
let place = autocomplete.getPlace(); | |
let address = ""; | |
if (place.address_components) { | |
address = [ | |
(place.address_components[0] && | |
place.address_components[0].short_name) || | |
"", | |
(place.address_components[1] && | |
place.address_components[1].short_name) || | |
"", | |
(place.address_components[2] && | |
place.address_components[2].short_name) || | |
"", | |
].join(" "); | |
} | |
let state, zip, city, street_number, route; | |
for (var x in place.address_components) { | |
let types = place.address_components[x].types; | |
if (types.includes("administrative_area_level_1")) { | |
state = place.address_components[x].short_name; | |
} | |
if (types.includes("postal_code")) { | |
zip = place.address_components[x].short_name; | |
} | |
if (types.includes("locality")) { | |
city = place.address_components[x].short_name; | |
} | |
if (types.includes("street_number")) { | |
street_number = place.address_components[x].short_name; | |
} | |
if (types.includes("route")) { | |
route = place.address_components[x].short_name; | |
} | |
} | |
const addressField = document.querySelector( | |
'#frmAddAppointment input[name="addressSearch"]' | |
); | |
const cityField = document.querySelector( | |
'#frmAddAppointment input[name="city"]' | |
); | |
const zipField = document.querySelector( | |
'#frmAddAppointment input[name="zip"]' | |
); | |
const stateField = document.querySelector( | |
'#frmAddAppointment select[name="state"]' | |
); | |
stateField.value = state; | |
addressField.value = street_number + " " + route; | |
cityField.value = city; | |
zipField.value = zip; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment