react-google-maps-api icon indicating copy to clipboard operation
react-google-maps-api copied to clipboard

Question: OverlayView Draggable

Open sharukhkhanajm opened this issue 2 years ago • 2 comments

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.

sharukhkhanajm avatar Oct 27 '21 05:10 sharukhkhanajm

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.

dodyvirgiawan avatar Aug 02 '22 09:08 dodyvirgiawan

this is so useful that should be made into feature.

sooonism avatar Aug 20 '22 08:08 sooonism