【问题标题】:React Google Maps - get position of marker on DragEndReact Google Maps - 在 DragEnd 上获取标记的位置
【发布时间】:2022-02-23 00:39:29
【问题描述】:

我正在使用@react-google-maps/api 让我的谷歌地图做出反应。

  <GoogleMap
      onLoad={onMapLoad}
      options={{
        draggable: true,
        scrollwheel: false,
        keyboardShortcuts: false,
        mapTypeControl: false,
        fullscreenControl: false,
        zoomControl: true,
        streetViewControl: false,
      zoom={17}
      center={{
        //get user location
        lat: -3.745,
        lng: -38.523,
      }}
    ></GoogleMap>

我正在尝试使用以下方法拖动标记后获取标记的 lat/lng 值

const onMapLoad = map => {
  let marker = new google.maps.Marker({
  position: markerPosition,
  map: map,
  draggable: true,
})
marker.addListener('dragend', handleDragEnd)
}


const handleDragEnd = e => {
    console.log(e.latLng)
  }

标记正确加载到地图上,但是当我尝试拖动控制台日志时,只会为两个 lat/lng 值返回 null。有谁知道我做错了什么?

【问题讨论】:

    标签: reactjs google-maps draggable


    【解决方案1】:
    marker.addListener('dragend', function (e) {
      console.log(this.getPosition().toJSON()); // this === marker
    })
    

    https://jsfiddle.net/4s6xcy2o/1/

    注意:你对箭头函数的使用会改变this

    【讨论】:

    • 非常感谢,现在可以正常使用了
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2018-12-20
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多