H5 API定位

总结:定位非常不准,并且成功率很低。

高德定位

需要在https域名下调用,本地调用偶尔能成功

/*** 高德精确定位* @param {*} config* https://lbs.amap.com/api/javascript-api/reference/location#m_AMap.Geolocation*/
export function locationGaodeExact(config = {}) {return new Promise((res, rej) => {AMap.plugin('AMap.Geolocation', function() {var geolocation = new AMap.Geolocation({enableHighAccuracy: true, //是否使用高精度定位,默认:truetimeout: 1000, //超过10秒后停止定位,默认:5sbuttonPosition: 'RB', //定位按钮的停靠位置buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点...config});geolocation.getCurrentPosition(function(status, result) {if (status == 'complete') {onComplete(result);} else {onError(result);}});});//解析定位结果function onComplete(data) {const {position: { lng, lat },formattedAddress,addressComponent: { province, city, district, adcode }} = data;const result = {longitude: lng,latitude: lat,province,city,district,address: formattedAddress,adcode // 区县code};console.log('location success', result);res(result);}//解析定位错误信息function onError(error) {console.log('location error', error);return rej(error);}// res({//   longitude: '120.023763,',//   latitude: '30.289903',//   city: '杭州市',//   district: '拱墅区',//   adcode: '330105'// })});
}

在PC端和IOS端经常定位失败,安卓定位还可以。

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>高德定位 和 H5定位</title><style>* {margin: 0;padding: 0;}#container {width: 100%;height: 500px;}</style>
</head><body><div id="container"></div><script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=2da0409b47ac022fb666ccaa88b4c75b"></script><script>// h5获取 (no)// window.navigator.geolocation.getCurrentPosition((e) => { alert('H5-success');alert(JSON.stringify(e)) }, (e) => { alert('h5-fail') })// var map = new AMap.Map('container', {//   resizeEnable: true// })// var map = new AMap.Map('container', {//   // resizeEnable: true,//   // center: [120.023763, 30.289903],//   zoom: 15,// })AMap.plugin('AMap.Geolocation', function () {var geolocation = new AMap.Geolocation({// 是否使用高精度定位,默认:trueenableHighAccuracy: true,// 设置定位超时时间,默认:无穷大timeout: 10000,// 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)buttonOffset: new AMap.Pixel(10, 20),//  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:falsezoomToAccuracy: true,//  定位按钮的排放位置,  RB表示右下buttonPosition: 'RB'})geolocation.getCurrentPosition()AMap.event.addListener(geolocation, 'complete', onComplete)AMap.event.addListener(geolocation, 'error', onError)function onComplete(data) {// data是具体的定位信息alert('高德-success')alert(JSON.stringify(data))}function onError(data) {// 定位出错alert('高德-onError')console.log('error',data)alert(JSON.stringify(data))}})</script>
</body>
</html>

腾讯

比以上两种方式定位成功率高很多,同时兼容ios、android、pc端。定位方式多样,包括GPS定位、IP定位等。

<!DOCTYPE html>
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>前端定位模块</title> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"><style>* {margin: 0;padding: 0;border: 0;}body {position: absolute;width: 100%;height: 100%;text-align: center;}#pos-area {background-color: #009DDC;margin-bottom: 10px;width: 100%;overflow: scroll;text-align: left;color: white;}#demo {padding: 8px;font-size: small;}#btn-area {height: 100px;}button {margin-bottom: 10px;padding: 12px 8px;width: 42%;border-radius: 8px;background-color: #009DDC;color: white;}</style><script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script></head>
<body><div id="pos-area"><p id="demo">点击下面的按钮,获得对应信息:<br /></p></div><div id="btn-area"><button onClick="geolocation.getLocation(showPosition, showErr, options)">获取精确定位信息</button><button onClick="geolocation.getIpLocation(showPosition, showErr)">获取粗糙定位信息</button><button onClick="showWatchPosition()">开始监听位置</button><button onClick="showClearWatch()">停止监听位置</button></div><script type="text/JavaScript">var geolocation = new qq.maps.Geolocation("OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77", "myapp");document.getElementById("pos-area").style.height = (document.body.clientHeight - 110) + 'px';var positionNum = 0;var options = {timeout: 8000};function showPosition(position) {console.log('获取精确定位信息', position)positionNum ++;document.getElementById("demo").innerHTML += "序号:" + positionNum;document.getElementById("demo").appendChild(document.createElement('pre')).innerHTML = JSON.stringify(position, null, 4);document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;};function showErr() {positionNum ++;document.getElementById("demo").innerHTML += "序号:" + positionNum;document.getElementById("demo").appendChild(document.createElement('p')).innerHTML = "定位失败!";document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;};function showWatchPosition() {document.getElementById("demo").innerHTML += "开始监听位置!<br /><br />";geolocation.watchPosition(showPosition);document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;};function showClearWatch() {geolocation.clearWatch();document.getElementById("demo").innerHTML += "停止监听位置!<br /><br />";document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight;};</script>
</body>
</html>

封装定位方法

  <script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>// 获取定位信息(多种定位方式-GPS/IP等)
export function getLocation(){return new Promise((res, rej) => {const geolocation = new qq.maps.Geolocation('JDZBZ-5LUCQ-N4X5T-G5QCL-2WOC6-IKFHR','myapp')geolocation.getLocation(data => {res(data)},err => {rej(err)},{ timeout: 1000 })})
}

将文件单独抽离

   // 定位API链接<script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>// 链接资源<script>window.qq=window.qq||{},qq.maps=qq.maps||{},window.soso||(window.soso=qq),soso.maps||(soso.maps=qq.maps),qq.maps.Geolocation=function(){"use strict";var e=[],t=null,o=0,n="_geoIframe_"+Math.ceil(1e7*Math.random()),i=document.createElement("iframe"),r=null,s=null,a=null,c=null,u=function(u,l){if(!u)return void alert("璇疯緭鍏ey锛�");if(!l)return void alert("璇疯緭鍏eferer锛�");var p=document.getElementById(n);if(!p){i.setAttribute("id",n),i.setAttribute("allow","geolocation");var g="https:";i.setAttribute("src",g+"//apis.map.qq.com/tools/geolocation?key="+u+"&referer="+l),i.setAttribute("style","display: none; width: 100%; height: 30%"),document.body?document.body.appendChild(i):document.write(i.outerHTML);var m=this;window.addEventListener("message",function(n){var i=n.data;if(i&&"geolocation"==i.module){if(clearTimeout(c),e.length>0){var u=e.shift();u.sucCb&&u.sucCb(i)}o=2,m.executeNextGeo(),t&&t(i)}else{s=(new Date).getTime();var l=s-r;if(l>=a){if(e.length>0&&"geo"===e[0].type){var u=e.shift(),p={type:"fail",code:5,message:"The request"};u.errCb&&u.errCb(p)}clearTimeout(c),o=-1,m.executeNextGeo()}if(e.length>0&&"ip"===e[0].type){var u=e.shift();u.errCb&&u.errCb(p)}}},!1)}};return u.prototype.executeNextGeo=function(){1!==o&&e.length>0&&(o=1,e[0].geoprocess())},u.prototype.getLocation=function(t,n,i){if(i&&i.timeout){var r=new RegExp("^[0-9]*$");if(!r.test(i.timeout))return void alert("timeout 璇疯緭鍏ユ暟瀛�")}if(e.length>10)throw new Error("geolocation queue must be lass than 10");e.push({sucCb:t,errCb:n,option:i,geoprocess:this.getOnceLocation,type:"geo"}),1!==o&&(o=1,this.getOnceLocation())},u.prototype.getOnceLocation=function(){var t=e[0]&&e[0].option;r=(new Date).getTime(),a=t&&t.timeout?+t.timeout:1e4,clearTimeout(c),c=setTimeout(function(){if(e.length>0){var t=e.shift();t.errCb&&t.errCb()}},a),document.getElementById(n).contentWindow.postMessage("getLocation","*")},u.prototype.getIpLocation=function(t,n){if(e.length>10)throw new Error("geolocation queue mast be lass than 10");e.push({sucCb:t,errCb:n,geoprocess:this.getOnceIpLocation,type:"ip"}),1!==o&&(o=1,this.getOnceIpLocation())},u.prototype.getOnceIpLocation=function(){document.getElementById(n).contentWindow.postMessage("getLocation.robust","*")},u.prototype.watchPosition=function(e){t=e,document.getElementById(n).contentWindow.postMessage("watchPosition","*")},u.prototype.clearWatch=function(){t=null,document.getElementById(n).contentWindow.postMessage("clearWatch","*")},u}();</script>
···

h5定位总结(h5api + 高德 + 腾讯)相关推荐

  1. 高德h5定位误差_#高德地图api移动端定位失败解决方案 #H5 原生Geollocation接口Chomre浏览器的坑...

    侧重:本文探索了 http 协议下,pc + 移动端定位解决方案 IOS版本: ios14 原生Geolocation 接口: Document Show my location function g ...

  2. 高德h5定位误差_高德地图定位JS API不准确问题

    到网上找了个解决高德偏移量的代码 https://blog.csdn.net/woshimu... 我的是ip定位 转换过的定位就准确了 this.map.plugin('AMap.Geolocati ...

  3. 高德地图H5 定位失败报错 geolocation time out. Get ipLocation failed解决方案

    高德地图H5 定位失败报错 geolocation time out. Get ipLocation failed的解决方法. 前言:此坑踩得我挺难受的,搞了三天 需求:进入页面,获取用户具体经纬度并 ...

  4. 用高德js api做h5定位功能

    定位失败?what 最近项目中有一需求要实现手机定位当前城市功能, 查了高德地图api,根据文档说明很快就做出来了. AMap.plugin('AMap.CitySearch', function ( ...

  5. 记录--Openlayers 高德腾讯、百度、天地图坐标相互转换

    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 在地图开发过程中,坐标的转换是很常用的功能,国内的话一般西安80(EPSG:4610).北京54(EPSG:2433)转WGS84比较多, ...

  6. uniapp中实现微信H5定位、解决跨域问题

    uniapp中实现微信H5定位 跨域问题: 移动端h5中直接使用WebServiceAPI可能会有跨域问题,前端最简单的解决方法就是jsonp, 但uniapp中再使用jQuery的ajax就不太友好 ...

  7. Openlayers 高德腾讯、百度、天地图坐标相互转换

    Openlayers 腾讯.百度.天地图坐标转换 OpenLayers 教程 Openlayers 腾讯.百度.天地图坐标转换 在线示例 OpenLayers 教程 在地图开发过程中,坐标的转换是很常 ...

  8. 地图poi数据下载-2019全国地图poi数据-百度高德腾讯

    百度高德腾讯地图poi数据下载 全国地图poi数据-下载 上海市(2947012) 上海城区(2947012) 江苏省(8157158) 南京市(1073860) 无锡市(974774) 徐州市(59 ...

  9. 解决高德地图锁屏黑屏定位不更新,高德地图绘制定位轨迹,高德定位判断定位停留点,高德地图将所有坐标绘制在可视区域内

    本文章主要介绍 高德定位锁屏黑屏定位不更新的问题. 实现流程是:程序开始阶段正常执行定位,注册监听锁屏监听,唤醒cpu监听,当锁屏 广播每2秒发起一起单次定位唤醒.源码如下: package net. ...

最新文章

  1. 某leader求助:周六晚上拉下属开会,被下属怀孕的老婆公然大骂,怎么办?网友:活该!...
  2. Javascript+xmlhttp调用Webservice
  3. 安卓 内存泄漏检测工具 LeakCanary 使用
  4. 解决Nginx: [error] open() "/usr/local/Nginx/logs/Nginx.pid
  5. boost::ratio_greater_equal相关的测试程序
  6. mysql大数据量处理
  7. 在应用程序中实现对NandFlash的操作
  8. 游戏笔记本计算机购买,2021大学生买电脑,容易犯的七种错误!游戏本和轻薄本买哪个?...
  9. Buffer、ArrayBuffer、DataView互转(node.js)
  10. 学Java看这就完事了!javasocket编程例子
  11. intel 82599网卡系统下丢失一路万兆端口
  12. 一步步教你破解WIFI无线WEP网络密钥
  13. RS-485通讯协议
  14. 【Bandit Algorithms学习笔记】EXP3算法理论证明
  15. python爬虫天猫商品数据及分析(1)
  16. 值对象 Value Object
  17. 简述计算机病毒的传播4种途径,4计算机病毒的传播途径.ppt
  18. Luogu_P4556 雨天的尾巴【题解】树上差分 线段树合并
  19. CCED,一个时代的落幕
  20. 信号采样与sinc插值恢复MATLAB

热门文章

  1. java ssm勤工助学岗位管理系统
  2. ifttt_如何使用智能手机和IFTTT创建地理事件触发器
  3. 颠覆式改变的丰田全新威驰VIOS
  4. C++11拉达姆lamda的使用以及注意事项
  5. 如何使用Premier下载最新平台的BIOS
  6. 基于RTT压缩包C基础-不明白的接口PRF_ENV_GET __attribute__
  7. Saxon PE usage
  8. 基本算法(用 PASCAL 描述)
  9. Sqlserver操作系统用户Administrator本地登陆SSMS报错18456的解决方法
  10. 会玩这 10 个 Linux 命令,一定是个有趣的 IT 男!