h5定位总结(h5api + 高德 + 腾讯)

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, //是否使用高精度定位,默认:true
        timeout: 1000, //超过10秒后停止定位,默认:5s
        buttonPosition: '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({
        // 是否使用高精度定位,默认:true
        enableHighAccuracy: true,
        // 设置定位超时时间,默认:无穷大
        timeout: 10000,
        // 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
        buttonOffset: new AMap.Pixel(10, 20),
        //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
        zoomToAccuracy: 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 += "开始监听位置!

"
; geolocation.watchPosition(showPosition); document.getElementById("pos-area").scrollTop = document.getElementById("pos-area").scrollHeight; }; function showClearWatch() { geolocation.clearWatch(); document.getElementById("demo").innerHTML += "停止监听位置!

"
; 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>   
···

你可能感兴趣的:(JavaScript)