我正在使用reactjs和带有darksky天气api的地理定位(导航) api构建一个天气应用程序。我正确地显示了经度和纬度,但是当我试图检索数据时,我得到了一个{code: 400,错误:“给定的位置(或时间)无效。”}。但是,如果我手动将地址放到浏览器中,就会得到正确的JSON。
示例URL请求:https://api.darksky.net/forecast/{api_secret_key}/37.4498,-77.3047
查看控制台中的标题,甚至没有显示请求的URL包含我要传入的经度和纬度。可能是在我得到纬度和经度之前正在执行天气API调用吗?
每个控制台请求URL:https://api.darksky.net/forecast/{api_secret_key}/,
getWeather = async (e) => { //Get weather data
let latitude = '';
let longitude = '';
e.preventDefault(); //prevent page reload behaviour
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
longitude = position.coords.longitude.toFixed(4);
console.log("Latitude: " + latitude + ", Longitude: " + longitude);
});
} else {
console.log("Geolocation not available");
}
//Pass the lattitude and longitude values from the location API call to the weather API
const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/${latitude},${longitude}`);
const weather_data = await weather_api_call.json(); //retrieve weather API data
console.log(weather_data); //print weather API data to console
}
答案:最终将获取和记录天气API数据移到getCurrentPosition函数中。
getWeather = (e) => {
e.preventDefault(); //prevent page reload behaviour
if ("geolocation" in navigator) { //if the users allows geolocation to be active
navigator.geolocation.getCurrentPosition(async (position) => { //access naviagotr API & get the users current lat and lon
let latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
let longitude = position.coords.longitude.toFixed(4);
console.log("Latitude: " + latitude + " Longitude: " + longitude); //check lat and lon
//Pass the lattitude and longitude values from the location API call to the weather API
const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/`+latitude+`,`+longitude); //run API call after when lat and lon data is gotten
const weather_data = await weather_api_call.json(); //retrieve weather API data after the call is executed with the lat and lon
console.log(weather_data); //print weather API data to console
});
} else {
console.log("Geolocation not available"); //Log if user blocks location in browser
}
}
发布于 2018-11-25 01:16:01
navigator.geolocation.getCurrentPosition
是一个异步调用,在这里您要在所提供的回调中设置纬度和经度的值。但是,getWeather
函数只是继续执行,并使用原始的纬度和经度值调用fetch,这些值被定义为空字符串。
如果您将获取调用移动到navigator.geolocation.getCurrentPosition
的回调中,那么您可以确保定义了纬度和经度。
https://stackoverflow.com/questions/53463787
复制相似问题