You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用google-maps-react拖拽Marker时无法获取坐标的问题求助

Solution for Getting Dragged Marker Coordinates in google-maps-react

Hey there! I’ve dealt with this exact frustration before—google-maps-react’s docs don’t always highlight all the hidden props you can use with the Marker component, but luckily there’s a straightforward fix.

Even though the module’s docs only list mapCenter, onClick, and onMouseover upfront, the Marker component actually inherits all the event handlers from the native Google Maps JavaScript API Marker. That means you can use the onDragEnd event to capture the marker’s new position once dragging stops.

Here’s how to implement it:

Step 1: Add a drag handler function to your component

First, define a method in your React component to handle the drag end event. This function will receive three arguments: the marker’s props, the marker instance, and the event object (which contains the new coordinates):

handleMarkerDragEnd = (markerProps, marker, event) => {
  // Extract the new latitude and longitude from the event
  const draggedPosition = {
    lat: event.latLng.lat(),
    lng: event.latLng.lng()
  };

  // Update your component state with the new position
  this.setState({
    initialRegion: draggedPosition
  });

  // Do whatever else you need with the coordinates—log them, send to an API, etc.
  console.log("Marker dragged to:", draggedPosition);
};

Step 2: Attach the handler to your Marker component

Update your Marker JSX to include the onDragEnd prop pointing to your handler function:

<Map
  // Your existing Map props here (like google, zoom, etc.)
>
  <Marker
    draggable={true}
    position={this.state.initialRegion}
    onDragEnd={this.handleMarkerDragEnd} // Add this line!
  />
</Map>

Bonus: Real-time drag updates

If you need to track the marker’s position while it’s being dragged (not just when it stops), you can use the onDrag event instead. It works the same way—just swap onDragEnd with onDrag in both the handler function name and Marker prop.

This should let you capture the marker’s coordinates perfectly after dragging. Let me know if you hit any other issues with it!

内容的提问来源于stack exchange,提问作者Rafae Khatri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:27:54