我想在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();
}, []);
1条答案
按热度按时间6kkfgxo01#
您只处理Android的权限请求,但如果您的目标是iOS平台,则上述实现不会处理iOS上的边缘情况。
建议使用
expo-location
在两个平台上同时处理权限和位置访问。让我们重构代码如下: