支付宝小程序webview内嵌H5使用定位

250 阅读2分钟
方案:定位获取在支付宝端处理  H5端进行接收(支付宝小程序与H5进行通讯)

//1.支付宝小程序端封装获取定位的方法
// 由于跳转到系统设置页无法监听用户最终是否打开系统定位及对支付宝授权位置信息,因此请在生命周期 onShow 中调用定位授权准备方法。
export const authGuideLocation = async () => {
  const myGetSystemInfo = () => {
    return new Promise((resolve, reject) => {
      my.getSystemInfo({
        success: resolve,
        fail: reject
      });
    });
  };

  const myGetSetting = () => {
    return new Promise((resolve, reject) => {
      my.getSetting({
        success: resolve,
        fail: reject
      });
    });
  };

  const myOpenSetting = () => {
    return new Promise((resolve, reject) => {
      my.openSetting({
        success: resolve,
        fail: reject
      });
    });
  };

  const myAlert = (content) => {
    return new Promise((resolve, reject) => {
      my.alert({
        content,
        success: resolve,
        fail: reject
      });
    });
  };

  // 获取用户是否开启系统定位及授权支付宝使用定位
  const isLocationEnabled = async () => {
    const systemInfo = await myGetSystemInfo();
    return !!(systemInfo.locationEnabled && systemInfo.locationAuthorized);
  };

  // 若用户未开启系统定位或未授权支付宝使用定位,则跳转至系统设置页
  const showAuthGuideIfNeeded = async () => {
    if (!(await isLocationEnabled())) {
      my.showAuthGuide({
        authType: "LBS"
      });
      return false;
    }
    return true;
  };

  // 获取用户是否授权过当前小程序使用定位
  const isLocationMPAuthorized = async () => {
    const settingInfo = await myGetSetting();
    return settingInfo.authSetting.location === undefined || settingInfo.authSetting.location;
  };

  // 若用户未授权当前小程序使用定位,则引导用户跳转至小程序设置页开启定位权限
  const requestLocationPermission = async () => {
    await myAlert("您之前取消过授权,是否前往授权?");
    const openSettingInfo = await myOpenSetting();
    return openSettingInfo.authSetting.location;
  };

  try {
    if (!(await showAuthGuideIfNeeded())) {
      return false;
    }
    if (await isLocationMPAuthorized()) {
      return true;
    }
    if (await requestLocationPermission()) {
      return true;
    }
    return false;
  } catch (error) {
    console.error(error);
    return false;
  }
};


//2.在支付宝小程序webview axml页面 
<web-view id="web-view-1"  onMessage="onmessage" onError="failLoad" onLoad="successLoad" src="{{ src }}"></web-view>

//小程序webview axjs逻辑中

Page({
  onLoad(e) {
    this.webViewContext = my.createWebViewContext('web-view-1');
  },
  onmessage(e) {
   // my.alert({
    //  content: JSON.stringify(e.detail),
    // });
   authGuideLocation().then(res => {
      console.log(res);
      if (res === true) {
      //定时每隔10分钟 重新获取一次经纬度 并传递到H5页面
    setInterval(()=>{
        my.getLocation({
          type: 2, // 获取经纬度和省市区县街道数据
          success: (res) => {
            console.log(res);
            let num=1
              this.webViewContext.postMessage({
               location: res,
               num:num++
              })      
          },
          fail: (res) => {
            my.alert({ title: '定位失败', content: JSON.stringify(res) });
          },
          complete: () => { },
        });
         },1000*60*10)
      }
    })
  },
});


//3.在h5端进行接收
//引入H5调试工具

<html>
    <script src="https://cdn.bootcdn.net/ajax/libs/eruda/3.0.1/eruda.min.js"></script>
<!--调试工具激活-->
    <script>eruda.init()</script>
    <!-- 引入支付宝小程序sdk -->
    <!-- <script type="text/javascript" src="https://appx/web-view.min.js"></script> -->
    <!-- 如该 H5 页面需要同时在非支付宝客户端内使用,为避免该请求404,可参考以下写法 -->
    <!-- 请尽量在 html 头部执行以下脚本 -->
    <script>
        if (navigator.userAgent.indexOf('AliApp') > -1) {
            document.writeln('<script src="https://appx/web-view.min.js"' + '>' + '<' + '/' + 'script>');
        }
    </script>
</html>

//H5中逻辑
<script>
// 支付宝小程序环境中
my.getEnv((res) => {
	console.log('当前在支付宝小程序环境中:', res.miniprogram); //true
	if (res.miniprogram) {
		my.postMessage({ name: "测试web-view" });
		// 接收来自小程序的消息。
		my.onMessage = (e) => {
			console.log('接收的支付宝小程序信息:', e); // 此时已经可以获取到定位数据了
			if (e.location&&e.location.longitude && e.location.latitude) {
                        //处理接收到的经纬度
				
			}
		}
	}
});
</script>