Introduction:
In this tutorial, we will learn how to get the longitude and latitude of the map coordinates from the click Event.
This example listens for the click event, retrieves the click’s latitude and longitude coordinates from google.maps.MapMouseEvent.latLng, and displays those coordinates in an info window.
Code:
function initMap() { const myLatlng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map")!, { zoom: 4, center: myLatlng, }); // Create the initial InfoWindow. let infoWindow = new google.maps.InfoWindow({ content: "Click the map to get Lat/Lng!", position: myLatlng, }); infoWindow.open(map); // Configure the click listener. map.addListener("click", (mapsMouseEvent) => { // Close the current InfoWindow. infoWindow.close(); // Create a new InfoWindow. infoWindow = new google.maps.InfoWindow({ position: mapsMouseEvent.latLng, }); infoWindow.setContent( JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2) ); infoWindow.open(map); }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap; export {};
Explanation:
- The function initMap() is created and it consists of the map properties.
- The ‘centre’ attribute defines where the map should be centered with the help of the latitude and longitude coordinates.
const myLatlng = { lat: -25.363, lng: 131.044 }; center: myLatlng,
zoom: 4,
const map = new google.maps.Map(document.getElementById("map")!,
let infoWindow = new google.maps.InfoWindow({ content: "Click the map to get Lat/Lng!", position: myLatlng, });
map.addListener("click", (mapsMouseEvent) => { }
infoWindow.close();
infoWindow = new google.maps.InfoWindow({ position: mapsMouseEvent.latLng, }); infoWindow.setContent( JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2) ); infoWindow.open(map); });
window.initMap = initMap;
Conclusion:
In this tutorial we learned about how to get the longitude and latitude of the map coordinates from the click Event. We also saw an example that listens for the click event, retrieves the click’s latitude and longitude coordinates from google.maps.MapMouseEvent.latLng, and displays those coordinates in an info window.