Basically, all that you need to do in order to obtain the coordinates of the location where the users clicks on an instance of Google Maps, is to attach an event listener to the map itself. From the received event, extract the latLng
property that contains an object with 2 methods, these 2 methods are: lat
and lng
that will returns the latitude and longitude values respectively:
// Add click listener on the map
google.maps.event.addListener(map, "click", function (event) {
var latLng = event.latLng;
// e.g Latitude: 7.135742728253103, Longitude: -73.11638207013567
alert("Latitude: " + latLng.lat() + ", Longitude: " + latLng.lng());
});
The following implementation in a full document shows how to initialize Google Maps and how to attach the listener:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Google Maps Coordinates on Click</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
width: 1200px;
height: 800px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<!-- Google Maps Container -->
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_TOKEN&callback=initMap">
</script>
<script>
var map;
// Callaback executed when Google Maps script has been loaded
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 7.118389341039206,
lng: -73.12187523419817
}
});
// Add click listener on the map
google.maps.event.addListener(map, "click", function (event) {
var latLng = event.latLng;
alert("Latitude: " + latLng.lat() + ", Longitude: " + latLng.lng());
});
}
</script>
</body>
</html>
Happy coding !