不能附加阻力& Dragend事件到可拖动标记(无法读取未定义的属性'addListener')

时间:2018-02-01 01:57:32

标签: google-maps google-maps-api-3

您是否可以请一看这段代码并告诉我为什么我无法将dragdragend事件附加/绑定到可拖动标记?

我正在

  

未捕获的TypeError:无法读取未定义的属性“addListener”

on

 marker.addListener('drag', handleEvent);
 marker.addListener('dragend', handleEvent);

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

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatLng
  });
map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
});

function placeMarker(position, map) {
    marker = new google.maps.Marker({
        position: position,
        draggable:true,
        map: map
    });
  console.log(marker.position.lat());
}
function handleEvent(event) {
   console.log(marker.position.lat());
}
 marker.addListener('drag', handleEvent);
 marker.addListener('dragend', handleEvent);
}

1 个答案:

答案 0 :(得分:1)

您正在将标记添加到标记之前。将这些定义移到placeMarker函数中。

function placeMarker(position, map) {
  marker = new google.maps.Marker({
    position: position,
    draggable: true,
    map: map
  });
  marker.addListener('drag', handleEvent);
  marker.addListener('dragend', handleEvent);
  console.log(marker.position.lat());
}

proof of concept fiddle

代码段



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

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatLng
  });
  map.addListener('click', function(e) {
    placeMarker(e.latLng, map);
  });

  function placeMarker(position, map) {
    marker = new google.maps.Marker({
      position: position,
      draggable: true,
      map: map
    });
    marker.addListener('drag', handleEvent);
    marker.addListener('dragend', handleEvent);
    console.log(marker.getPosition().toUrlValue(6));
  }

  function handleEvent(event) {
    console.log(marker.getPosition().toUrlValue(6));
  }

}

#map {
  height: 100%;
}

html,
body {
  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?callback=initMap"></script>
&#13;
&#13;
&#13;