如何使 Geolocation API 函数在 localhost file:// 上运行?

How can I make Geolocation API function working on localhost file://?

我有这个基本代码来使用地理定位检索纬度和经度 API :

showmap.html

<button  onclick="getLocation()">Find me </button>

<script type="text/javascript" src="js/geolocation.js"></script>

js/geolocation.js

function getLocation() {

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    alert("Geolocation is not supported by your browser. Please update your browser. Visit Help Center.");
  }
}

function showPosition(position) {
  var latitude = position.coords.latitude;
  var longitude =  position.coords.longitude;

  console.log("Latitude : " + latitude + "<br> Longitude :" + longitude);
}

当我点击按钮时,我在控制台收到这个错误

SyntaxError: An invalid or illegal string was specified showmap.html:72
    _sendMessage file:///home/user/Desktop/Projects/showmap.html:72
    call file:///home/user/Desktop/Projects/showmap.html:64
    getCurrentPosition file:///home/user/Desktop/Projects/showmap.html:16
    getLocation file:///home/user/Desktop/Projects/js/geolocation.js:4
    onclick file:///home/user/Desktop/Projects/showmap.html:1
    fireMouseEvent resource://devtools/server/actors/emulation/touch-simulator.js:290
    dispatchMouseEvents resource://devtools/server/actors/emulation/touch-simulator.js:264

我正在想办法解决这个问题。这不起作用是因为我在 file:// 吗?

要让 file: 使用地理定位 Api、运行 ngrok 并使用 https url 来托管您的 HTML 应用程序。无需 PHP 或 Python 之类的后端语言,您可以使用您的凭据生成本地隧道。

这假设您已经安装了 ngrok 并且您 运行正在 Ubuntu。

打开终端并运行 :

ngrok http -auth="user:password" file:///path/to/your/HTML/project

参考: 使用 ngrok 的内置文件服务器提供本地目录 https://ngrok.com/docs