谷歌地图api v3“dragend”事件不止一次

时间:2012-06-21 12:22:49

标签: google-maps-api-3

目前我在谷歌地图(api v3)上有这个监听器事件:

google.maps.event.addListener(Map, 'center_changed', FixedMarkerInCenter);
google.maps.event.addListener(Map, 'zoom_changed', FixedMarkerInCenterZoom);
google.maps.event.addListener(Map, 'dragend', FindReverseGeocode });

问题是'dragend'事件触发了多次(至少四次)并且函数'FindReverseGeocode'多次发生。 有谁知道这个问题?

2 个答案:

答案 0 :(得分:4)

是的,这很烦人但是......不要绝望 - 你可以用简单的JavaScript修复它:

map.dragInProgress = false; //adding flag to already existing map object to keep DOM clean
google.maps.event.addListener(map, 'dragend', function() {
  if(map.dragInProgress == false) { //only first shall pass
    map.dragInProgress = true;
    window.setTimeout(function() {
        console.log('Note how you will see this console message only once.');
        //cast your logic here
        map.dragInProgress = false; //reset the flag for next drag
    }, 1000);
  }
});

简而言之,这使您每秒只能接收一次dragend事件。确保您的脚本不会在逻辑中间死亡,或者首先是最后一次拖动。您可以使用try / catch / finally来克服这个问题。享受!

答案 1 :(得分:-1)

我支持我的评论,但这是一张实现center_changed(带标记)和dragend带地理编码器的基本地图。

在IE9,Chrome 19和Firefox 13中,dragend事件仅在每次拖动时触发一次。您会注意到center_changed被多次触发,即使拖动未完成。这就是为什么我认为您在FindReverseGeocode中调用了FixedMarkerInCenter方法。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' type='text/javascript'></script>
<script type="text/javascript"></script>
</head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var map;
var geocoder;

function initialize()
{
    var latlng = new google.maps.LatLng(47.6059399181561, 14.747812500000007);
    map = new google.maps.Map(document.getElementById('map'), {
      zoom:6,
      center:latlng,
      mapTypeId:google.maps.MapTypeId.HYBRID
    });

    google.maps.event.addListener(map, 'center_changed', placeMarker);
    google.maps.event.addListener(map, 'dragend', reverseLookup);

    geocoder = new google.maps.Geocoder();
}

function placeMarker()
{
    var center = map.getCenter();
    marker = new google.maps.Marker({
      map:map,
      position: center
    });
}

function reverseLookup()
{
    geocoder.geocode({'latLng': map.getCenter()}, function(results, status)
    {
      if (status == google.maps.GeocoderStatus.OK)
      {
        document.getElementById('area').value = 
        results[results.length-1].formatted_address + " " +
        map.getCenter() + "\r\n" + document.getElementById('area').value;
      }
    });
}

</script>
<body onLoad="initialize()">
<div id="map" style="width: 800px; height: 350px;"></div>
<textarea id='area' cols='80' rows='5'></textarea>
</body>
</html>