簡體   English   中英

OpenLayers:將 map 鎖定到向量的范圍

[英]OpenLayers: lock map to the vector's extents

我正在學習如何使用 OpenLayers 在 JavaScript 中創建一個庫。 通常我使用下面的代碼將我的 map 鎖定在手動傳遞的矢量范圍上。

var minX= 3.0025038498794938;
var minY= 47.7706339888675302;
var maxX= 5.1702255722362533;
var maxY= 49.5690401585264695;
var maxExtent = [minX, minY, maxX, maxY];
var boundary = ol.proj.transformExtent(maxExtent, 'EPSG:4326', 'EPSG:3857');
var center = ol.proj.transform([4.0863647111, 48.6698370737], 'EPSG:4326', 'EPSG:3857');

var view = new ol.View({
  extent: boundary,
  center: center,
  zoom: 9,
  maxZoom: 18,
  minZoom: 8,
});
map.setView(view);

我的目標是使用相同的哲學,但使用特定 function 內的矢量范圍。我能夠在矢量擴展的縮放上加載 map:

function getPolygonsExtent() {
  vectorsLayer.getSource().once('change', function(evt) {
    if (vectorsLayer.getSource().getState() === 'ready') {
      if (vectorsLayer.getSource().getFeatures().length > 0) {
        extent = vectorsLayer.getSource().getExtent();
        options = {
          size: map.getSize(),
          padding: [0, 0, 0, 0],
        }
        map.getView().fit(extent, options);
      }
    }
  });
};

但我不知道如何才能實現我的目標。 我以為有一個 function 像map.getView().setExtent(extent); ,但事實並非如此。 有什么建議么?

沒有setExtent()方法,因此您需要創建一個新視圖

  map.getView().fit(extent, options);
  var newView = new ol.View({
    extent: extent,
    showFullExtent: true,
    center: map.getView().getCenter(),
    zoom: map.getView().getZoom(),
    maxZoom: 18,
    minZoom: 8,
 });
 map.setView(newView);

fit()方法適合 map 內的范圍,但默認情況下,范圍選項將 map 限制在范圍內,使用showFullExtent以獲得與fit()類似的行為。 如果您的適合選項包括一個duration ,您還需要一個callback來更新視圖,當它在內聯代碼中完成時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM