如何在react native expo中获取当前位置?

rryofs0p  于 2023-05-07  发布在  React
关注(0)|答案(1)|浏览(331)

我想在react native expo应用程序中获取当前天气。但是我需要我的当前位置来实现,所以我使用了Location.getCurrentPositionAsync({}),我得到了像“请求位置权限时出错”,“未授权使用位置服务”这样的错误

useEffect(() => {
        const fetchWeatherData = async (latitude, longitude) => {
          try {
            const response = await fetch(
              'https://api.openweathermap.org/data/2.5/weatherlat=${latitude}&lon=${longitude}&appid=3d9b9b12834e4fca69c88401aeb73c2e'
            );
            const json = await response.json();
            setWeatherData(json);
            console.log(weatherData.main.temp)
          } catch (error) {
            console.error('Error fetching weather data:', error);
          }
        };
        
        const getLocation = async () => {
            try {
              const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                  title: 'Location Permission',
                  message: 'WeatherApp needs access to your location for fetching weather data.',
                  buttonNeutral: 'Ask Me Later',
                  buttonNegative: 'Cancel',
                  buttonPositive: 'OK',
                }
              );
      
              if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                let location = await Location.getCurrentPositionAsync({});
                console.log(location)
                fetchWeatherData(location.coords.latitude, location.coords.longitude);

              } else {
                setLocationError('Location permission denied');
              }
            } catch (error) {
              console.error('Error requesting location permission:', error);
            }
          };
      
          getLocation();

    }, []);
6kkfgxo0

6kkfgxo01#

您只处理Android的权限请求,但如果您的目标是iOS平台,则上述实现不会处理iOS上的边缘情况。
建议使用expo-location在两个平台上同时处理权限和位置访问。
让我们重构代码如下:

import * as Location from "expo-location";

useEffect(() => {
  const fetchWeatherData = async (latitude, longitude) => {
    try {
      const response = await fetch(
        "https://api.openweathermap.org/data/2.5/weatherlat=${latitude}&lon=${longitude}&appid=3d9b9b12834e4fca69c88401aeb73c2e"
      );
      const json = await response.json();
      setWeatherData(json);
      console.log(weatherData.main.temp);
    } catch (error) {
      console.error("Error fetching weather data:", error);
    }
  };

  const getLocation = async () => {
    try {
      let { status } = await Location.requestForegroundPermissionsAsync();

      if (status !== "granted") {
        setLocationError("Location permission denied");
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      fetchWeatherData(location.coords.latitude, location.coords.longitude);
    } catch (error) {
      console.error("Error requesting location permission:", error);
    }
  };

  getLocation();
}, []);

相关问题