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之路】 已经接入了智能助手,欢迎关注,欢迎提问。
欢迎访问我的博客网站-长谈GIS:
http://shanhaitalk.com
都看到这了,不要忘记点赞、收藏 + 关注 哦 !
本号不定时更新有关 GIS开发 相关内容,欢迎关注 !