How to add Google Maps Autocomplete search box?
To use Google Maps/Places APIs now, you're required to use an API Key. So the API URL will change from
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
to
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
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>
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);
Just copy and paste the sameple code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
</head>
<body>
<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">
<script>
function init() {
var input = document.getElementById('locationTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</body>
</html>
Well formatted code can be found from this link. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/