Openlayers + Vue 实现自定义鼠标右键为改变视图角度事件
效果:
持续按下鼠标右键再拖动鼠标可以实现变换视图的角度
(openlayers的样式被我改了一下,看上去有点像ArcGIS API for JS 4.x的样式)
关键点
Vue里面如何阻止浏览器的默认右键事件
如何阻止openlayers自带的鼠标点击拖动地图事件
1.Vue里面如何阻止浏览器的默认右键事件
这里有一个坑,下面的代码是无效的,不能阻止浏览器的默认右键事件
html:
<div id="map"
class="w-100"
@mousedown.prevent.right.prevent="changeRotation('down',$event)"
@mousemove="changeRotation('move',$event)"
@mouseup.prevent.right.prevent="changeRotation('up',$event)"></div>
JavaScript:
//methods中
...
changeRotation:function(type,event){
event.preventDefault();
event.stopPropagation();
......
},
...
.prevent修饰符对mousedown和mouseup是无效的
正确的办法是:
只需要在html上增加: @contextmenu.prevent=""
<div id="map"
class="w-100"
@contextmenu.prevent=""
@mousedown.right="changeRotation('down',$event)"
@mousemove="changeRotation('move',$event)"
@mouseup.right="changeRotation('up',$event)"></div>
不需要在methods添加代码
2.如何阻止openlayers自带的鼠标点击拖动地图事件
这里要在用户按住右键和按住右键移动鼠标时禁止拖动地图事件,松开后恢复点击拖动地图事件(openlayers自带的点击事件是不区分鼠标左右键的)
这个changeRotation的具体代码:
// 改变视图方向
changeRotation:function(type,event){
// 点击默认的移动地图事件
let pan=null;
this.map.getInteractions().forEach(function(element, index, array) {
if(element instanceof ol.interaction.DragPan) {
pan = element;
}
});
// 右键按下
if (type==="down") {
this.activeMouseRight=true;
// 禁用地图拖动事件
pan.setActive(false);
}
else if (type==="move") {
// 首先判断右键是否被按下
if (this.activeMouseRight) {
/*
* 计算角度
*/
let mapCenter={
x:$("#map").width()/2+$("#map").offset().left,
y:$("#map").height()/2+$("#map").offset().top,
},
clickPoint={
x:event.screenX,
y:event.screenY,
};
let radian=Math.atan((clickPoint.y-mapCenter.y)/(clickPoint.x-mapCenter.x));
if (radian<Math.PI*0.5&&radian>Math.PI*-0.5) {
// 设置角度
this.map.getView().setRotation(radian);
}
}
}
// 右键松开
else if (type==="up") {
this.activeMouseRight=false;
// 启用地图拖动事件
pan.setActive(true);
}
},
这里将openlayers中的ol.Map类绑定成了Vue对象的一个属性
html:
<div id="map"
class="w-100"
@contextmenu.prevent=""
@mousedown.right="changeRotation('down',$event)"
@mousemove="changeRotation('move',$event)"
@mouseup.right="changeRotation('up',$event)"></div>
原文链接:https://blog.csdn.net/DSH964/article/details/86010177