用户允许访问后如何使用浏览器地理位置
Posted
技术标签:
【中文标题】用户允许访问后如何使用浏览器地理位置【英文标题】:How to use browser GeoLocation after user allows access 【发布时间】:2016-05-10 13:12:09 【问题描述】:我遇到了基于地理位置返回 JSON 的天气 API 调用问题。浏览器询问允许/拒绝访问位置的问题,然后我希望 API 调用发生,最好是在页面加载时。我已经将呼叫放在按钮单击之后,但它仍然没有使用当地天气更新页面。但是,如果我使用调试器单步执行代码,它可以正常工作。
$(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
【问题讨论】:
如果在getCurrentPostion中提供超时选项,像这样navigator.geolocation.getCurrentPosition(function(position) /*success*/, function()/*fail*/, 超时:5000); 【参考方案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);
【讨论】:
我最终使用 IP 地址进行定位,但我确信这段代码会起作用。谢谢。以上是关于用户允许访问后如何使用浏览器地理位置的主要内容,如果未能解决你的问题,请参考以下文章