Categories
JavaScript Answers

How to get coordinates of marker in Google Maps API and JavaScript?

Spread the love

Sometimes, we want to get coordinates of marker in Google Maps API and JavaScript.

In this article, we’ll look at how to get coordinates of marker in Google Maps API and JavaScript.

How to get coordinates of marker in Google Maps API and JavaScript?

To get coordinates of marker in Google Maps API and JavaScript, we listen for the dragend event.

For instance, we write

const map = new google.maps.Map(document.getElementById("map_canvas"), {
  zoom: 1,
  center: new google.maps.LatLng(35, -82),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
});

const myMarker = new google.maps.Marker({
  position: new google.maps.LatLng(41, -100),
  draggable: true,
});

google.maps.event.addListener(myMarker, "dragend", (evt) => {
  console.log(evt.latLng.lat().toFixed(3), evt.latLng.lng().toFixed(3));
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

to listen for the dragend event of the myMarker marker to get its coordinates after dragging.

We get its latitude with evt.latLng.lat.

And we get its latitude with evt.latLng.lng.

Conclusion

To get coordinates of marker in Google Maps API and JavaScript, we listen for the dragend event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *