webgis中捕捉功能的实现

2021-12-06 10:32:28 浏览数 (3)

概述

本文以openlayers为例,结合turf.js讲一下webgis中绘制和编辑时如何实现捕捉功能。

效果

为了验证捕捉的结果是否正确,就将绘制的几个面做了一个合并的测试,效果如下:

实现思路

  • 输入
    • 要捕捉的图层,此处为vectorSource
    • 捕捉的范围,单位是像素
    • 鼠标移动时的坐标
  • 输出
    • 满足条件的点

捕捉工具的舒适化参数如下:

实现的大致流程如下:

实现代码

代码语言:javascript复制
 /**
  * 获取捕捉点
  * @param {Array} coords - 传入坐标
  * @return {Array}
  */
 getSnapPoint (coords) {
   if (!this._active) return []
   let result = []
   let features = this._vectorSource.getFeatures()
   const res = this._map.getView().getResolution()
   const dis = this.getPixelTolerance() * res
   const point = turfPoint.point(toLonLat(coords))
   for (let i = 0; i < features.length; i  ) {
     const feature = features[i]
     const json = feature2Geojson(feature)
     const line = polygonToLine(json)
     const dist = pointToLineDistance(point, line)
     if (dist * 1000 < dis) {
       const pointLine = nearestPointOnLine(line, point, { units: 'kilometers' })
       result = pointLine.geometry.coordinates
       break
     }
   }
   this._overlay.setPosition(result.length === 0 ? null : result)
   return result
 }
// 处理map的事件,click,pointermove,dblclick
function clickEvent(e) {
  if(!isDraw) return
  const snapPoint = snap.getSnapPoint(e.coordinate)
  const coordinate = snapPoint.length > 0 ? ol.proj.fromLonLat(snapPoint) : e.coordinate ;
  ......
}
function pointerMoveEvent(e) {
  if(!isDraw) return
  const snapPoint = snap.getSnapPoint(e.coordinate)
  const coordinate = snapPoint.length > 0 ? ol.proj.fromLonLat(snapPoint) : e.coordinate ;
  ......
}
function dblclickEvent(e) {
  if(!isDraw) return
  let coords = coordinates.concat([]);
  const snapPoint = snap.getSnapPoint(e.coordinate)
  const coordinate = snapPoint.length > 0 ? ol.proj.fromLonLat(snapPoint) : e.coordinate ;
  ......
}

0 人点赞