react-google-maps-api
react-google-maps-api copied to clipboard
Question: OverlayView Draggable
Hi i am using OverlayView in order to create custom marker. i would like to know that can we make OverlayView draggable and get the lat and lng to update the OverlayView position just like normal marker? Thanks.
I was able to achieve this by controlling the OverlayView positon via react state. (although I think it is a dirty solution, but it does suffice my use case for now)
const [markerPos, setMarkerPos] = useState()
const [isDragging, setIsDragging] = useState(false)
<GoogleMap
{....}
options={{ draggable: !isDragging }}
onMouseMove={(e) => {
if (isDragging) {
const { latLng } = e;
setMarkerPos({ lat: latLng?.lat() || 0, lng: latLng?.lng() || 0 });
}
}}
>
<OverlayView
mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
position={markerPos}
>
<div
onMouseDown={() => setIsDragging(true)}
onMouseUp={() => setIsDragging(false)}
/>
</OverlayView>
</GoogleMap>
So basically I add an event handler to the child element of OverlayView to control the state.
When user clicks, the map becomes undraggable, and will update the OverlayView position based on the current latitude and longitude of the mouse position via onMouseMove.
And when user stop clicking, maps become draggable again and the marker position stays.
this is so useful that should be made into feature.