Google地图几何库:如何创建处于被拖动状态的标记

Google Maps Geometry Library: how do I create a marker that is in a state of being dragged

我的意图是在 dragstart 事件中将多段线(具有两个坐标)一分为二。

下面的代码发生了什么:

  1. 折线正在等待拖动开始
  2. 当用户开始拖动多段线时,两条新多段线和它们之间的标记会替换旧多段线
  3. 拖动在当前鼠标位置停止而不松开鼠标

实际意图:

在第 3 步中,继续拖动,但拖动的元素是新标记而不是删除的多段线。

如何将 "dragging" 从折线转移到标记?

const path = new google.maps.MVCArray([
  new google.maps.LatLng(0, 0),
  new google.maps.LatLng(10, 10),
])

const polyline = new google.maps.Polyline({
  map,
  path,
  draggable: true
})

let marker, newPolylineA, newPolylineB

const dragstartListener = polyline.addListener('dragstart', ({ latLng }) => {
  google.maps.event.removeListener(dragstartListener)
  polyline.setMap(null)

  marker = new google.maps.Marker({
    map,
    position: latLng,
    draggable: true,
  })

  newPolylineA = new google.maps.Polyline({
    map,
    path: [ path.getAt(0), latLng ],
  })

  newPolylineB = new google.maps.Polyline({
    map,
    path: [ latLng, path.getAt(1) ],
  })
})

我通过使用 strokeOpacity 隐藏原始折线并使用 drag 和 dragend 事件解决了这个问题。

这不是真正的拖动目标交换,但它至少模仿了结果。

const coordinateA = new google.maps.LatLng(0, 0)
const coordinateB = new google.maps.LatLng(10, 10)
const path = new google.maps.MVCArray([
  coordinateA,
  coordinateB,
])

const polyline = new google.maps.Polyline({
  map,
  path,
  draggable: true
})

let marker, newPolylineA, newPolylineB

const dragstartListener = polyline.addListener('dragstart', ({ latLng }) => {
  polyline.setOptions({
    strokeOpacity: 0
  })

  marker = new google.maps.Marker({
    map,
    position: latLng,
    draggable: true,
  })

  newPolylineA = new google.maps.Polyline({
    map,
    path: [ path.getAt(0), latLng ],
  })

  newPolylineB = new google.maps.Polyline({
    map,
    path: [ latLng, path.getAt(1) ],
  })

  google.maps.event.removeListener(dragstartListener)
})

const dragListener = polyline.addListener('drag', ({ latLng }) => {
  marker.setPosition(latLng)  
  newPolylineA.setPath([ coordinateA, latLng ])
  newPolylineB.setPath([ latLng, coordinateB ])
})

const dragendListener = polyline.addListener('dragend', ({ latLng }) => {
  google.maps.event.removeListener(dragendListener)
  google.maps.event.removeListener(dragListener)

  marker.setPosition(latLng)  
  newPolylineA.setPath([ coordinateA, latLng ])
  newPolylineB.setPath([ latLng, coordinateB ])

  polyline.setMap(null)
})