我一直在做这个:http://davidcool.com/feeds
它在除Safari以外的所有浏览器中都可以正常工作。有时Safari会在无限循环中请求地理位置许可,有时它会像它应该的那样只请求一次,大多数时候它会请求三次……所有其他浏览器都按计划请求一次。
代码如下:
function success(position) {
//output lat+long data
//console.log(position);
//var s = document.querySelector('#status');
//s.innerHTML = "Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude + "<br />";
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "success";
s.className = 'success';
//get timezone info
$.ajax({
url:'https://maps.googleapis.com/maps/api/timezone/json?location=' + position.coords.latitude + ',' + position.coords.longitude + '×tamp=' + Math.floor(position.timestamp/1000) + '&language=en&key=????',
dataType: "json",
async:false,
cache:false,
error:
function(res){
console.log(res);
},
success:
function(res){
//console.log(res);
time_zone_id = res.timeZoneId;
time_zone_name = res.timeZoneName;
//var t = document.querySelector('#status1');
//t.innerHTML = "Time Zone ID: " + res.timeZoneId + "<br />Time Zone Name: " + res.timeZoneName + "<br />" ;
}
});
//get address info
$.ajax({
url:'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&language=en&key=????',
dataType: "json",
async:false,
cache:false,
error:
function(res){
console.log(res);
},
success:
function(res){
//console.log(res);
city = res.results[2].address_components[1].long_name;
address = res.results[2].formatted_address;
//var t = document.querySelector('#status2');
//t.innerHTML = "Address: " + res.results[0].formatted_address ;
}
});
//get weather info
$('#weather').load("weather.php", {'latitude':position.coords.latitude, 'longitude':position.coords.longitude, 'local_time_zone_id':time_zone_id, 'local_time_zone_name':time_zone_name, 'city':city, 'address':address});
};
function error(msg) {
var s = document.querySelector('#weather');
//s.innerHTML = typeof msg == 'string' ? msg : "Failed to get location. Try refreshing.";
s.innerHTML = typeof msg == 'string' ? msg : "Failed to get location. Try refreshing.";
s.className = 'fail';
};
//get lat+long info
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
//setTimeout(navigator.geolocation.getCurrentPosition(success, error), 500);
} else {
error('not supported');
};
我看过其他人有同样的问题,但还没能找到一个明确的答案,为什么会发生这种情况。什么好主意吗?
有趣的是,在我的开发Mac上,它只要求一次,在另一个开发Mac上,它要求多次!!
我不是100%确定,但我有同样的问题。然后我在error
回调中删除了msg
参数,现在它似乎在Safari中工作了。
所以你的error
回调应该看起来像
function error() {
var s = document.querySelector('#weather');
s.innerHTML = "Failed to get location";
s.className = 'fail';
}
让我知道这是否有效!