【发布时间】:2016-07-29 15:15:53
【问题描述】:
我正在构建一个天气页面,我需要获取用户位置以获取天气数据。
if ((navigator.geolocation)&&(location!=null)) {
var locations = null;
window.navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
locations = latitude+'/'+longitude;
show_all_weather_components();
console.log("1");
});
}
/* If location is not found the set default location as USDC0001, which is default code for washington DC. */
var locations= !locations?"USDC0001":locations;
console.log("2");
我在控制台中首先获得 2。 IE。它总是设置默认地址而不是用户实际地址。我知道这听起来很荒谬,但有什么方法可以避免这里代码的“非阻塞”模式。 还是有其他方法可以获取用户位置。我也尝试了 ip database Api,但它没有精确地工作。
有一次我想在 if 条件部分下面放一个延迟,但是由于这个天气应用程序的不同模块,我的页面已经很慢了。任何想法将不胜感激。 谢谢
【问题讨论】:
-
locations 变量始终为空,因此如果条件失败
-
navigator.geolocation 不是 Jquery 的一部分,而是 HTML 5 的一部分。它还提示用户在页面加载时共享位置。在用户分享之前,您将无法获取用户的用户位置。
-
我明白了,即使我之前允许共享位置,这也需要时间,并且 console.log("2") 比 console.log("1) 更早执行。
-
好的,我将尝试取出 var location =null,然后检查
-
还是不行。结果相同
标签: javascript jquery geolocation weather