Files
mini-programs/src/utils/locationUtils.ts
2025-09-07 18:54:36 +08:00

118 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Taro from '@tarojs/taro'
export interface Location {
latitude: number
longitude: number
speed?: number
accuracy?: number
}
export interface LocationInfo {
latitude: number
longitude: number
address: string
name?: string
}
// 获取当前位置
export const getCurrentLocation = (): Promise<LocationInfo> => {
return new Promise((resolve, reject) => {
Taro.getLocation({
type: 'wgs84',
success: (res) => {
console.log('===获取地理位置', res)
// 使用逆地理编码获取地址信息
reverseGeocode(res.latitude, res.longitude)
.then(address => {
resolve({
latitude: res.latitude,
longitude: res.longitude,
address
})
})
.catch(() => {
resolve({
latitude: res.latitude,
longitude: res.longitude,
address: `${res.latitude.toFixed(6)}, ${res.longitude.toFixed(6)}`
})
})
},
fail: (error) => {
reject(error)
}
})
})
}
// 选择地图位置
export const chooseLocation = (): Promise<LocationInfo> => {
return new Promise((resolve, reject) => {
Taro.chooseLocation({
success: (res) => {
resolve({
latitude: res.latitude,
longitude: res.longitude,
address: res.address,
name: res.name
})
},
fail: (error) => {
reject(error)
}
})
})
}
export const getLocation = (): Promise<Location> => {
return new Promise((resolve, reject) => {
Taro.getLocation({
success: (res) => {
resolve({
latitude: res.latitude,
longitude: res.longitude,
speed: res.speed,
accuracy: res.accuracy
})
},
fail: (error) => {
reject(error)
}
})
})
}
// 逆地理编码简化版本实际项目中应该调用真实的地图服务API
export const reverseGeocode = (latitude: number, longitude: number): Promise<string> => {
return new Promise((resolve) => {
// 这里应该调用真实的地图服务API比如腾讯地图、高德地图等
// 暂时返回坐标字符串
setTimeout(() => {
resolve(`纬度:${latitude.toFixed(6)}, 经度:${longitude.toFixed(6)}`)
}, 500)
})
}
// 计算两点间距离(单位:米)
export const calculateDistance = (
lat1: number,
lng1: number,
lat2: number,
lng2: number
): number => {
const radLat1 = lat1 * Math.PI / 180.0
const radLat2 = lat2 * Math.PI / 180.0
const a = radLat1 - radLat2
const b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
let s = 2 * Math.asin(Math.sqrt(
Math.pow(Math.sin(a/2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) *
Math.pow(Math.sin(b/2), 2)
))
s = s * 6378.137 // 地球半径
s = Math.round(s * 10000) / 10000
return s * 1000 // 转换为米
}