Skip to content

Panning 与 page scrolling ​

Panning 与 page scrolling示例。 trackpad mousewheel 缩放 scroll page

本示例展示了一种常见的页面滚动行为:在触控设备上,当单指放在地图上时,可用于滚动页面,只有双指才会执行拖拽平移。对于鼠标或触控板设备,按下平台修饰键(Cmd 或 Ctrl)才能在地图上拖拽平移,否则页面将滚动。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {platformModifierKeyOnly} from 'ol/events/condition.js';
import DragPan from 'ol/interaction/DragPan.js';
import MouseWheelZoom from 'ol/interaction/MouseWheelZoom.js';
import {defaults} from 'ol/interaction/defaults.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';

const map = new Map({
  interactions: defaults({dragPan: false, mouseWheelZoom: false}).extend([
    new DragPan({
      condition: function (event) {
        return this.getPointerCount() === 2 || platformModifierKeyOnly(event);
      },
    }),
    new MouseWheelZoom({
      condition: platformModifierKeyOnly,
    }),
  ]),
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>拖拽平移与页面滚动</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "two-finger-pan-scroll",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}