谷歌地图:限制拖动

7

我正在尝试重新创建此处演示的平移限制行为: 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> 

有没有人愿意帮我看看是否有遗漏的地方? :D

(在StackOverflow上有另一个最新的版本3的代码,名为“如何限制Google Maps API V3中的平移?”但是该行为在视觉上会“弹回”,而不仅仅是限制超出边界的移动。)


尝试查看此帖子:https://dev59.com/5m865IYBdhLWcg3wa-A0 - Leonardo Gandini
2个回答

2

这不是Zoom安全的方法。 - Timo Kähkönen

0

在agm-map中有一个名为restriction的属性。restriction是MapRestriction类型。 您可以在此处找到此属性的API文档。 根据文档所述,restriction属性限制了超出我们定义的限制范围的平移和缩放。以下是一个示例。

restriction: {
    latLngBounds:{
      north: 85.0, 
      south: -85.0, 
      west: -180.0, 
      east: 180.0
    },
    strictBounds : true
  }

我正在使用Angular。将该对象传递以限制平移操作非常简单。


如何将带有纬度和经度的地图包含进来?我已经定义了纬度和经度,而不是“north”等等。并且我使用了[restriction]="restriction"绑定了值,但它没有起作用。 - Sai Manoj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接