我有一个很简单的JS使用navigator。geolocation。getcurrentposition jammy。
$(document).ready(function(){
$("#business-locate, #people-locate").click(function() {
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
});
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
function foundLocation(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var userLocation = lat + ', ' + lon;
$("#business-current-location, #people-current-location").remove();
$("#Near-Me")
.watermark("Current Location")
.after("<input type='hidden' name='business-current-location' id='business-current-location' value='"+userLocation+"' />");
$("#people-Near-Me")
.watermark("Current Location")
.after("<input type='hidden' name='people-current-location' id='people-current-location' value='"+userLocation+"' />");
}
function noLocation() {
$("#Near-Me").watermark("Could not find location");
$("#people-Near-Me").watermark("Could not find location");
}
})//end DocReady
基本上,这里发生的事情是我们得到当前位置,如果它得到了,两个“水印”被放置在两个字段中,表示“当前位置”,两个隐藏字段被创建,并使用latong数据作为它们的值(它们在开始时被删除,这样它们就不会每次都重复)。还有两个按钮,它们有一个点击功能,做同样的事情。
不幸的是,每隔三次左右,它就会奏效。
这里有什么问题?
截至2020年年中,这里的答案都没有提供任何解释,只是黑客攻击或猜测。
正如@Coderer在我之前指出的,安全上下文(https)是今天需要的,所以在越来越多的设备上,地理定位在普通http下根本不起作用:
安全上下文
此特性仅在安全上下文中(HTTPS)以及部分或所有支持的浏览器中可用。
getCurrentPosition()(和watchPosition()更适合这里)的第三个参数是PositionOptions对象,由以下属性组成:
enableHighAccurancy (default false): if set to true, response is slower and more accurate. If you got timeout errors, keep this to false. If the accurancy is low, set it to true. In my tests the accurancy varies and on some devices it has no effect. On other devices setting true may cause surprisingly quick battery depletion.
timeout (default infinity): milliseconds before the API gives up and calls the error handler (the second parameter). Today most mobile devices with geolocation enabled and permission granted for the browser/page get the value with reasonable accurancy within a second. When the geolocation service is not available, alternative method like geo IP may be used, the delay can be many seconds and the precision usually ranges from questionable to useless.
maximumAge (default 0): milliseconds when cached value is valid, the device may decide to use valid cached data instead of sensor measure. I usually set this to non-zero values with slowly moving devices (like walking with mobile phone). On static devices, Infinity can be set to avoid consequent reading errors.
正如@YoLoCo在我之前指出的那样,getCurrentPosition()和watchPosition()会干扰,我在2020年确认了他的结果。通常,使用watchPosition代替getCurrentPosition周期性调用。
以下是我的解决方案,感谢一个闭包:
function geoloc(success, fail){
var is_echo = false;
if(navigator && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(pos) {
if (is_echo){ return; }
is_echo = true;
success(pos.coords.latitude,pos.coords.longitude);
},
function() {
if (is_echo){ return; }
is_echo = true;
fail();
}
);
} else {
fail();
}
}
function success(lat, lng){
alert(lat + " , " + lng);
}
function fail(){
alert("failed");
}
geoloc(success, fail);
你不会得到一个错误消息,因为默认情况下它没有超时(至少我认为)。我用firefox也遇到过同样的问题,只是对我来说,firefox总是超时。您可以像这样自己设置一个超时。
我的功能在chrome中工作得很好,但我每次在firefox中都会超时。
navigator.geolocation.getCurrentPosition(
function(position) {
//do succes handling
},
function errorCallback(error) {
//do error handling
},
{
timeout:5000
}
);
我建议你仔细观察你的错误。一切都被期待。为每件事都准备一个备份计划。我使用一些默认值或值从我的数据库自己的情况下谷歌地理位置和导航地理位置失败。
我也遇到了同样的情况。我尝试了超时解决方案,但不可靠。我发现如果你只调用它两次,位置就会正确刷新
function getLocation(callback)
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
navigator.geolocation.getCurrentPosition(callback, function(){},{maximumAge:0, timeout:10000});
},function(){}, {maximumAge:0, timeout:10000});
}
return true;
}
这当然是有点慢,但我没有给我错误的位置一次。我有它击中超时几次,没有返回任何东西,但除此之外,它工作得很好。我知道这仍然有点老套,我期待有人找到真正的解决方案。
或者,如果你想确保它会一直尝试,直到你想放弃,你可以试试这样的方法。
//example
$(document).ready(function(){
getLocation(function(position){
//do something cool with position
console.log(position);
});
});
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)//set at what point you want to just give up
{
//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}
)
}
}
我可能在这里有一些打字和拼写错误,但我希望你能明白。如果有人有问题或者找到更好的建议,请告诉我。
@brennanyoung的回答很好,但如果你想知道在失败的情况下该怎么做,你可以使用IP地理定位API,如https://ipinfo.io(这是我的服务)。这里有一个例子:
function do_something(coords) {
// Do something with the coords here
// eg. show the user on a map, or customize
// the site contents somehow
}
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords);
},
function(failure) {
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
});
};
});
详情见https://ipinfo.io/developers/replacing-getcurrentposition。