获取我当前位置的自定义弹出窗口

时间:2017-01-12 11:52:31

标签: javascript jquery geolocation location geo

我当前的网站完全取决于当前位置。现在我正在使用地理位置获取当前位置。但在目前情况下,用户对共享位置感到困惑。所以我想创建一个自定义弹出窗口(bootstrap)来获取客户端PC的当前位置。

我目前的代码如下:

function getLocation() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, error, {enableHighAccuracy:true,timeout:60000,maximumAge:0});
    }
    else {
        console.log("Geolocation is not supported by this browser.");
    }
}

function error(error) {
    console.log(error);
}

function showPosition(position) {

    var latitude = position.coords.latitude,
    longitude = position.coords.longitude;

    console.log(latitude);
    console.log(longitude);
}

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:3)

现在有办法浏览浏览器的地理位置权限弹出窗口。在Chrome上,它看起来像这样:

Chrome geolocation example

用户需要先单击“允许”才能读取其位置(这是一项安全功能)。 但是,如果您绝对需要它,您可以检测权限是否被拒绝,并向用户解释如何授予权限以及权限的重要性。

点击this answer查看类似问题,this example查看"权限被拒绝"错误:



function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, positionError);
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}

function showPosition(position) {
  // Success, can use position.
  console.log("Your position is: " + position);
}

function positionError(error) {
  if (error.PERMISSION_DENIED) {
    console.log("Error: permission denied");
    // Your custom modal here.
    showError('Geolocation is not enabled. Please enable to use this feature.');
  } else {
    // Handle other kinds of errors.
    console.log("Other kind of error: " + error);
  }
}

function showError(message) {
  // TODO
}

getLocation();