84 行
2.4 KiB
JavaScript
84 行
2.4 KiB
JavaScript
// pwuniapp/common/location.js
|
||
// 同城生活陪伴小程序统一地图与定位能力服务层
|
||
|
||
// 默认腾讯位置服务 Key(可在管理后台【安全合规-平台系统配置-地图定位服务】动态更新维护)
|
||
// 申请地址:https://lbs.qq.com
|
||
export const DEFAULT_TENCENT_MAP_KEY = '';
|
||
|
||
/**
|
||
* 计算两个经纬度坐标之间的球面距离(千米/km)
|
||
* @param {number} lat1 纬度1
|
||
* @param {number} lon1 经度1
|
||
* @param {number} lat2 纬度2
|
||
* @param {number} lon2 经度2
|
||
* @returns {string} 格式化后的距离(例如 "1.2km" 或 "350m")
|
||
*/
|
||
export function calculateDistance(lat1, lon1, lat2, lon2) {
|
||
if (!lat1 || !lon1 || !lat2 || !lon2) return '同城';
|
||
const toRad = (d) => (d * Math.PI) / 180;
|
||
const R = 6371; // 地球平均半径(km)
|
||
const dLat = toRad(lat2 - lat1);
|
||
const dLon = toRad(lon2 - lon1);
|
||
const a =
|
||
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
|
||
Math.sin(dLon / 2) * Math.sin(dLon / 2);
|
||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||
const d = R * c;
|
||
|
||
if (d < 1) {
|
||
return `${Math.round(d * 1000)}m`;
|
||
}
|
||
return `${d.toFixed(1)}km`;
|
||
}
|
||
|
||
/**
|
||
* 唤起地图选点 (chooseLocation)
|
||
* 封装权限申请与平台兼容处理
|
||
* @returns {Promise<{name: string, address: string, latitude: number, longitude: number}>}
|
||
*/
|
||
export function chooseMapLocation() {
|
||
return new Promise((resolve, reject) => {
|
||
// #ifdef MP-WEIXIN || APP-PLUS
|
||
uni.chooseLocation({
|
||
success: (res) => {
|
||
resolve({
|
||
name: res.name || '',
|
||
address: res.address || '',
|
||
latitude: res.latitude,
|
||
longitude: res.longitude
|
||
});
|
||
},
|
||
fail: (err) => {
|
||
reject(err);
|
||
}
|
||
});
|
||
// #endif
|
||
|
||
// #ifndef MP-WEIXIN || APP-PLUS
|
||
reject(new Error('当前运行环境不支持原生地图选点'));
|
||
// #endif
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取当前用户地理位置经纬度 (getLocation)
|
||
* @returns {Promise<{latitude: number, longitude: number}>}
|
||
*/
|
||
export function getUserLocation() {
|
||
return new Promise((resolve, reject) => {
|
||
uni.getLocation({
|
||
type: 'gcj02', // 国测局坐标系,腾讯地图/高德地图通用
|
||
success: (res) => {
|
||
resolve({
|
||
latitude: res.latitude,
|
||
longitude: res.longitude
|
||
});
|
||
},
|
||
fail: (err) => {
|
||
reject(err);
|
||
}
|
||
});
|
||
});
|
||
}
|