Created
February 23, 2022 02:07
-
-
Save paulobunga/19a79f3de676ddabb2a4fa3e670a430f to your computer and use it in GitHub Desktop.
Google Map Autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Place Autocomplete</title> | |
<style> | |
#map { | |
width: 500px; | |
max-height: 400px; | |
height: 100%; | |
} | |
/* Optional: Makes the sample page fill the window. */ | |
html, | |
body { | |
height: 100%; | |
margin: 0; | |
padding: 0; | |
} | |
</style> | |
</head> | |
<body> | |
<div> | |
<div> | |
<div id="title">Autocomplete search</div> | |
</div> | |
<div id="pac-container"> | |
<input id="autocomplete" type="text" placeholder="Enter a location" /> | |
</div> | |
</div> | |
<div id="map"></div> | |
<script | |
src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap&libraries=places&v=weekly" | |
async | |
></script> | |
<script> | |
function initMap() { | |
const map = new google.maps.Map(document.getElementById('map'), { | |
center: { lat: 40.749933, lng: -73.98633 }, | |
zoom: 13, | |
mapTypeControl: false, | |
}); | |
const autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { | |
strictBounds: false, | |
types: ['establishment', 'geocode'], | |
fields: ['place_id', 'geometry', 'name'], | |
componentRestrictions: { country: ['AU'] }, | |
}); | |
autocomplete.addListener('place_changed', () => { | |
const place = autocomplete.getPlace(); | |
if (!place.geometry || !place.geometry.location) { | |
window.alert("No details available for input: '" + place.name + "'"); | |
return; | |
} | |
// If the place has a geometry, then present it on a map. | |
if (place.geometry.viewport) { | |
map.fitBounds(place.geometry.viewport); | |
} else { | |
map.setCenter(place.geometry.location); | |
map.setZoom(17); | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment