我试图使用浏览器提供的地理位置。
这是我的代码
console.log("Before Geolocation");
if(navigator.geolocation) {
console.log("Geolocation Supported");
navigator.geolocation.getCurrentPosition(function(position) {
console.log("Within function");
geoloc = position.coords.latitude + "," + position.coords.longitude;
console.log(geoloc);
},
function(){
console.log("error");
},
{
timeout: 10000
}
);
}
else {
console.log("geolocation not supported");
}
if (geoloc != '') {
addition = geoloc;
}
else {
addition = "DEFAULT LOCATION";
}
console.log(addition);
我的问题是,当我运行代码时,chrome上的控制台输出显示:
Before Geolocation
Geolocation Supported
DEFAULT LOCATION
好像是电话:
navigator.geolocation.getCurrentPosition(function(position) {
似乎没有被执行,因为成功和失败功能都没有做某事。 (可以在控制台中查看)
该功能未触发但支持地理定位的原因是什么?
答案 0 :(得分:2)
调用该函数,但它是异步的。这就是你必须提供回调函数的原因。
var addition = "DEFAULT LOCATION";
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
if (navigator.geolocation) {
console.log('geolocation supported');
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
console.log("geolocation not supported");
console.log(addition);
}
function success(position) {
addition = position.coords.latitude + "," + position.coords.longitude;
console.log(addition);
// I worked! Party on...
}
function error(err) {
console.error(err.message);
}