Sometimes, we want to get lat/lng from Google marker with JavaScript.
In this article, we’ll look at how to get lat/lng from Google marker with JavaScript.
How to get lat/lng from Google marker with JavaScript?
To get lat/lng from Google marker with JavaScript, we can listen to the marker’s dragstart and dragend events.
For instance, we write
<div id="map_canvas"></div>
to add a div for the map.
Then we set its size with
#map_canvas {
width: 400px;
height: 300px;
}
Then we create the map with a marker inside with
const map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 1,
center: new google.maps.LatLng(45.137879, -82.836914),
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
const myMarker = new google.maps.Marker({
position: new google.maps.LatLng(47.651968, 9.478485),
draggable: true,
});
google.maps.event.addListener(myMarker, "dragend", (evt) => {
console.log(evt.latLng.lng().toFixed(3));
});
google.maps.event.addListener(myMarker, "dragstart", (evt) => {
console.log("dragging marker");
});
We use the Map constructor to fill the div with the map contents.
And we set the default zoom and center of the map.
Next, we create a marker with the Marker constructor.
And then we call addListener to listen to the dragstart and dragend events of the marker.
In the dragend callback, we get the longitude of the marker’s current location with evt.latLng.lng().
Conclusion
To get lat/lng from Google marker with JavaScript, we can listen to the marker’s dragstart and dragend events.