Place Autocomplete
Search with autocomplete google maps
by Osama Qassar
HTML
<div class="pac-card" id="pac-card">
<div>
<div id="title">
Autocomplete search
</div>
<div id="type-selector" class="pac-controls">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-address">
<label for="changetype-address">Addresses</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</label>
</div>
<div id="strict-bounds-selector" class="pac-controls">
<input type="checkbox" id="use-strict-bounds" value="">
<label for="use-strict-bounds">Strict Bounds</label>
</div>
</div>
<div id="pac-container">
<input id="pac-input" type="text" placeholder="Enter a location">
</div>
</div>
<div id="map"></div>
<div id="infowindow-content">
<img src="" width="16" height="16" id="place-icon">
<span id="place-name" class="title"></span><br>
<span id="place-address"></span>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap"
async defer></script>
CSS
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
height: 300px
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
input[type='text']{
width:100%;
margin: 20px;
}
JavaScript
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("No details available for input: '" + place.name + "'");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
});
}