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

时间:2015-10-27 18:28:43

标签: javascript google-maps

所以我有一个for循环,可以创建超过100个标记。当我拖动一个随机标记时,我总是在控制台中写入相同的位置。但是" Point"拖动另一个标记时,值不同。所以问题是为什么我总能保持同样的立场?如果我只尝试使用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
        });
    }
}); 

1 个答案:

答案 0 :(得分:1)

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

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

除此之外,您还可以在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());
});