我在使用天气API调用时遇到问题,该调用会根据geoLocation返回JSON。浏览器询问允许/拒绝访问位置的问题然后我希望API调用发生,最好是在页面加载时。我已将呼叫置于按钮后面,但它仍然不会使用本地天气更新页面。但是,如果我使用调试器逐步执行代码,它可以正常工作。
Javascript:
$(document).ready(function () {
var curLatitude = 'x';
var curLongditude = 'y';
var weatherApi = 'http://api.openweathermap.org/data/2.5/weather?q=London,GB&APPID=[insert-registered-api-key]';
// check for Geolocation support
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
curLatitude = position.coords.latitude;
curLongditude = position.coords.longitude;
if (curLatitude !== 'x' && curLongditude !== 'y') {
weatherApi = 'http://api.openweathermap.org/data/2.5/weather?lat=' + curLatitude +
'&lon=' + curLongditude + '&APPID=[insert-registered-api-key]';
};
loadWeather(weatherApi);
}, function() {
console.log('FAILED');
} );
} else {
console.log('No geoLoc');
// no geo location support - just load London weather
loadWeather(weatherApi);
};
$('#btnLocal').click(function () {
$(".message").html('clicked');
loadWeather(weatherApi);
});
function loadWeather(weatherApiUri) {
var current = "";
var ok;
var ret = $.getJSON(weatherApiUri, function(jsonres) {
console.log( "JSON Data: loaded" );
current = 'called api';
console.log(current);
$(".message").html(current);
}).done(function() {
console.log( "done" );
}).fail(function() {
console.log( "error" );
}).always(function() {
console.log( "complete" );
});
var weatherReturned = {id:0 , main:"weather", description:"weather detail", icon:"code" };
weatherReturned = ret.responseJSON.weather;
$(".message").html(ret.responseJSON.name + ', ' + weatherReturned[0].description);
};
});
JSON回复:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":500,"main":"Rain","description":"light rain","icon"
:"10d"}],"base":"cmc stations","main":{"temp":290.673,"pressure":1009.48,"humidity":83,"temp_min":290
.673,"temp_max":290.673,"sea_level":1019.21,"grnd_level":1009.48},"wind":{"speed":4.3,"deg":93.0027}
,"rain":{"3h":0.1375},"clouds":{"all":92},"dt":1462884891,"sys":{"message":0.0043,"country":"GB","sunrise"
:1462853704,"sunset":1462909185},"id":2643743,"name":"London","cod":200}
答案 0 :(得分:1)
您可以做的是设置一个带调用setInterval函数的计时器。
在计时器功能中,您可以在 navigator.geolocation 检查通过后检查您将设置的标记。
只有在区间函数中,你才能输出逻辑。
不要忘记清除计时器以避免不必要的电话。
代码可以是这样的:
var timer = setInterval(function(){
if(geoReady){
// clear interval
window.clearInterval(timer);
// do your logic
}, 300
}
if (navigator.geolocation) {
geoReady = true;
}
else {
// clear interval
window.clearInterval(timer);
}