第三方api有腾讯、高德、百度,下面简述腾讯位置api

  1. 引入jweixin.js
<script>
// 方法一 把js文件放到自己服务器上
import wx from '@/static/jweixin-1.6.0.js';

// 方法二 vue在生命周期中应用
mounted() {
    const oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = "https://res2.wx.qq.com/open/js/jweixin-1.6.0.js";
    oScript.onload = this.wxInit();
    document.body.appendChild(oScript);
},
methods: {
	wxInit(){
		// 配置
	}
}


</script>
  1. 获取位置
// 根路径
uni.setStorageSync('WxCodeUrl', location.href)


methods: {
	async wxInit() {
		/**
		这部分是ios兼容问题
		ios真机中 签名会提示RealURL和URl不一致,
		原因是ios中会把进入程序的第一个页面当作RealURL从而导致签名失败
		 */
      const ua = navigator.userAgent.toLowerCase();
      let url = window.location.href
      if (/iphone|ipad|ipod/.test(ua)) {
        url = uni.getStorageSync('WxCodeUrl');
      }
      let that = this

      await this.$api.ihosp_regist_wxjsdk({
        thdAppId: getInitAppId(),
        url: url
      }).then(res => {
        wx.config({
          debug: false,
          appId: APPID, // 必填,公众号的唯一标识
          timestamp: res.timestamp, // 必填,生成签名的时间戳
          nonceStr: res.nonceStr, // 必填,生成签名的随机串
          signature: res.signature, // 必填,签名
          jsApiList: ['getLocation'],
        });

        that.waitForWxReady().then(() => {
          that.getLocation()
        }).catch((err) => {
          // 未获取到定位信息 刷新重试
          console.error(err);
        })
      })
    },
    waitForWxReady(index) {
      let that = this
      return new Promise((resolve, reject) => {
        if (typeof wx !== 'undefined') {
          if (wx.ready) {
            resolve();
          } else {

            document.addEventListener('WeixinJSBridgeReady', () => {
              resolve();
            });
          }
        } else {
          // wx 对象不存在,可能不处于微信环境中,reject 报错
          reject(new Error('请在微信环境中打开页面'));
        }
      });
    },
	getLocation(){
		wx.checkJsApi({
        jsApiList: ['getLocation'],
        success: function (res) {
          if (res.checkResult.getLocation == false) {
            uni.showModal({
              title: '你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!',
            })
            return;
          }
        }
      })

      wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: true, // 开启高精度定位
        highAccuracyExpireTime: 3000, // 高精度定位超时时间(ms),指定时间内返回最高精度,该值3000ms以上高精度定位才有效果
        success: (res) => {
        	// res.latitude,res.longitude
        },
        cancel: function (res) {
          uni.showModal({
            title: '用户拒绝授权获取地理位置',
          })
        }
      });
	}
}

在微信环境下是推荐使用微信api的,用户未开启定位,安卓手机会弹出下图,去设置会跳到用户开启定位的位置。ios因为系统原因是不会弹窗的,鸿蒙4也不会弹出下面框。
高德和百度也都尝试过,在微信环境中体验感并没有微信好用
在这里插入图片描述

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐