本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-02-26
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
async function getSignature() {
const thisPageUrl = window.location.href.split('#')[0];
const response = await requestWxSignature(thisPageUrl); // 向后端请求拿到签名
if (response) {
return response.data;
}
}
// 点击打开最近营业厅的地图
function openMap() {
const data = await getSignature()
const { appId, timestamp, nonceStr, signature} = data;
wx.config({
appId,
timestamp,
nonceStr,
signature,
jsApiList: ['openLocation', 'getLocation'] // 传递需要调用的api
});
wx.ready(() => {
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: async res => {
// 拿到当前设备的经纬度信息
const localLat = res.latitude; // 纬度,浮点数,范围为90 ~ -90
const localLgt = res.longitude; // 经度,浮点数,范围为180 ~ -180。
// 请求后端获取最近的营业厅地址,传入当前客户端的定位坐标
const resp = await requestNearbyBusinessHall({
latitude: `${localLat}`,
longitude: `${localLgt}`
});
if (resp) {
const data = resp.data;
// 后端返回的是百度地图坐标,根据方法转换为微信地图坐标
const coord = bdToWx(+data.lat, +data.lng);
// 获得最近的营业厅地址 调用 wx.openLocation
wx.openLocation({
latitude: coord.newlat, // 纬度,浮点数,范围为90 ~ -90 必须是Number
longitude: coord.newlng, // 经度,浮点数,范围为180 ~ -180。 必须是Number
name: data.name, // 位置名
address: data.adress, // 地址详情说明
scale: 16, // 地图缩放级别,整形值,范围从1~28。默认为最大
infoUrl: '', // 在查看位置界面底部显示的超链接,可点击跳转
fail() {
alert('打开地图失败');
}
});
}
},
fail() {
alert('获取地理位置失败');
}
});
});
}
function bdToWx(lat, lng){
const p = 3.14159265358979324 * 3000 / 180;
const x = lng - 0.0065;
const y = lat - 0.006;
const z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * p);
const t = Math.atan2(y, x) - 0.000003 * Math.cos(x * p);
const newlng = z * Math.cos(t);
const newlat = z * Math.sin(t);
return { newlng, newlat };
}
console.log(bdToWx(22.539946, 114.063637));
function wxToBd(lat, lng){
const p = 3.14159265358979324 * 3000 / 180;
const x = lng;
const y = lat;
const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * p);
const t = Math.atan2(y, x) + 0.000003 * Math.cos(x * p);
const newlng = z * Math.cos(t) + 0.0065;
const newlat = z * Math.sin(t) + 0.006;
return { newlng, newlat };
}
console.log(wxToBd(22.534288127909594, 114.05708935923532));