没有 SSL 连接的地理定位

新手上路,请多包涵

我正在开发一个使用地理位置坐标的应用程序。我使用 HTML5 地理定位功能找出网站访问者的位置,但问题出在 Chrome 上,它不支持不安全来源的 GeoLocation。

   function showPosition(){
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function(position){
            var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
            document.getElementById("result").innerHTML = positionInfo;
        });
    } else{
        alert("Sorry, your browser does not support HTML5 geolocation.");
    }
}

这是代码 getCurrentPosition 无法正常工作,因为我的站点未连接 SSL。

Chrome 警告: getCurrentPosition() 和 watchPosition() 不再适用于不安全的来源。要使用此功能,您应该考虑将您的应用程序切换到安全来源,例如 HTTPS。

还有其他方法可以在 chrome 上获取坐标/LatLong 值吗? [仅限不安全连接]

编辑:它在我的机器上使用 localhost:80 工作,但在 http 上的测试 url 中不工作

原文由 Niranth Reddy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 574
2 个回答
var apiGeolocationSuccess = function(position) {
    alert("API geolocation success!\n\nlat = " + position.coords.latitude + "\nlng = " + position.coords.longitude);
};

var tryAPIGeolocation = function() {
    jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDCa1LUe1vOczX1hO_iGYgyo8p_jYuGOPU", function(success) {
        apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
  })
  .fail(function(err) {
    alert("API Geolocation error! \n\n"+err);
  });
};

var browserGeolocationSuccess = function(position) {
    alert("Browser geolocation success!\n\nlat = " + position.coords.latitude + "\nlng = " + position.coords.longitude);
};

var browserGeolocationFail = function(error) {
  switch (error.code) {
    case error.TIMEOUT:
      alert("Browser geolocation error !\n\nTimeout.");
      break;
    case error.PERMISSION_DENIED:
      if(error.message.indexOf("Only secure origins are allowed") == 0) {
        tryAPIGeolocation();
      }
      break;
    case error.POSITION_UNAVAILABLE:
      alert("Browser geolocation error !\n\nPosition unavailable.");
      break;
  }
};

var tryGeolocation = function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        browserGeolocationSuccess,
      browserGeolocationFail,
      {maximumAge: 50000, timeout: 20000, enableHighAccuracy: true});
  }
};

tryGeolocation();

原文由 Mannan Bahelim 发布,翻译遵循 CC BY-SA 3.0 许可协议

非常简单:打开 Chrome,打开此地址并输入您希望为其启用的域

chrome://flags/#unsafely-treat-insecure-origin-as-secure

在此处输入图像描述

这样它是永久的,你不需要每次都打开 chrome 浏览器

google-chrome --args --unsafely-treat-insecure-origin-as-secure="http://whatever.test"

正如上面的回答。

原文由 Aryeh Beitz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏