2012-06-21 88 views
2

目前,我有我的谷歌地圖這個監聽事件(API V3):谷歌地圖API V3「dragend」觸發的事件不止那些

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」函數發生多次。 有誰知道這個問題?

+0

我猜你在'FixexMarkerInCenter'和'FixedMarkerInCenterZoom'中調用了'FindReverseGeocode',這導致了很多對'FindReverseGeocode'的調用。 –

回答

-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> 
2

誠然,這是相當惱人的,但..不要絕望,只是還沒有 - 你可以用簡單的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來克服它。請享用!