Getting current location via MapView

117 views Asked by At
<View>
    <MapView
        mapPadding={{ top: 100, right: 0, bottom: 0, left: 0 }}
        showsUserLocation={true}
        showsMyLocationButton={true}
        onRegionChange={startAnimation}
        onRegionChangeComplete={(e) =>
            getFormattedAddress(e.latitude, e.longitude)
        }
        ref={mapRef}
        style={MapScreenStyles.map}
        initialRegion={region}
        onUserLocationChange={(event) => {
            const { coordinate } = event.nativeEvent;
            mapRef.current?.animateToRegion({
                latitude: coordinate.latitude,
                longitude: coordinate.longitude,
                latitudeDelta: 0.01,
                longitudeDelta: 0.01,
            });
        }}
    ></MapView>
    <Lottie
        source={require('../lf30_editor_scvkos7p')}
        style={{
            width: 80,
            height: 80,
        }}
    />
</View>

I am writing food-delivery-app using react-native. This is part of code related to my MapView component. When I visit this component I want to localize Lottie exactly where is blue dot (user's current location). I am using onUserLocationChange to get currentLocation to move Lottie. But Lottie continuing to follow blue dot. I want this behaviour only ones, when component mounts. Is there any way to stop onUserLocation or remove it?

I am new in react-native world and need some help.

1

There are 1 answers

0
oren On

Try to get the user's location when the user enters the app and save it. Then when you navigate to map screen you will use it as initial region so no need to use onUserLocationChange. Or you can get user's location inside useEffect using react-native-geolocation

...
const [initialRegion, setInitialRegion] = useState({
    latitude: 10,
    longitude: 10,
    latitudeDelta: 0.001,
    longitudeDelta: 0.001,
  });

  useEffect(() => {
    Geolocation.getCurrentPosition((pos) => {
      const crd = pos.coords;
      setInitialRegion({
        latitude: crd.latitude,
        longitude: crd.longitude,
        latitudeDelta: 0.0421,
        longitudeDelta: 0.0421,
      });
    }).catch((err) => {
      console.log(err);
    });
  }, []);

  return (
    <MapView
      style={styles.map}
      initialRegion={initialRegion}
      ...
    />
  );
...