您是否可以请一看这段代码并告诉我为什么我无法将drag
和dragend
事件附加/绑定到可拖动标记?
我正在
未捕获的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);
}
答案 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());
}
代码段
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;