我想在 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();
}, []);