【问题标题】:How can I tell which marker is being dragged an a Google Maps API drag event?如何判断在 Google Maps API 拖动事件中拖动了哪个标记?
【发布时间】:2011-11-14 01:27:22
【问题描述】:

Google Maps V3 API 中的“drag”、“dragstart”和“dragend”事件都将 mouseEvent 传递给注册的回调函数。

但是 - 此事件不包含关于 哪个标记 被拖动的任何信息。我该如何确定?

如果您只是查看“dragend”事件,这将更加复杂 - 它只有 new 坐标,甚至无法从坐标推断。

我认为必须有一种简单的方法来确定正在拖动的标记...

【问题讨论】:

    标签: google-maps google-maps-api-3


    【解决方案1】:

    我会在创建时使用侦听器将拖动事件附加到标记。

    google.maps.event.addListener(marker, 'dragend', function() {
                    //do something with the event.
                });
    

    这是一个示例小提琴:http://jsfiddle.net/2YQg6/10/ (不要介意我刚刚编辑过的其他东西,我以前用过一个小提琴来处理可拖动的标记。)

    相关代码在标记创建循环中:

    //geo code and build markers for each list item.
    for (var i = 0; i < $listItems.length; i++) {
        geocoder.geocode({
            'address': $($listItems[i]).text()
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    draggable: true,
                    originalPos: results[0].geometry.location
                });
    
                google.maps.event.addListener(marker, 'dragend', function() {
                    infoWindow.setContent("marker originally at this position: " + this.originalPos + " was dragged to: " + this.position);
                    infoWindow.open(map, this);
                });
    
    
                markers.push(marker);
            }        
    
    });
    }
    

    【讨论】:

    • 长话短说,监听函数中的“this”关键字将指向您的标记
    • 不能过分强调 Dannys 评论的有用性,因为我在 Google 文档的任何地方都找不到该信息。
    • this 不会出现在 Google 的文档中,因为它是 JavaScript 语言的一部分。 stackoverflow.com/questions/3127429/javascript-this-keyword
    • @Bryan Weaver ...如何使用 ES6 的匿名函数语法找到标记实例,即使用 ()=>{ } 作为 dragend 事件处理程序?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2015-02-08
    • 1970-01-01
    • 2014-02-12
    • 2015-10-27
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多