h5定位geolaction无法调试解决方法
昨天接到一个在h5获取经纬度的需求,看了文档后,代码其实很简单,但在浏览器上调试就比较蛋疼了...
代码:
关于geolaction的介绍,我想这个文档会比我讲得更详细:
https://developer.mozilla.org/zh-CN/docs/Web/API/Geolocation/Using_geolocation
获取经纬度方式有两种:
1.navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options) 【适用于对经度要求不高的,可获得低精度,后两个参数可选】
2.navigator.geolocation.watchPosition(successCallback, errorCallback, options) 【适用于对经度有要求的,可获得高精度,后两个参数可选】
ps:watchPosition()会返回一个 ID,唯一地标记该位置监视器。可将该ID 传给clearWatch(ID)来停止监视用户位置。
本地无服务调试:
1.是否获取地理位置的提示框有时不出来.... 很尴尬;
2.出来了,点击允许就没然后了.... 也很尴尬
3.点击允许后,获得了想要的经纬度 ... 大概要看浏览器心情
公司测试环境看效果:
是否同意获取地理位置的弹框始终不出来..... 我一度以为是代码问题or环境问题【公司项目比较老】
后发现这个提示:
搜了下CanIus里各浏览器支持情况:
查看其CanIUse里的notice,会发现,geolocation越往后基本就只支持https请求的,点击测试环境里浏览器提示里的链接,里面提供了非安全环境(即http环境)测试方法:
https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
粘贴部分原文如下:
Testing Powerful Features
- Secure the server with a publicly-trusted certificate. If the server is reachable from the Internet, several public CAs offer free, automatically-renewed server certificates.
- http://localhost is treated as a secure origin, so if you're able to run your server from localhost, you should be able to test the feature on that server.
- You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that on Android and ChromeOS this requires having a device with root access/dev mode. (This flag is broken in Chrome 63 but fixed in Chrome 64 and later. Prior to Chrome 62, you must also include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.)
- Create a self-signed certificate for temporary testing. Direct use of such a certificate requires clicking through an invalid certificate interstitial, which is otherwise not recommended. Note that because of this interstitial click-through (which also prevents HTTPS-response caching), we recommend options (1) and (2) instead, but they are difficult to do on mobile. See this post on setting up a self-signed certificate for a server for more information on how to do this.
An alternative approach is to generate a self-signed root certificate which you place into the trust store of the developer PC/devices, and then issue one or more certificates for the test servers. Trusting the root certificate means that Chrome will treat the site as secure and load it without interstitials or impacting caching. One easy way of setting up and using a custom root certificate is to use the open source mkcert tool.
- Secure the server with a publicly-trusted certificate. If the server is reachable from the Internet, several public CAs offer free, automatically-renewed server certificates.
![](https://img2018.cnblogs.com/blog/1000531/201903/1000531-20190313211644424-837677212.jpg)