We usually use 2d map, actually, there are many avaliable web map library such like openlayers, leaflet, or mapbox-gl-js. I’ll introduce a method to make a horizontal only map in openlayers.
To control map horizontal only, we have to hook these interactions: pan
, wheel scroll zoom
.
The default interaction openlayers use above can be found in follow link:
The first step, we disable the default interaction of map.
1const map = new Map({
2 ...
3 interactions: defaultInteractions({
4 dragPan: false,
5 mouseWheelZoom: false,
6 doubleClickZoom: false
7 })
8 ...
9}
After apply this option, the map can’t be controlled anymore, this what we suppose.
We first create a custom pan interaction extented from DragPan
.
The default interaction implement 3 method to handle Drag Event
, Pointer Up
, Pointer Down
event. The Drag Event
handler contains the coordinate compute. in other word, we need overide a new handleDragEvent
.
1class Drag extends DragPan {
2 constructor() {
3 super();
4 this.handleDragEvent = function (mapBrowserEvent) {
5 ...
6 const delta = [
7 this.lastCentroid[0] - centroid[0],
8 // centroid[1] - this.lastCentroid[1],
9 0
10 ];
11 ...
12 }
The centroid second element storage the y coordinate, thus ,we comment the line about y delta and set zero to it.
1const map = new Map({
2...
3interactions: defaultInteractions({
4 dragPan: false,
5 mouseWheelZoom: false,
6 doubleClickZoom: false
7}).extend([new Drag()]),
8...
9})
Add the custom drag interaction after defaultInteractions
funtion, and our map now can be paned use mouse drag.
According the drag pan section, we can easily found the coordinate compute line of the MouseWheelZoom
.
They appearing at L187-L189, do a little tweak in handleEvent
method:
1const coordinate = mapBrowserEvent.coordinate;
2const horizontalCoordinate = [coordinate[0], 0]
3this.lastAnchor_ = horizontalCoordinate;
Same as dragPan, we add custom MouseWheelZoom
interaction Zoom
after default interactions.
1const map = new Map({
2...
3interactions: defaultInteractions({
4 dragPan: false,
5 mouseWheelZoom: false,
6 doubleClickZoom: false
7}).extend([new Drag(),new Zoom]),
8...
9})
Now our map can zoom use mouse wheel, and it only work in horizontal direction.