Skip to content

Instantly share code, notes, and snippets.

@moshiurse
Last active August 8, 2023 05:18
Show Gist options
  • Save moshiurse/15b28a416729e8519290a12b71ab6301 to your computer and use it in GitHub Desktop.
Save moshiurse/15b28a416729e8519290a12b71ab6301 to your computer and use it in GitHub Desktop.
Google Map Autocomplete
function initMap() {
var inputs = document.querySelectorAll('.pac-input');
inputs.forEach(input => {
const autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
onPlaceChanged(autocomplete);
});
})
}
function onPlaceChanged(autocomplete) {
var selectedPlace = autocomplete.getPlace();
let location = selectedPlace.geometry.location;
let lat = location.lat();
let lon = location.lng();
let name = selectedPlace.name;
console.log(lat, lon, name);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap&libraries=places"></script>
<script src="app.js"></script>
</head>
<body>
<div id="pac-container">
<input class="pac-input" type="text" placeholder="Enter a location" />
<input class="pac-input" type="text" placeholder="Enter a location" />
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment