I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible.
My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and some tutorials yet they all bundle together the autocomplete functionality with mapping it on an embedded Google map.
I don't need to map the location visually, I just need the autocomplete box for now, unfortunately I cannot work out which parts of the API are relevant to this and every example I have looked at includes plenty of JS for mapping.
How can I ONLY add the autocomplete input functionality?
Google Maps now will hide the search bar on the top and explore bar on the bottom of the map screen to create a larger visual field.
First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file. Use script file to load the autocomplete class.
A significant portion of this code can be eliminated.
HTML excerpt:
<head> ... <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script> ... </head> <body> ... <input id="searchTextField" type="text" size="50"> ... </body>
Javascript:
function initialize() { var input = document.getElementById('searchTextField'); new google.maps.places.Autocomplete(input); } google.maps.event.addDomListener(window, 'load', initialize);
To get latitude and longitude too, you can use this simple code:
<html> <head> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> <script> function initialize() { var input = document.getElementById('searchTextField'); var autocomplete = new google.maps.places.Autocomplete(input); google.maps.event.addListener(autocomplete, 'place_changed', function () { var place = autocomplete.getPlace(); document.getElementById('city2').value = place.name; document.getElementById('cityLat').value = place.geometry.location.lat(); document.getElementById('cityLng').value = place.geometry.location.lng(); }); } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <input type="hidden" id="city2" name="city2" /> <input type="hidden" id="cityLat" name="cityLat" /> <input type="hidden" id="cityLng" name="cityLng" /> </body> </html>
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