我正在构建一个天气页面,我需要获取用户位置才能获取天气数据。
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数据库Api,但是它不能精确工作。
曾经我曾考虑过将延迟放在if条件部分的下面,但是由于该天气应用程序的模块不同,我的页面已经非常慢。任何想法将不胜感激。谢谢
您必须使用getCurrentPosition的其他参数。这是一个例子:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="result"></div>
<script>
var result = document.getElementById('result');
if (navigator.geolocation && location != null) {
window.navigator.geolocation.getCurrentPosition(function(position){
result.text = position.coords.latitude + '/' + position.coords.longitude;
}, function(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
result.innerHTML = "Denied request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
result.innerHTML = "Location unavailable."
break;
case error.TIMEOUT:
result.innerHTML = "Location request timed out."
break;
case error.UNKNOWN_ERROR:
result.innerHTML = "An unknown error occurred."
break;
}
}, { timeout: 1000, maximumAge: 1000 });
}
</script>
</body>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句