React Native地图在重新启动应用程序时渲染当前位置时出现问题。

huangapple go评论72阅读模式
英文:

React Native Maps Rendering current location breaks when I restart App

问题

目前,我的应用程序会请求用户的位置权限,如果用户接受权限请求,然后获取他们的位置信息。但是,目前的问题是,当我在地图上渲染一个固定的区域时,一切正常,但当我将代码更改为获取用户的实际位置后,如果重新启动应用程序或者重新运行Expo,应用程序会崩溃,因为状态变量未定义。我应该如何解决这个问题?以下是代码:

const Map = () => {

  // 获取用户位置权限
  const [location, setLocation] = useState();
  
  useEffect(() => {
    const getPermissions = async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        console.log("请授予位置权限");
        return;
      }

      let currentLocation = await Location.getCurrentPositionAsync({});
      setLocation(currentLocation.coords);

      console.log("位置信息:");
      console.log(currentLocation);
    };
    
    getPermissions();

  }, []);

  return (
    // 将此 Mapview 更改为用户的当前位置
    // 将显示距离用户设置的位置约0到30英里不等。
    <MapView 
      initialRegion={{
        // 当我使用纬度和经度作为 latitude: latitude: location.coords.latitude longitude: location.coords.longitude 重新启动应用程序时,应用程序会崩溃,因为状态被清除。
        latitude: 24.8607,
        longitude: 67.0011,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
      }}
      style={styles.map}
    />
  );
}

我希望应用程序可以在重新启动后继续保持用户的位置信息。

英文:

currently with my app I have it so that it asks the user for location perms and if they accept it then fetches their location. Currently however when I render the map with a set region it works and when the change the code to their location that the code fetches it changes to their location. When i reset the app or Expo the app crashes because the state is undefined. How can I get passed this? Here is the code:

const Map = () =&gt; {

  // Get permissons for using user location
  const [location, setLocation] = useState();
  
  useEffect(() =&gt; {
    const getPermissions = async () =&gt; {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== &#39;granted&#39;) {
        console.log(&quot;Please grant location permissions&quot;);
        return;
      }

      let currentLocation = await Location.getCurrentPositionAsync({});
      setLocation(currentLocation.coords);

      console.log(&quot;Location:&quot;);
      console.log(currentLocation);
    };
    
    getPermissions();

  }, []);

    return(
//Will change this Mapview to users current location
//Will display about 0 - 30 miles away from used depending on user settings.
    &lt;MapView 
    initialRegion={
      { 
          //I when I restart the app with latitude and longitude as latitude: latitude: location.coords.latitude longitude: location.coords.longitude app crashes cause the state is cleared. 
          latitude: 24.8607,
          longitude: 67.0011,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
     style ={styles.map}/&gt;
  );
}

I want the app to constantly be set to the users location even if the app is restarted

答案1

得分: 1

由于您没有为您的“位置状态”定义初始值,它将以“null”值初始化。因此,“location.coords”是“undefined”。

要解决此问题,当将纬度和经度属性传递给“MapView”组件时,您可以检查位置是否不为null或undefined,并将其值传递给“MapView”组件。

如果更改“initialRegion”属性,地图不会重新呈现,因为它用于初始渲染。要在位置状态更新后更新地图位置,您可以使用“region”属性。当其值更改时,它将在MapView中引发渲染。新的区域将显示出来。

可以通过以下方式重写属性来实现这一点:

<MapView 
    initialRegion={{ 
          latitude: !!location ? location.coords.latitude : 24.8607,
          longitude: !!location ? location.coords.longitude : 67.0011,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
     region={{ 
          latitude: !!location ? location.coords.latitude : 24.8607,
          longitude: !!location ? location.coords.longitude : 67.0011,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
     style ={styles.map}
/>

这样,一旦获取了权限并使用新值更新了状态,就会将新的props传递给“MapView”并进行渲染。

您应该使用“initialRegion”来显示“位置”更新之前的默认区域。之后,“region”属性可以更新视图。

英文:

Since you haven't defined an initial value for your location state, it is initialized with a null value. Thus location.coords is undefined.

To fix the issue, when passing the latitude and longitude props to the MapView component, you can check if location isn't null or undefined, and pass its values to the MapView component.

The Map won't re-render if you change the initialRegion prop since it is used for initial rendering. To update the Map location after the location state is updated, you can use the region prop. It will cause a render in MapView when its value is changed. And the new region will be shown.

This can be approached by rewriting the props as below:

&lt;MapView 
    initialRegion={{ 
          latitude: !!location ? location.coords.latitude : 24.8607,
          longitude: !!location ? location.coords.longitude : 67.0011,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
     region={{ 
          latitude: !!location ? location.coords.latitude : 24.8607,
          longitude: !!location ? location.coords.longitude : 67.0011,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        }}
     style ={styles.map}
/&gt;

This way, once the permission is acquired and the state is updated with new values, the MapView will receive the new props and renders.

You should use initialRegion for showing a default region before the location is updated. After that, the region prop can update the view.

huangapple
  • 本文由 发表于 2023年5月30日 10:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定