以下代碼示例讓我感到困惑。這是我可以用來演示我的問題的一段較大代碼的最簡單版本。基本上我希望用戶能夠通過按住鼠標鍵並拖動來繪製邊界框。如果在mouseMove事件中重繪了矩形,GoogleMaps會丟失mouseUp事件
如果我使用mouseMove函數中的setBounds重繪了rectange,我從來沒有看到mouseUp事件!如果我禁用mouseMove函數中的矩形重畫,我得到mouseUp事件。我可以通過在mouseUp事件中繪製矩形來部分解決此問題,但用戶在拖動框時看不到輪廓。
您可以在http://www.geoffschultz.org/Test/bounding_box.html
這裏看到此代碼的樣本代碼:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#mapdiv { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map, mouseDownPos, gribBoundingBox = "", mouseIsDown = 0;
function display_map()
{
var latlng = new google.maps.LatLng(42, -71);
var myOptions = {zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById("mapdiv"), myOptions);
google.maps.event.addListener(map,'mousemove',function(event) {mouseMove(event);});
google.maps.event.addListener(map,'mousedown',function(event) {mouseDown(event);});
google.maps.event.addListener(map,'mouseup',function(event) {mouseUp(event);});
}
function mouseMove(event)
{
if (mouseIsDown)
{
if (gribBoundingBox) // box exists
{
var bounds = new google.maps.LatLngBounds(gribBoundingBox.getBounds().getSouthWest(), event.latLng);
gribBoundingBox.setBounds(bounds); // If this statement is enabled, I lose mouseUp events
}
else // create bounding box
{
var bounds = new google.maps.LatLngBounds(mouseDownPos, event.latLng);
gribBoundingBox = new google.maps.Rectangle({map: map, bounds: bounds, fillOpacity: 0.05, strokeWeight: 1});
}
}
}
function mouseDown(event)
{
mouseIsDown = 1;
mouseDownPos = event.latLng;
map.setOptions({draggable: false});
}
function mouseUp(event)
{
if (mouseIsDown)
{
mouseIsDown = 0;
map.setOptions({draggable: true});
// var bounds = new google.maps.LatLngBounds(mouseDownPos, event.latLng);
// gribBoundingBox.setBounds(bounds); // If used instead of above, box drawn properly
gribBoundingBox.setEditable(true);
}
}
</script>
</head>
<body onload="display_map()">
<div id="mapdiv" style="width:100%; height:100%"></div>
</body>
</html>
Tomik, 非常感謝這個答案。這工作得很好,如果沒有你的洞察力,我永遠都不會想到這一點。解決方案1完美工作。 – GeoffSchultz