FakeEmpire
FakeEmpire

Reputation: 798

Getting draggable marker position (lat,lng) in Google Maps (React)

Using the Google Maps API, I am attempting to capture the exact lat and lng of a marker in React, however I am running into some difficulty.

This is my event listener -

window.google.maps.event.addListener(marker, 'dragend', (e) => {
  console.log(marker.getPosition());
});

Browser console -

_.F {lat: function, lng: function}

Upvotes: 2

Views: 4523

Answers (1)

shotor
shotor

Reputation: 986

You're nearly there. Let's find marker.getPosition in the docs: https://developers.google.com/maps/documentation/javascript/reference#Marker

We see there that the return value for that function is a LatLng object. We can navigate to that object in the documentation by clicking on the text: https://developers.google.com/maps/documentation/javascript/reference#LatLng

And there we see that a LatLng object contains lat() and lng() functions that return the actual values.

So putting it all together, to get the latitude and longitude coordinates:

var position = marker.getPosition()
var lat = position.lat()
var lng = position.lng()

Upvotes: 2

Related Questions