简体   繁体   English

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

[英]Google Maps - Drag marker, GetPosition returning same position always

So I have a for loop which creates more than 100 markers.所以我有一个 for 循环,它创建了 100 多个标记。 When I drag a random marker I get always the same position written in the console.当我拖动一个随机标记时,我总是在控制台中写入相同的位置。 But the "Point" value is different when I drag another marker.但是当我拖动另一个标记时,“点”值是不同的。 So the question is why I am getting always the same position?所以问题是为什么我总是得到相同的位置? If I try with only 1 marker, the code is working.如果我只尝试使用 1 个标记,则代码正在运行。

Piece of code:一段代码:

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
        });
    }
}); 

The marker is passed as a parameter to the function by the listener.标记作为参数由侦听器传递给函数。 Try this code:试试这个代码:

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. */
});

In addition to this, you can also call getPosition() on this :除此之外,您还可以拨打getPosition()this

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());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM