'Is there a way to get marker's on screen position in react-native-maps?

I need custom tooltip with semitransparent background which overlays the map.

So in common we draw first MapView. After marker press on top of MapView we draw overlay (backgroundColor: "#00000033"), on top of it draw tooltip and image over the marker position to simulate highlight. And now I need to get absolute position of marker on screen to draw my image over it. There is point prop in onPress nativeEvent regarding to docs but I haven't it in my real event and I don't know if that is what I need.

{
   "action": "marker-press",
   "coordinate": {
      "latitude": -15.3469687,
      "longitude": 37.100195
   },
   "id": "unknown",
   "target": 295
}

Is there a way to get marker's on screen position?



Solution 1:[1]

Yes, you can use the measureInWindow method on the ref of the custom component. If your custom component doesn't have this method available, you can wrap it in a View, and use the method on that.

Example:

const markerRef = useRef();
const [markerPosition, setMarkerPosition] = useState({});

const measureMarker = () => {
  markerRef.current?.measureInWindow((x, y, width, height) => {
    const { width: screenWidth, height: screenHeight } = Dimensions.get('screen');
    // if any non-zero, on-screen values, save measurements
    if (!(x || y || width || height)) return;
    if (x > screenWidth || y > screenHeight) return;
    setMarkerPosition({x, y, width, height});
  }
};

...

return (
  <View ref={markerRef} onLayout={measureMarker}>
    <CustomMarker
      ...
);

See the docs for measureInWindow for more. measure would also work for the purpose of getting the on-screen position.

Note that these callbacks won't work until native layout is completed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1