需求:使用微信浏览器获取用户定位,并使用高德地图获取当前地址,并计算两点之间距离
1.先安装微信sdk
npm i weixin-js-sdk -S
在需要的页面引用:import wx from "weixin-js-sdk";
2. 获取timestamp和nonceStr,并初始化微信JS-SDK配置
具体文档:网页授权 | 微信开放文档
接口调用说明:概述 | 微信开放文档
async getWxConfigConfig() {
try {
var url = window.location.href.split("#")[0];
let axiosUrl = "接口地址";
const data = {
url: url,
};
const { data: res } = await axios.post(
`${axiosUrl}`,
qs.stringify(data)
);
const wxconfig = {
appId: res.data.appid,
timestamp: res.data.timestamp,
nonceStr: res.data.nonceStr,
signature: res.data.signature,
};
wx.config({
debug: false,
appId: wxconfig.appId,
timestamp: wxconfig.timestamp,
nonceStr: wxconfig.nonceStr,
signature: wxconfig.signature,
jsApiList: [
"updateAppMessageShareData",
"updateTimelineShareData",
"checkJsApi",
"openLocation",
"getLocation",
],
openTagList: ["wx-open-subscribe"],
});
wx.ready(() => {
//获取用户当前位置
wx.getLocation({
type: "wgs84",
success: (res) => {
const { longitude, latitude } = res;
this.userLocation = { longitude, latitude };
this.getUserProvince();
},
cancel: () => {
console.log("用户拒绝授权获取地理位置");
},
fail: (error) => {
console.error("获取用户定位失败", error);
},
});
});
} catch (error) {
console.error("微信配置失败", error);
}
},
3.根据经纬度用高德获取当前所在城市地址(首先先申请高德Key)
async getUserProvince() {
try {
if (!this.userLocation) {
console.error("用户位置不可用");
return;
}
const { longitude, latitude } = this.userLocation;
const amapApiKey = "高德API Key";
const mapurl = `https://restapi.amap.com/v3/geocode/regeo?key=${amapApiKey}&location=${longitude},${latitude}&output=JSON&batch=false&roadlevel=0`;
const response = await axios.get(mapurl);
var rcd = response.data.regeocode;
this.addr = rcd.addressComponent.district;
console.error("找不到当前位置");
} catch (error) {
console.error("获取当前位置失败", error);
}
},
4.计算两点之间距离
getDistance(item) {
if (!this.userLocation) {
return "计算中...";
}
// 将纬度和经度转换为地图。LngLat对象
const point1 = new AMap.LngLat(
this.userLocation.longitude,
this.userLocation.latitude
);
const point2 = new AMap.LngLat(item.longitude, item.latitude);
// 以米为单位计算距离
const distance = AMap.GeometryUtil.distance(point1, point2);
// 将距离转换为公里,四舍五入到小数点后一位
const distanceInKm = Math.round(distance / 100) / 10;
return `${distanceInKm} km`;
},
5.打开地图
openMap() {
wx.openLocation({
latitude: parseFloat(latitude), // 纬度,浮点数,范围为90 ~ -90
longitude: parseFloat(longitude), // 经度,浮点数,范围为180 ~ -180。
name: title,
address: site, // 地址详情说明
scale: 15,
});
},