Adam Starrh Adam Starrh - 1 year ago 132
Javascript Question

Javascript: Get Coords from both clicking and dragging map marker

I have the below script in which a google map marker is placed when the map is clicked. It can then be dragged around for further precision. I would like to obtain the coordinates of the map pin in either case.

map.addListener('click', function (e) {
placeMarkerAndPanTo(e.latLng, map);
});

function placeMarkerAndPanTo(latLng, map) {
var position = latLng;
console.log(position);
while (markersArray.length) {
markersArray.pop().setMap(null);
}
var marker = new google.maps.Marker({
draggable: true,
position: latLng,
map: map,
title: "Select Your Location!"
});
map.panTo(latLng);

markersArray.push(marker);

map.addListener(marker, 'dragend', function (event) {
var position = event.latLng;
console.log(position);
});
}


I get the click coords just fine, but I'm having trouble placing my
'dragend'
listener so that it picks up on the action. If it is placed inside the
placeMarkerAndPanTo
function, then it doesn't really 'listen' after the function is over. However, if I place it outside the function, then it has no idea what a
marker
is!

What is the simplest solution to this problem?

Answer Source

You have a typo in your code:

markersArray.push(marker);

map.addListener(marker, 'dragend', function (event) {
var position = event.latLng;
console.log(position);
});

should be:

markersArray.push(marker);

google.maps.event.addListener(marker, 'dragend', function (event) {
var position = event.latLng;
console.log(position);
});

proof of concept fiddle

code snippet:

var geocoder;
var map;
var markersArray = [];

function placeMarkerAndPanTo(latLng, map) {
  var position = latLng;
  console.log(position);
  while (markersArray.length) {
    markersArray.pop().setMap(null);
  }
  var marker = new google.maps.Marker({
    draggable: true,
    position: latLng,
    map: map,
    title: "Select Your Location!"
  });
  map.panTo(latLng);

  markersArray.push(marker);

  google.maps.event.addListener(marker, 'dragend', function(event) {
    var position = event.latLng;
    console.log(position);
  });
}

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  map.addListener('click', function(e) {
    placeMarkerAndPanTo(e.latLng, map);
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download