这篇展示了如何在地图上添加第二次按下鼠标移动鼠标实现拖拽缩放地图效果。
官网demo地址:
Double click, Drag and Zoom
官网介绍文字的翻译如下:
示例比较简单,直接贴代码:
const map = new Map({//添加第二次点击拖拽缩放地图interactions: defaultInteractions().extend([new DblClickDragZoom()]),layers: [new Tile({source: new XYZ({url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",}),}),],target: "map",view: new View({center: [0, 0],zoom: 2,}),});
interactions属性用来设置地图上的交互,DblClickDragZoom就是第二次按下鼠标拖拽缩放的类。
鼠标双击放大事件是openlayers自带的,如果要取消,需要这样写:
// 禁用双击放大interactions: defaultInteractions({doubleClickZoom: false, }),
完整代码:
<template><div class="box"><h1>Double click, Drag and Zoom</h1><div id="map"></div></div>
</template><script>
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import View from "ol/View.js";
import Tile from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import {DblClickDragZoom,defaults as defaultInteractions,
} from "ol/interaction.js";
export default {data() {return {map: null,};},methods: {initMap() {const map = new Map({//添加第二次点击拖拽缩放地图interactions: defaultInteractions().extend([new DblClickDragZoom()]),// 禁用双击放大// interactions: defaultInteractions({// doubleClickZoom: false, // }),layers: [new Tile({source: new XYZ({url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",}),}),],target: "map",view: new View({center: [0, 0],zoom: 2,}),});},},mounted() {this.initMap();},
};
</script>
<style scoped>
#map {width: 100%;height: 500px;
}
.box {height: 100%;
}
</style>