I use the Google Maps API and the autocomplete search feature. At this time, you should start entering the location (city, state, zip code, etc.), and then select the result from the drop-down list so that the map is the center in this place. However, I would like to make this proof of a fool and set it up so that if someone enters only a city or just a state and gets “enter” without selecting an autocomplete result, it will still work. For example, if someone types “New York” and presses “enter” without selecting a result from the drop-down list, he will still be concentrated in New York.
I assume this is achieved by grabbing the first result from the Autocomplete drop-down list if it is not manually selected.
I have added an event listener to represent the form, but am not sure how to pass the first result to the "place" variable.
Here is my code:
function searchBar(map) { var input = document.getElementById('search-input'); var searchform = document.getElementById('search-form'); var place; var options = {componentRestrictions: {country: 'us'}}; var autocomplete = new google.maps.places.Autocomplete(input, options);
And here is the JSFiddle for experimentation.
source share