谷歌地图:限制平移

Mar*_*c P 7 google-maps limit pan

我正在尝试重新创建pan限制行为,如下所示:http: //econym.org.uk/gmap/example_range.htm

不幸的是,它使用的是API版本2,而不是当前的版本3.我正在更新命令,以便它们是最新的,但我想我可能错过了一些东西,因为它不起作用:

<html> 
<body> 
<script type="text/javascript" src="http://meyouand.us/scripts/jquery-1.4.4.min.js"></script> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
$(document).ready(function() {

// Generate map
var latlng = new google.maps.LatLng(37.76201, -122.4375);
var myOptions = { zoom: 12, center: latlng, panControl: false, zoomControl: true, mapTypeControl: false, streetViewControl: false, scrollwheel: true, draggable: true, mapTypeId: google.maps.MapTypeId.TERRAIN };
var map = new google.maps.Map(document.getElementById("gmap"), myOptions);

// Limit panning

// The allowed region which the whole map must be within
var southWest = new google.maps.LatLng(37.684, -122.591);
var northEast = new google.maps.LatLng(37.836, -122.333);
var allowedBounds = new google.maps.LatLngBounds(southWest, northEast);

// Double check boundaries, plot points just in case
var sW = new google.maps.Marker({
    position: southWest, 
    map: map,
    title: "southWest"
});
var nE = new google.maps.Marker({
    position: northEast, 
    map: map,
    title: "northEast"
});

// Add a move listener to restrict the bounds range
google.maps.event.addListener(map, "dragend", function() { checkBounds(); });


// If the map position is out of range, move it back
function checkBounds() {
  // Perform the check and return if OK
  if (allowedBounds.contains(map.getCenter())) {
    return;
  }

  // It's not OK, so find the nearest allowed point and move there
  var C = map.getCenter();
  var X = C.lng();
  var Y = C.lat();

  var AmaxX = allowedBounds.getNorthEast().lng();
  var AmaxY = allowedBounds.getNorthEast().lat();
  var AminX = allowedBounds.getSouthWest().lng();
  var AminY = allowedBounds.getSouthWest().lat();

  if (X < AminX) {X = AminX; alert('hi') }
  if (X > AmaxX) {X = AmaxX; alert('hi') }
  if (Y < AminY) {Y = AminY; alert('hi') }
  if (Y > AmaxY) {Y = AmaxY; alert('hi') }
  alert ("Restricting "+Y+" "+X);
  map.setCenter(new LatLng(Y,X));
}

});
</script> 
<body> 

<div id="gmap" style="width: 480px; height: 440px;"></div>

</body> 
</html> 
Run Code Online (Sandbox Code Playgroud)

有人会介意另外一双眼睛,看看我是否错过了什么?:d

(StackOverflow上还有另一个最新的版本3代码,名为"我如何限制谷歌地图API V3中的平移?"然而,这种行为在视觉上"快照"而不是简单地限制超出边界的移动.)

Woj*_*ekT 2

使用这篇文章中的示例:Google 地图 v3 - 限制可视区域和缩放级别并将地图侦听器事件从 更改dragenddrag。我刚刚测试过它并且它按预期工作。

编辑:js fiddle 的示例