user982124
user982124

Reputation: 4622

Google Maps API - Get New Center Coordinates after map is moved

I'm using the Google Maps API to display a map, but I now need to capture the centre coordinators if the user moves the map. I'm after the new lat/long of the new centre of the map after it has been moved.

Looking at the Maps Events docs I can see a few options here:

 center_changed
 dragend

that I could potentially move. I've tried both but can't get the syntax right and not sure how to retrieve the centre lat/long. Here's my latest attempt

google.maps.event.addListener(map, 'dragend', function() {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    console.log("current latitude is: "+latitude);
    console.log("current longitude is: "+longitude);
});

but I get an error TypeError: undefined is not an object (evaluating 'event.latLng.lat') when this runs.

Can anyone tell me what the most approrpriate event to use here and how I can get the new centre co-ordinatates when the map has changed by the user dragging it.

Upvotes: 1

Views: 3575

Answers (1)

geocodezip
geocodezip

Reputation: 161384

If you want the center values when it changes, use the 'center_changed' event:

center_changed

Arguments: None
This event is fired when the map center property changes.

google.maps.event.addListener(map, "center_changed", function() {
  var center = this.getCenter();
  var latitude = center.lat();
  var longitude = center.lng();
  console.log("current latitude is: " + latitude);
  console.log("current longitude is: " + longitude);
});

proof of concept fiddle

code snippet:

function initMap() {
  var myLatlng = {
    lat: -25.363,
    lng: 131.044
  };

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatlng
  });
  google.maps.event.addListener(map, "center_changed", function() {
    var center = this.getCenter();
    var latitude = center.lat();
    var longitude = center.lng();
    console.log("current latitude is: " + latitude);
    console.log("current longitude is: " + longitude);
  });

}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Upvotes: 3

Related Questions