I have successfuly implemented Google Maps Places V3 autocomplete feature on my input box as per http://web.archive.org/web/20120225114154/http://code.google.com:80/intl/sk-SK/apis/maps/documentation/javascript/places.html. It works nicely, however I would love to know how can I make it select the first option from the suggestions when a user presses enter. I guess I would need some JS magic, but I am very much new to JS and don't know where to start.
Thanks in advance!
Google Map with Autocomplete Search BoxCreate an input element ( searchInput ) where the autocomplete addresses search will be added. Create a DIV element ( map ) to display the Google Map. Specify the elements to display the geolocation data.
It is currently not possible to restrict results to a specific locality. You can use bounds as you have done so above to bias results towards, but not restricted to places contained within the specified bounds. If you believe restriction by locality would be a useful feature please file a Places API - Feature Request.
Here is a solution that does not make a geocoding request that may return an incorrect result: http://jsfiddle.net/amirnissim/2D6HW/
It simulates a down-arrow
keypress whenever the user hits return
inside the autocomplete field. The ↓ event is triggered before the return event so it simulates the user selecting the first suggestion using the keyboard.
Here is the code (tested on Chrome and Firefox) :
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script> <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> <script> var pac_input = document.getElementById('searchTextField'); (function pacSelectFirst(input) { // store the original event binding function var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent; function addEventListenerWrapper(type, listener) { // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected, // and then trigger the original listener. if (type == "keydown") { var orig_listener = listener; listener = function(event) { var suggestion_selected = $(".pac-item-selected").length > 0; if (event.which == 13 && !suggestion_selected) { var simulated_downarrow = $.Event("keydown", { keyCode: 40, which: 40 }); orig_listener.apply(input, [simulated_downarrow]); } orig_listener.apply(input, [event]); }; } _addEventListener.apply(input, [type, listener]); } input.addEventListener = addEventListenerWrapper; input.attachEvent = addEventListenerWrapper; var autocomplete = new google.maps.places.Autocomplete(input); })(pac_input); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With