当前位置: 首页 > news >正文

OpenLayers 自定义拖动事件

前言

页面交互的复杂度体现系统使用的难易程度,在开发WebGIS系统过程中,总会涉及要素操作,如何设计才能使交互操作变得简洁呢?OpenLayers提供了一些成熟的交互控件可以做到,并且可以自定义交互事件。

1. 自定义交互类

创建拖动类Drag,并继承ol.interaction.Pointer类。在构造函数中初始化使用super函数初始化鼠标事件,然后设置坐标和鼠标样式。

PointerInteraction作为用户定义事件down、move、up的基类,管理着事件“拖动序列”。

当用户定义事件函数handleDownEvent返回true时,开始拖动序列,在拖动序列中,事件函数handleDragEvent在移动事件中被调用,当事件函数handleUpEvent被调用并返回false时,拖动序列结束。

class Drag extends ol.interaction.Pointer {constructor() {super({handleDownEvent,handleDragEvent,handleMoveEvent,handleUpEvent})// 要素坐标this.coordinate_ = null// 鼠标样式this.cursor_ = 'pointer'// 移动前鼠标样式this.previousCursor_ = undefined// 移动要素this.feature_ = null}
}

2. 鼠标交互事件

2.1. 鼠标按下事件

在鼠标按下事件中查询当前像素坐标点要素,从事件参数event中获取到map对象,通过调用forEachFeatureAtPixel方法获取目标位置要素对象,该方法接受两个参数,一个目标点象数坐标,另一个参数为函数对象,在该函数中返回查询要素。

如果在鼠标按下事件中查询到要素对象,则保存当前位置坐标和查询要素,设置返回条件为仅当查询到要素时才返回true,即当返回值为true时才可以进行拖动。

// 鼠标按下事件,返回'true'开始拖动
function handleDownEvent(evt) {const map = evt.mapconst feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {return feature})if (feature) {this.coordinate_ = evt.coordinatethis.feature_ = feature}// 仅当查询到要素时才可以进行拖动return !!feature
}

2.2. 鼠标拖动事件

在鼠标拖动事件中需要计算要素拖动距离,在移动事件中可以获取当前移动的鼠标坐标,将当前X、Y坐标和目标要素坐标做差得出偏移距离,然后获取到要素几何对象,通过translate方法设置几何对象偏移。最后更新要素坐标值。

//  鼠标拖动事件
function handleDragEvent(evt) {// 计算拖动距离const deltaX = evt.coordinate[0] - this.coordinate_[0]const deltaY = evt.coordinate[1] - this.coordinate_[1]const geometry = this.feature_.getGeometry()geometry.translate(deltaX, deltaY)// 更新位置坐标this.coordinate_[0] = evt.coordinate[0]this.coordinate_[1] = evt.coordinate[1]
}

2.3. 鼠标移动事件

在鼠标移动事件中切换鼠标样式。在查询到要素对象时,设置鼠标样式为自定义样式,并保存地图对象原来鼠标样式,在未查询到要素对象时恢复原来的鼠标样式。

// 鼠标移动事件
function handleMoveEvent(evt) {if (this.cursor_) {const map = evt.mapconst feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {return feature})// 获取地图对象绑定HTMLElementconst element = map.getTargetElement()if (feature) {if (element.style.cursor !== this.cursor_) {this.previousCursor_ = element.style.cursorelement.style.cursor = this.cursor_}} else if (this.previousCursor_ !== undefined) {element.style.cursor = this.previousCursor_this.previousCursor_ = undefined}}
}

2.4. 鼠标释放事件

在鼠标释放事件中返回false,重置要素和坐标值,结束拖动事件。

// 鼠标松开事件
function handleUpEvent(evt) {this.feature_ = nullthis.coordinate_ = nullreturn false
}

3. 加载拖动交互事件

加载交互事件有很多种方式,可以使用addInteraction方式加载,也可以获取交互对象进行加载。具体加载方式可以参考:OpenLayers 移动要素:

4. 完整代码

其中libs文件夹下的包需要更换为自己下载的本地包或者引用在线资源。

<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>OpenLayers 拖拽缩放和旋转</title><meta charset="utf-8" /><link rel="stylesheet" href="../../libs/css/ol9.2.4.css"><script src="../../js/config.js"></script><script src="../../libs/js/ol9.2.4.js"></script><style>* {padding: 0;margin: 0;font-size: 14px;font-family: '微软雅黑';}html,body {width: 100%;height: 100%;}#map {position: absolute;top: 50px;bottom: 0;width: 100%;}#top-content {position: absolute;width: 100%;height: 50px;line-height: 50px;background: linear-gradient(135deg, #ff00cc, #ffcc00, #00ffcc, #ff0066);color: #fff;text-align: center;font-size: 32px;}#top-content span {font-size: 32px;}</style>
</head><body><div id="top-content"><span>OpenLayers 自定义拖拽事件</span></div><div id="map" title="地图显示"></div>
</body></html><script>//地图投影坐标系const projection = ol.proj.get('EPSG:3857');//==============================================================================////============================天地图服务参数简单介绍==============================////================================vec:矢量图层==================================////================================img:影像图层==================================////================================cva:注记图层==================================////======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================////==============================================================================//const TDTImgLayer = new ol.layer.Tile({title: "天地图影像图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,attibutions: "天地图影像描述",crossOrigin: "anoymous",wrapX: false})})const TDTImgCvaLayer = new ol.layer.Tile({title: "天地图影像注记图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + TDTTOKEN,attibutions: "天地图注记描述",crossOrigin: "anoymous",wrapX: false})})const map = new ol.Map({target: "map",loadTilesWhileInteracting: true,view: new ol.View({center: [102.845864, 25.421639],zoom: 5,worldsWrap: false,minZoom: 1,maxZoom: 20,projection: 'EPSG:4326',}),layers: [TDTImgLayer, TDTImgCvaLayer],// 地图默认控件controls: ol.control.defaults.defaults({zoom: false,attribution: false,rotate: false}),// interactions: ol.interaction.defaults.defaults().extend([new Drag()])})map.on('click', evt => {console.log("获取地图坐标:", evt.coordinate)})class Drag extends ol.interaction.Pointer {constructor() {super({handleDownEvent,handleDragEvent,handleMoveEvent,handleUpEvent})// 要素坐标this.coordinate_ = null// 鼠标样式this.cursor_ = 'pointer'// 移动前鼠标样式this.previousCursor_ = undefined// 移动要素this.feature_ = null}}// 鼠标按下事件,返回'true'开始拖动function handleDownEvent(evt) {const map = evt.mapconst feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {return feature})if (feature) {this.coordinate_ = evt.coordinatethis.feature_ = feature}// 仅当查询到要素时才可以进行拖动return !!feature}//  鼠标拖动事件function handleDragEvent(evt) {// 计算拖动距离const deltaX = evt.coordinate[0] - this.coordinate_[0]const deltaY = evt.coordinate[1] - this.coordinate_[1]const geometry = this.feature_.getGeometry()geometry.translate(deltaX, deltaY)// 更新位置坐标this.coordinate_[0] = evt.coordinate[0]this.coordinate_[1] = evt.coordinate[1]}// 鼠标移动事件function handleMoveEvent(evt) {if (this.cursor_) {const map = evt.mapconst feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {return feature})const element = map.getTargetElement()if (feature) {if (element.style.cursor !== this.cursor_) {this.previousCursor_ = element.style.cursorelement.style.cursor = this.cursor_}} else if (this.previousCursor_ !== undefined) {element.style.cursor = this.previousCursor_this.previousCursor_ = undefined}}}// 鼠标松开事件function handleUpEvent(evt) {this.feature_ = nullthis.coordinate_ = nullreturn false}map.getInteractions().extend([new Drag()])// 创建要素对象const pointFeature = new ol.Feature(new ol.geom.Point([90.45461480466271,28.27171566587066]))const lineStringFeature = new ol.Feature(new ol.geom.LineString([[98.06070935932541, 31.773693479057368],[98.06070935932541, 18.823243159290566]]))const polygonFeature = new ol.Feature(new ol.geom.Polygon([[[105.62320775, 30.401227753660713],[114.27164739576722, 30.471610903957952],[114.27164739576722, 21.920091032793525],[105.62320775, 20.934729613526073]]]))// 创建矢量数据源const vectorSource = new ol.source.Vector({features: [pointFeature, lineStringFeature, polygonFeature]})// 创建矢量图层const vectorLayer = new ol.layer.Vector({source: vectorSource,style: {'icon-src': '../../image/point.png',// 'icon-size':[100,100],'icon-scale': 5,// 'icon-opacity': 0.95,// 'icon-anchor': [0.5, 46],'icon-anchor-x-units': 'fraction','icon-anchor-y-units': 'pixels','stroke-width': 5,'stroke-color': [0,255,204, 1],'fill-color': [255,204,0, 0.6],}})map.addLayer(vectorLayer)</script>

OpenLayers示例数据下载,请回复关键字:ol数据

全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试

【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。

欢迎访问我的博客网站-长谈GIShttp://shanhaitalk.com

都看到这了,不要忘记点赞、收藏 + 关注

本号不定时更新有关 GIS开发 相关内容,欢迎关注 !

http://www.dtcms.com/a/263118.html

相关文章:

  • Webpack优化详解
  • 运营商智能化升级:破局客服、外呼、质检的“数智神经中枢”革命
  • torchvision中的数据使用
  • Maven 中,dependencies 和 dependencyManagement
  • 临床试验中基线数据缺失的处理策略
  • synetworkflowopenrestydpdk
  • Spring Boot + ONNX Runtime模型部署
  • 6阶段实现最强RAG 模块化检索增强 实践指南
  • [springboot系列] 探秘JUnit 5: Java单元测试利器
  • Redis 和 Mysql 如何保证数据一致性
  • 底盘结构---履带式运动模型
  • 快速手搓一个MCP服务指南(八):FastMCP 代理服务器:构建灵活的 MCP 服务中介层
  • HTML<input>元素详解
  • 《用奥卡姆剃刀原理,为前端开发“减负增效”》
  • 《微信生态裂变增长利器:推客小程序架构设计与商业落地》
  • python训练day45 Tensorborad使用介绍
  • Linux 日志监控工具对比:从 syslog 到 ELK 实战指南
  • 阶段二开始-第一章—8天Python从入门到精通【itheima】-121节+122节(函数和方法的类型注解+Union联合类型注解)
  • 【运维系列】【ubuntu22.04】安装GitLab
  • 2025年光学工程、精密仪器与光电子技术国际会议(OEPIOT 2025)
  • Armbian 25.5.1 Noble Gnome 开启远程桌面功能
  • 百度文心ERNIE 4.5 大模型系列正式开源
  • Windows 安装 nodejs npm
  • 数据生命周期管理实战:建、用、管、存、归档到销毁的全流程治理
  • 如何用废弃电脑变成服务器搭建web网站(公网访问零成本)
  • 24V转12V降压实际输出12.11V可行性分析
  • GitHub Actions配置python flake8和black
  • 云手机的用途都有哪些?
  • 51c大模型~合集144
  • 赋能低压分布式光伏“四可”建设,筑牢电网安全新防线