根据极值点自动缩放

Automatic zoom depending on extreme points

我用的是OL 4.6.5.

我在矢量图层中放置了一些标记,并使用自制的东西来找到缩放,这取决于标记放置的距离(来自数据库的点)。这很笨拙但很管用...

现在我正在寻找一个函数或其他方法来自动设置缩放,这取决于最大和最小纬度和经度。我无法使 "fitExtent()" 正常工作,所以我查看了这里,找到了两个解决方案,但我只能使用这个:

var onChangeKey = vectorSource.on('change', function() {   if
(vectorSource.getState() == 'ready') {
    vectorSource.unByKey(onChangeKey);
    map.getView().fitExtent(vectorSource.getExtent(), map.getSize());   } });

它使用 "fitExtent()" 的方式与我不同,但不幸的是它并没有改变 2 的缩放比例。另一种解决方案是一些奇怪的语言??? JS 控制台报告:"Uncaught SyntaxError: Unexpected identifier".

这里有一个示例页面:https://xerxx.se/zoomtest.html JScode 在底部。我尝试过的两种解决方案都在那里,上面引用的是"in action"。 我自己的笨拙代码也在那里 - 你会看到它。

这一定有一个聪明的命令,对吧?

此处不需要您在代码中采用的语法,因为 vectorSource.on('change', function() { 仅在异步加载源(Ajax 调用)时才重要。

您的代码是同步的,例如

var vectorSource = new ol.source.Vector({
    features: [placeOSM[1], placeOSM[2]]
});
...

替换方块

var onChangeKey = vectorSource.on('change', function() {
  if (vectorSource.getState() == 'ready') {
    vectorSource.unByKey(onChangeKey);
    map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
  }
});

// fitExtent is now fit and second arg map.getSize() is now optional
// e.g http://openlayers.org/en/latest/apidoc/ol.View.html#fit 
map.getView().fit(vectorSource.getExtent());