谷歌地图-拖动标记,GetPosition总是返回相同的位置

Google Maps - Drag marker, GetPosition returning same position always

本文关键字:返回 位置 GetPosition 拖动 谷歌地图      更新时间:2023-09-26

所以我有一个for循环,它创建了100多个标记。当我拖动一个随机标记时,我总是在控制台中得到相同的位置。但是当我拖动另一个标记时,"点"值不同。所以问题是为什么我总是处于同样的位置?如果我只尝试使用1个标记,则代码正在工作。

一段代码:

coordinates.forEach(function(entry) {   
    if(!isOdd(number)){
        marker_lat = entry;
        number++;
    }else{
        marker_lng = entry;             
        var myLatlng = new google.maps.LatLng(parseFloat(marker_lat),parseFloat(marker_lng));
        marker_icon = "red.png";
          mark = new google.maps.Marker({
           position: myLatlng,
           map: map,
           title: number,
           icon: marker_icon,  
           draggable:true
         });                
        number++;
        google.maps.event.addListener(mark, 'dragend', function() { 
                id_point = $(this).attr("title");
                console.log("Point: "+id_point);
                console.log(mark.getPosition().lat());// Always the same position
                console.log(mark.getPosition().lng());// Always the same position
        });
    }
}); 

侦听器将标记作为参数传递给函数。试试这个代码:

google.maps.event.addListener(mark, 'dragend', function(m) { 
    id_point = $(this).attr("title");
    console.log("Point: "+id_point);
    console.log(m.latLng.lat());
    console.log(m.latLng.lng()); /* different from your
                                    code.  Can't really
                                    test right now, but
                                    this seems to work on
                                    the last project I
                                    did. */
});

除此之外,您还可以在this:上调用getPosition()

google.maps.event.addListener(mark, 'dragend', function(m) { 
    id_point = this.title;
    console.log("Point: "+id_point);
    console.log(this.getPosition().lat()); // same as below
    console.log(m.latLng.lat());
});