使用AJAX控件的v7限制Bing地图上的最小/最大缩放?

Ben*_*anc 9 ajax zoom bing-maps

我正在开发一个使用Bing Maps AJAX Control v7的网站.我需要做的一件事是限制缩放级别,以防止用户放大超过一定级别,或缩小超过一定级别.

我在Map对象上找到了一个"getZoomRange"方法,在检查它之后,它只返回一个具有"min"和"max"属性的对象文字.所以,我认为重载它可能会做的伎俩:

// "map" is our Bing Maps object
map.getZoomRange = function ()
{
  return {
    max:      14
    min:      5
  };
};
Run Code Online (Sandbox Code Playgroud)

...但不是.它没有任何效果(它实际上与使用默认仪表板时缩放滑块的外观有关).

劫持事件并阻止它继续进行似乎也没有效果.

Ben*_*anc 10

根据Bing Maps的支持,唯一的方法(不是特别优雅,并在地图上产生一些不受欢迎的抖动)如下:

// "map" is our Bing Maps object, overload the built-in getZoomRange function
// to set our own min/max zoom
map.getZoomRange = function ()
{
  return {
    max:      14,
    min:      5
  };
};

// Attach a handler to the event that gets fired whenever the map's view is about to change
Microsoft.Maps.Events.addHandler(map,'viewchangestart',restrictZoom);

// Forcibly set the zoom to our min/max whenever the view starts to change beyond them 
var restrictZoom = function ()
{
  if (map.getZoom() <= map.getZoomRange().min) 
  {
    map.setView({
      'zoom':       map.getZoomRange().min,
      'animate':    false
    });
  }
  else if (map.getZoom() >= map.getZoomRange().max) 
  {
    map.setView({
      'zoom':       map.getZoomRange().max,
      'animate':    false
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

  • Bing Maps API v7更新的原因之一就是打破了这一点.在大多数情况下它仍然可以正常工作,但如果用户使用鼠标滚轮积极地放大或缩小,"viewchangestart"事件并不总能正确捕获.我的修复是在"viewchangestart"和"viewchange"事件上调用"restrictZoom"函数.我也不检查缩放是否为"> ="或"<="; 我更确切地说,检查缩放是">"还是"<".在我发现的所有例子中,这是最好的. (4认同)

And*_*rey 10

我正在处理一个类似的问题,我最终做了一些非常类似于MrJamin在他的回答中描述的东西,有一个(微妙的,但主要的)差异:我添加了一个处理程序targetviewchanged.根据MSDN 上的官方文档,'targetviewchanged' occurs when the view towards which the map is navigating changes.而且,Map#getZoom我没有打电话,而是使用了Map#getTargetZoom哪一个returns the zoom level of the view to which the map is navigating.注意,这种方法可以防止抖动.

这是我的代码的缩短版本:

function restrictZoom(map,min,max) {
  Microsoft.Maps.Events.addHandler(map,'targetviewchanged',function(){
    var targetZoom = map.getTargetZoom();
    var adjZoom = targetZoom;

    if(targetZoom > max) {
      adjZoom = max;
    } else if(targetZoom < min) {
      adjZoom = min;
    }

    if(targetZoom != adjZoom) {
      map.setView({zoom:adjZoom});
    }
  });
}
Run Code Online (Sandbox Code Playgroud)