Search code examples
javascriptreact-nativegeolocation

react-native not updating MapView initialRegion with react-native-geolocation-service


I would like to update my map to show the user location. Using the code below, I get a world map not a map of the UK, which is what the latitude and longitude should show, can anyone help?

  const [location, setLocation] = useState({
    initialPosition: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0,
      longitudeDelta: 0,
    },
  });

  const getLocationPermissions = async () => {
    const granted = await request(
      Platform.select({
        android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
      }),
      {
        title: 'DemoApp',
        message: 'App would like access to your location ',
      }
    );

    return granted === RESULTS.GRANTED;
  };

  useEffect(() => {
    //  check permission
    const isGranted = getLocationPermissions();

    if (isGranted) {
   // get location 
      Geolocation.getCurrentPosition((info) => {
        let lat = info.coords.latitude;
        let long = info.coords.longitude;
   // update state with location,latitude: 52.62869394486038
   //longitude: -1.9794797216434805
        var initialRegion = {
          latitude: lat,
          longitude: long,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        };
      });
    } else {
      console.log('error');
    }
  }, []);

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

Solution

  • After retrieve user location from device, animate map to that region.

    import * as React from "react";
    import { Text, View, StyleSheet } from "react-native";
    import MapView from "react-native-maps";
    
    const App = () => {
      const mapRef = React.useRef(null);
    
      React.useEffect(() => {
        // Below are mocked location in UK. Retrieve real location
        // from device with Geoocation API
    
        // latitude: 52.62869394486038
        //longitude: -1.9794797216434805
        const userRegion = {
          latitude: 52.62869394486038,
          longitude: -1.9794797216434805,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        };
    
        mapRef.current?.animateToRegion(userRegion);
      }, []);
    
      return (
        <View style={styles.container}>
          <MapView
            ref={mapRef}
            initialRegion={{
              latitude: 37.78825,
              longitude: -122.4324,
              latitudeDelta: 0.0922,
              longitudeDelta: 0.0421,
            }}
            style={styles.mapStyle}
          />
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        paddingTop: 10,
        backgroundColor: "#ecf0f1",
      },
      mapStyle: {
        ...StyleSheet.absoluteFillObject,
      },
    });
    
    export default App;
    
    

    Working example snack.

    https://snack.expo.dev/@emmbyiringiro/9f04a3