我们通常使用 2D 地图,实际上,有许多可用的网页地图库,比如 openlayers、leaflet 或 mapbox-gl-js。我将介绍一种在 openlayers 中制作仅支持水平平移地图的方法。
要控制地图仅支持水平平移,我们必须挂钩这些交互:pan
、wheel scroll zoom
。
openlayers 使用的默认交互可以在以下链接中找到:
- dragPan: DragPan.js
- mouseWheelZoom: MouseWheelZoom.js
禁用默认交互#
第一步,我们禁用地图的默认交互。
const map = new Map({
...
interactions: defaultInteractions({
dragPan: false,
mouseWheelZoom: false,
doubleClickZoom: false
})
...
}
应用此选项后,地图将无法再被控制,这正是我们所期望的。
挂钩交互#
拖动平移#
我们首先创建一个自定义的平移交互,扩展自 DragPan
。
默认交互实现了 3 个方法来处理 Drag Event
、Pointer Up
、Pointer 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
];
...
}
质心的第二个元素存储 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]),
...
})
现在我们的地图可以使用鼠标滚轮进行缩放,并且仅在水平方向上工作。