每次刷新我的应用程序时,地图都会更改初始位置 [react-native]

Every refresh on my app the map changes the initial position [react-native]

我正在研究 React,我正在使用它各自的库编写一些 Uber 功能,如地图、地理位置和方向。 我一直是关于 MapView 的问题,我想......每次当我的应用程序重新加载时,初始坐标都会设置到地图上的另一个位置并放大。 我看到另一个开发人员有同样的问题,尽管他们使用的是 Class 组件,但我不太清楚如何将显示的解决方案转换为功能组件。 谁能帮帮我?

这是我的代码:

const Map = () => {
  const [origin, setOrigin] = useState([0, 0]);
  const [destination, setDestination] = useState([0, 0]);

  const mapView = useRef(null);

  useEffect(() => {
    async function loadPosition() {
      await RNLocation.requestPermission({
        ios: 'whenInUse',
        android: {
          detail: 'coarse',
        },
      }).then(granted => {
        if (!granted) {
          Alert.alert('Não foi permitido o uso da localização');
        }
      });

      const currentOrigin = await RNLocation.getLatestLocation({
        timeout: 2000,
      });
      const {latitude, longitude} = currentOrigin;

      console.log([latitude, longitude]);
      setOrigin([latitude, longitude]);
    }

    loadPosition();
  }, []);

  const handleLocationSelected = useCallback((data, {geometry}) => {
    const {
      location: {lat: latitude, lng: longitude},
    } = geometry;

    const currentDestination = [latitude, longitude];
    setDestination(currentDestination, {
      title: data.structured_formatting.main_text,
    });
  }, []);

  return (
    <View style={{flex: 1}}>
      <MapView
        style={{flex: 1}}
        initialRegion={{
          latitude: origin[0],
          longitude: origin[1],
          latitudeDelta: 0.0143,
          longitudeDelta: 0.0134,
        }}
        showsUserLocation
        loadingEnabled
        ref={mapView}>
        {destination && (
          <Directions
            origin={{
              latitude: origin[0],
              longitude: origin[1],
            }}
            destination={{
              latitude: destination[0],
              longitude: destination[1],
            }}
            onReady={result =>
              mapView.current.fitToCoordinates(result.coordinates)
            }
          />
        )}
      </MapView>
      <Search onLocationSelected={handleLocationSelected} />
    </View>
  );
};

您需要在所有坐标都设置好后才能显示您的地图。发生这种情况是因为当您重新加载应用程序时,一些内容已经呈现,而您的请求仍在请求中。

试试下面的代码:

const Map = () => {
    const [isLoading, setIsLoading] = useState(false);
    const [origin, setOrigin] = useState([0, 0]);
    const [destination, setDestination] = useState([0, 0]);

    const mapView = useRef(null);

    async function loadPosition() {
        setIsLoading(true)

        await RNLocation.requestPermission({
            ios: 'whenInUse',
            android: {
                detail: 'coarse',
            },
        }).then(granted => {
            if (!granted) {
                Alert.alert('Não foi permitido o uso da localização');
            }
        });

        const currentOrigin = await RNLocation.getLatestLocation({
            timeout: 6000,
        });
        const { latitude, longitude } = currentOrigin;

        setOrigin([latitude, longitude]);

        setIsLoading(false)
    }

    const handleLocationSelected = useCallback((data, { geometry }) => {
        const {
            location: { lat: latitude, lng: longitude },
        } = geometry;

        const currentDestination = [latitude, longitude];
        setDestination(currentDestination, {
            title: data.structured_formatting.main_text,
        });
    }, []);


    useEffect(() => {
        loadPosition();
    }, []);

    return (
        <View style={{ flex: 1 }}>
            {isLoading ? (
                <Text> Loading the Map...</Text>
            ) : (
                    <>
                        <MapView
                            style={{ flex: 1 }}
                            initialRegion={{
                                latitude: origin[0],
                                longitude: origin[1],
                                latitudeDelta: 0.0143,
                                longitudeDelta: 0.0134,
                            }}
                            showsUserLocation
                            loadingEnabled
                            ref={mapView}>
                            {destination && (
                                <Directions
                                    origin={{
                                        latitude: origin[0],
                                        longitude: origin[1],
                                    }}
                                    destination={{
                                        latitude: destination[0],
                                        longitude: destination[1],
                                    }}
                                    onReady={result =>
                                      mapView.current.fitToCoordinates(result.coordinates)
                                    }
                                />
                            )}
                        </MapView>
                        <Search onLocationSelected={handleLocationSelected} />
                    </>
                )}
        </View>
    );
};