Search code examples
javascriptreact-nativereact-native-maps

In react-native, using react-native-maps, how do I end marker drag programmatically?


My app displays a map with a polygon boundary and a marker in the middle of it. The marker is draggable. When the app detects that the marker has been dragged to one of the boundaries, I want to stop the drag programmatically. It seems like this should be simple, but I haven't been able to figure out how to do it. For example, I should be able to call something like onDragEnd(event) or dragEnd(event).


Solution

  • First, I made a state variable for the marker location when it is outside the boundary:

      const [outside, setOutside] = useState(false);
    

    Then, in the onDragStart event, I set the outside state to false. In the onDrag event, the code is:

        onDrag={(event) => {
          if (outOfBounds(event) === true) {
            event.stopPropagation();
            setOutside(true);                
          }
          else {
            setOutside(false);
          }
        }}
    

    This keeps the coordinates from changing as the marker is dragged outside the boundary, but it does not hide the marker. To hide the marker, there is a conditional style on the View that defines the marker. It is:

        <View style={[styles.outerMarker, {opacity: outside ? 0 : 1}]}>
    

    So when the outside state is true, the opacity is 0, hiding the marker.