I want to add the Address Autocomplete feature of the Google Maps JavaScript API to my form. I followed their example page and have everything working so far.
However, I don't like how the example uses a separate field just for the autocomplete behavior. I want to attach the autocomplete behavior to my existing Street Address field, so that I can avoid having to add an additional field to my form.
By default, when an autocomplete suggestion is selected, the field it's attached to fills in with the full address (e.g. 123 Main St., Anytown, CA, United States
). But since I'm attaching the autocomplete behavior to my Street Address field, I only want it to show the number and street name once a suggestion is selected. So I tried setting the value of the autocomplete field to just the street_number
and route
from the JSON response:
if (addressType == "street_number") {
// Set the value to the street number
document.getElementById("autocomplete").value = val; /* 123 */
} else if (addressType == "route") {
// Append the street name
document.getElementById("autocomplete").value += " " + val; /* 123 Main St. */
}
This works...but only while the field is focused. As soon as it loses focus – like when you tab to the next field – it redisplays the full address again.
I can't find any event or anything I can use to prevent the field from redisplaying the full address whenever it loses focus. The Autocomplete class only has one event, place_changed
, which only fires when an autocomplete suggestion is selected.
So I tried adding a DOM listener for the blur
event on the field, so that whenever it loses focus I can set its value back to just the street address:
google.maps.event.addDomListener(document.getElementById("autocomplete"), "blur", function() {
document.getElementById("autocomplete").value = streetAddress;
console.log(document.getElementById("autocomplete").value); /* logs "123 Main St."
});
But even though the log statement shows that the value of the field is set to 123 Main St.
on blur, it still displays the full 123 Main St., Anytown, CA, United States
in the browser.
Is there any way to achieve what I'm trying to do, or do I just have to resort to adding a separate autocomplete field?
Solved! It turns out that if I just manually blur the autocomplete field on the
place_changed
event before I fill it in with the street address, then it "sticks" and doesn't revert back to the full address (even if I tab in and out of it):Update: my original solution worked in Safari and Chrome, but not IE. To get IE to work as well, I found I just had to wrap my
fillInAddress()
function in a timeout:I'm not sure why this makes any difference – especially since the other browsers are fine without it – but by setting the value to
0
, it doesn't cause any perceptible delay.