区分标记映射api v3

Distinguish markers maps api v3

本文关键字:api v3 映射      更新时间:2023-09-26

im创建了一个带有地理编码和反向地理编码的路由淋浴。工作得很好,但当我想拖动标记时,我想用更新的地址更新正确的输入。问题是我无法确定起点和终点。使用下面的代码,如果我只有一个点,它会正确地更新起始地址,但在添加另一个点后,它们都开始更新相同的输入。(不知道我是否有一个好主意来区分它们的属性-我把这些点添加到数组中,根据它的长度,它应该用"start"或"stop"添加属性destination。似乎在添加第二个标记后,它会更新上一个标记的destination值)。

function placeMarker(location) {
if(list.length < 2) {
    marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable:true,
        animation: google.maps.Animation.DROP,
        destination: 'start'
    });
    map.setCenter(location);
    list.push(marker);
    if (list.length == 2) {
        list[1].destination = 'stop';
    };
    geocoder.geocode({'latLng': location}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                if(list.length == 1) {
                    $('#start').val(results[0].formatted_address);
                } else {
                    $('#end').val(results[0].formatted_address);
                }
            }
        }
    });
}
if (list.length == 2) {
    drawRoute(list[0].getPosition(), list[1].getPosition());
};
google.maps.event.addListener(marker, 'drag', function(event) {
    console.log(marker.destination);
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (marker.destination == 'start') {
                $("#start").val(results[0].formatted_address);
            } else {
                $("#end").val(results[0].formatted_address);
            }
        }
    });
});
};

谢谢你的帮助!

您只将eventListener附加到一个标记,而不是

google.maps.event.addListener(marker, 'drag', function(event){...})

你应该做一些类似的事情

google.maps.event.addListener(list[0], 'drag', function(event){...})
google.maps.event.addListener(list[1], 'drag', function(event){...})

并且每次创建标记时都应该附加这些侦听器。