Warm tip: This article is reproduced from serverfault.com, please click

javascript-获取一段已单击的折线

(javascript - Obtain a segment of Polyline which was clicked)

发布于 2020-11-30 22:37:26

在我的应用程序中,我有:

<MapContainer {...opts} scrollWheelZoom>
  <>..</>
  <Polyline eventHandlers={{ click: e => { console.log('line clicked', e.sourceTarget) }, }} positions={positonArrat}/>}
</MapContainer>

每条折线由N个直线部分组成。

在不使用火箭科学的情况下,如何获得被单击的折线段

另一种选择是用多条线替换一条多段线,以便每次单击都可以得到一个结果,但是开箱即用的解决方案将是不错的...

Questioner
injecteer
Viewed
0
injecteer 2020-12-01 23:48:50

我最终使用了简单的数学运算,onClick函数如下所示:

const TOLERANCE = 3

onPolylineClick = e => {
  const { x, y } = e.layerPoint
  const parts = e.target._parts[ 0 ] // some undocumented shit
  let prev = parts[ 0 ]
  const section = parts.slice( 1, parts.length ).findIndex( p => {
    try{
      // check if in bounds
      if( !( Math.min( prev.x, p.x ) <= x <= Math.max( prev.x, p.x ) && 
             Math.min( prev.y, p.y ) <= y <= Math.max( prev.y, p.y ) ) ) return false
      const yCalc = ( x - prev.x ) * ( p.y - prev.y ) / ( p.x - prev.x ) + prev.y
      return Math.abs( y - yCalc ) < TOLERANCE
    }finally{
      prev = p
    }
  })
  this.setState( { selectedSection:section } )
}

它在中设置匹配部分的第一个点的索引state

然后,为了可视化所选部分,我在顶部显示了一个2点的橙色折线:

<MapContainer {...opts} scrollWheelZoom>

  <Polyline eventHandlers={{ click:this.onPolylineClick }} positions={points} />}
  
  {-1 !== selectedSection && 
     <Polyline color="orange" positions={points.slice( selectedSection, selectedSection + 2 )}/>}

</MapContainer>