方案:定位获取在支付宝端处理 H5端进行接收(支付宝小程序与H5进行通讯)
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;
}
};
<web-view id="web-view-1" onMessage="onmessage" onError="failLoad" onLoad="successLoad" src="{{ src }}"></web-view>
Page({
onLoad(e) {
this.webViewContext = my.createWebViewContext('web-view-1');
},
onmessage(e) {
authGuideLocation().then(res => {
console.log(res);
if (res === true) {
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)
}
})
},
});
<html>
<script src="https://cdn.bootcdn.net/ajax/libs/eruda/3.0.1/eruda.min.js"></script>
<script>eruda.init()</script>
<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);
if (res.miniprogram) {
my.postMessage({ name: "测试web-view" });
my.onMessage = (e) => {
console.log('接收的支付宝小程序信息:', e);
if (e.location&&e.location.longitude && e.location.latitude) {
}
}
}
});
</script>