我的网站上的 idevice 上的地理定位出现问题。
实际上我只需要获取纬度/经度坐标。 在 PC、Android 设备上一切都很酷,在 iPhone 上也很好,但前提是我使用 wifi 连接。但是,当我使用旧 iPhone 5s 使用 3G 或 LTE 时,我什么也得不到(但从 iPhone 6 开始就可以了)。
我了解到,如果 wifi 关闭,Safari 将不支持地理定位。 但我仍然需要让它在 iPhone 4,5 等 iDevices 上运行。 我正在使用这段示例代码:
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
最佳答案
我是 iPhone 5S 用户,尝试了 3G 地理定位,效果非常好。我试过这个CodePen通过 Wifi 和 3G 没有任何问题。
$(document).ready(function(){
setInterval(function(){
getLocation(function(position) {
//do something cool with position
currentLat = position.coords.latitude;
currentLng = position.coords.longitude;
$("#status").html(currentLat + " " + currentLng);
});
}, 1000);
});
var GPSTimeout = 10; //init global var NOTE: I noticed that 10 gives me the quickest result but play around with this number to your own liking
//function to be called where you want the location with the callback(position)
function getLocation(callback) {
if (navigator.geolocation) {
var clickedTime = (new Date()).getTime(); //get the current time
GPSTimeout = 10; //reset the timeout just in case you call it more then once
ensurePosition(callback, clickedTime); //call recursive function to get position
}
return true;
}
//recursive position function
function ensurePosition(callback, timestamp) {
if (GPSTimeout < 6000) {
//call the geolocation function
navigator.geolocation.getCurrentPosition(
function(position) //on success
{
//if the timestamp that is returned minus the time that was set when called is greater then 0 the position is up to date
if (position.timestamp - timestamp >= 0) {
GPSTimeout = 10; //reset timeout just in case
callback(position); //call the callback function you created
} else //the gps that was returned is not current and needs to be refreshed
{
GPSTimeout += GPSTimeout; //increase the timeout by itself n*2
ensurePosition(callback, timestamp); //call itself to refresh
}
},
function() //error: gps failed so we will try again
{
GPSTimeout += GPSTimeout; //increase the timeout by itself n*2
ensurePosition(callback, timestamp); //call itself to try again
}, {
maximumAge: 0,
timeout: GPSTimeout
}
)
}
}
感谢 Chris Beckett 提供示例。
如果您还无法使其正常工作,也许您可以提供更多详细信息?
Ps:只需编辑以确保每个需要地理定位的人都检查是否启用了 Safari 的定位服务:
- 首先检查是否已在“设置”>“隐私”>“位置服务”下启用“位置服务”
- 接下来检查是否为 Safari 网站启用了该功能
关于javascript - 移动设备的地理定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34435922/