使用navigator.geolocation解决h5公众号定位不准确的问题

发布时间 2023-04-11 16:27:09作者: zaijinyang

封装js(utils/geolocation.min.js):

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("请输入key!");if(!l)return void alert("请输入referer!");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}();

使用:

<!-- 精确定位 -->
<template>
  <view>{{ positionInfo }}</view>
</template>

<script>
import '@/utils/geolocation.min.js';
export default {
  data() {
    return {
      positionInfo: ''
    };
  },
  onLoad(options) {
    this._initLocation();
  },
  methods: {
    _initLocation() {
      if (origin.indexOf('https') === -1) {
        uni.showToast({
          title: '请在https环境中使用'
        });
        return;
      }
      if (!navigator || !navigator.geolocation) {
        uni.showToast({
          title: '地理位置服务不可用'
        });
        return;
      }
      uni.showLoading({
        title: '定位中...',
        mask: true
      });
      const options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      };
      /** err 说明
				code 1  表示用户拒绝授权
				code 3  未获取到地址信息,可能是设备没有开启定位服务或者系统没有给浏览器定位权限
			**/
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const lat = position.coords.latitude,
            lng = position.coords.longitude,
            geo = new qq.maps.Geolocation('QAWBZ-S2MWR-U5OWI-WZBUC-UXDSZ-AAFRJ', '获取位置信息');
          geo.getLocation(this.getLocationSuccess, this.getLocationErr, options);
        },
        (err) => {
          if (err.code === 1) {
            uni.showModal({
              title: '获取定位权限失败',
              content: '你拒绝了位置授权服务。请允许当前页面获取定位授权,后刷新页面。'
            });
          } else {
            uni.showModal({
              title: '获取定位权限失败',
              content: '请确定手机定位已打开,并且当前浏览器允许获取定位,都开启后请刷新页面。'
            });
          }
          uni.hideLoading();
        }
      );
    },
    getLocationSuccess(position) {
      uni.showToast({
        title: '定位成功!',
        duration: 1000
      });
      this.positionInfo = position;
      uni.hideLoading();
    },
    getLocationErr() {
      uni.showToast({
        title: '获取位置失败!',
        duration: 2000
      });
      uni.hideLoading();
    }
  }
};
</script>

  

效果:

                

 

 注:使用浏览器定位域名必须是https访问