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

时间:2020-01-10 04:57:22

标签: javascript geolocation

我有以下基本代码可通过Geolocation 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://中,所以这不起作用吗?

1 个答案:

答案 0 :(得分:0)

要使nomProgramme.c与Geolocation Api一起使用,请运行file:并使用ngrok URL托管HTML应用程序。无需PHP或Python之类的后端语言,您可以使用凭据生成本地隧道。

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

打开终端并运行:

https

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