I am using Google Maps API and the Autocomplete search feature. Currently, you must begin typing a location(city, state, zip, etc.) and then select a result from the dropdown for the map to center at that location. However, I would like to make this fool proof and set it up so that if someone types just a city or just a state and hits "enter" without selecting an Autocomplete result, it will still work. For instance, if someone types "New York" and hits "enter" without selecting a result in the dropdown, it will still center on New York.
I'm assuming this is accomplished by grabbing the first result from the Autocomplete dropdown if one is not selected manually.
I've added an event listener for the submission of the form, but not sure how to pass the first result into 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);
//Add listener to detect autocomplete selection
google.maps.event.addListener(autocomplete, 'place_changed', function () {
place = autocomplete.getPlace();
center = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
map.setCenter(center);
map.setZoom(5);
});
//Add listener to search
searchform.addEventListener('submit', function() {
center = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
map.setCenter(center);
map.setZoom(5);
});
//Reset the inpout box on click
input.addEventListener('click', function(){
input.value = "";
});
};
And here is a JSFiddle for experimentation.