javascript - 支持地理定位但不起作用

标签 javascript html geolocation

我正在尝试使用浏览器提供的地理位置。

这是我的代码

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) {

似乎没有被执行,因为成功函数和失败函数都没有做任何事情。 (可以在控制台查看)

该函数未触发但支持地理定位的原因可能是什么?

最佳答案

该函数被调用,但它是异步的。这就是为什么您必须提供回调函数。

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);
}

关于javascript - 支持地理定位但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38906725/

相关文章:

javascript - 使用 wkhtmltopdf 在 PDF 中嵌入 JavaScript

html - 如何强制 Flash 崩溃以进行测试?

javascript - 使用 google geolocation api 查找塔的位置

geolocation - 关闭 Openlayers 3 地理定位

javascript - 从对象数组 : Javascript 中获取键

Javascript:如何使变量 "private"仅用于当前递归层?

javascript - go 函数内的await js 异步函数(promise)

javascript - 如何打印出我的个人对象构造函数中的所有人?

javascript - 在按钮之前添加带有 jQ​​uery 的表格行

ios - 如何更改 Ionic 2 iOS 应用程序的位置访问描述?我正在为我的应用程序使用 cordova 地理定位插件