banner
陈不易

陈不易

没有技术想聊生活
twitter
medium
tg_channel

在 OpenLayers 中僅限於水平平移的地圖

我們通常使用 2D 地圖,實際上,有許多可用的網頁地圖庫,例如 openlayersleafletmapbox-gl-js。我將介紹一種在 openlayers 中製作僅水平地圖的方法。
要控制地圖僅水平平移,我們必須掛鉤這些交互:panwheel scroll zoom
openlayers 使用的默認交互可以在以下鏈接中找到:

禁用默認交互#

第一步,我們禁用地圖的默認交互。

const map = new Map({  
  ...
  interactions: defaultInteractions({  
    dragPan: false,  
    mouseWheelZoom: false,  
    doubleClickZoom: false  
  })
  ...
}

應用此選項後,地圖將無法再被控制,這正是我們所期望的。

掛鉤交互#

拖動平移#

我們首先創建一個自定義的平移交互,從 DragPan 擴展而來。
默認交互實現了 3 個方法來處理 Drag EventPointer UpPointer Down 事件。Drag Event 處理程序包含 坐標計算。換句話說,我們需要覆蓋一個新的 handleDragEvent

class Drag extends DragPan {  
  constructor() {  
    super();  
    this.handleDragEvent = function (mapBrowserEvent) {  
      ...
          const delta = [  
            this.lastCentroid[0] - centroid[0],  
            // centroid[1] - this.lastCentroid[1],  
            0  
          ];  
     ...
    }

centroid 的第二個元素存儲 y 坐標,因此,我們註釋掉有關 y delta 的行並將其設置為零。

const map = new Map({  
...
interactions: defaultInteractions({  
  dragPan: false,  
  mouseWheelZoom: false,  
  doubleClickZoom: false  
}).extend([new Drag()]),
...
})

defaultInteractions 函數之後添加自定義的拖動交互,我們的地圖現在可以使用鼠標拖動進行平移。

滾輪縮放#

根據拖動平移部分,我們可以輕鬆找到 MouseWheelZoom 的坐標計算行。
它們出現在 L187-L189,在 handleEvent 方法中進行一些小調整:

const coordinate = mapBrowserEvent.coordinate;  
const horizontalCoordinate = [coordinate[0], 0]  
this.lastAnchor_ = horizontalCoordinate;

與 dragPan 相同,我們在默認交互後添加自定義的 MouseWheelZoom 交互 Zoom

const map = new Map({  
...
interactions: defaultInteractions({  
  dragPan: false,  
  mouseWheelZoom: false,  
  doubleClickZoom: false  
}).extend([new Drag(),new Zoom]),
...
})

現在,我們的地圖可以使用鼠標滾輪縮放,並且僅在水平方向上工作。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。