我正在与 Google Maps
合作现在,我希望能够禁止用户将 map 拖出指定的边界。
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.00, 14.07),
new google.maps.LatLng(54.50, 24.09)
);
我该怎么办?我尝试使用 drag
事件但没有运气..
google.maps.event.addListener(map, 'drag', function() {
if (
!strictBounds.contains(map.getBounds().getNorthEast())
|| !strictBounds.contains(map.getBounds().getSouthWest())
) {
// map is out of bounds here
}
});
如何停止用户对 strictBounds
的拖动?
最佳答案
您可能想改为监听 dragend
事件,如果 map 被拖动到允许的边界之外,请将其移回到允许的边界内。很高兴您使用 LatLngBounds
对象来定义边界,因为您将能够使用 contains()
方法,如果给定的 lat/lng 参数在边界内,该方法将返回 true。
您可能还应该限制缩放级别,因为通过缩小,用户仍然能够“看到”边界之外的 map 。
因此,您可能需要尝试以下示例:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Limit Panning</title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var minZoomLevel = 5;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(28.70, -127.50),
new google.maps.LatLng(48.85, -55.90));
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function() {
if (strictBounds.contains(map.getCenter())) return;
// Out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
</script>
</body>
</html>
上述示例的屏幕截图。在这种情况下,用户将无法向南或远东拖动:
关于javascript - 强制停止 map 拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3194323/