// 高德地图key export const GAODE_MAP_KEY = import.meta.env.VITE_AMAP_KEY // 获取地图实例 export function getMapContext(mapid: string, instance: any) { return uni.createMapContext(mapid, { this: instance.proxy, }) } // 获取当前定位 export function getLoalcation({ mapContext, success = null, fail = null, moveCenter = false, }) { uni.getLocation({ type: 'gcj02', geocode: true, success(res) { console.log('定位成功', res) const { latitude, longitude } = res if (moveCenter && mapContext) { moveToLocation(mapContext, longitude, latitude) } success && success({ latitude, longitude }) }, fail(err) { console.error('uni.getLocation-------', err) fail && fail(err) }, }) } // 移至中心点 export function moveToLocation(mapContext: any, longitude: number, latitude: number) { const point = { latitude, longitude, } mapContext.moveToLocation(point) } /** * 添加线 * @param sColor 线颜色 * @param arrPoint 线坐标 * @param width 线宽度 * @param arrowLine 是否有箭头 */ export function addLine({ sColor, arrPoint, width = 4, arrowLine = false, }: { sColor: string arrPoint: any[] width?: number arrowLine?: boolean }) { return { points: arrPoint, color: sColor, width, arrowLine, } } /** * 获取路径规划 * @param mapsdk 高德地图sdk实例 * @param slng 起点经度 * @param slat 起点纬度 * @param elng 终点经度 * @param elat 终点纬度 * @param success 成功回调 * @param fail 失败回调 */ export function getRoutePlan({ mapsdk, slng, slat, elng, elat, success, fail, }: { mapsdk: any slng: number slat: number elng: number elat: number success: (res: any) => void fail: (err: any) => void }) { // 检测 mapsdk 实例是否存在 if (!mapsdk) { fail && fail('mapsdk实例不存在') console.error('mapsdk实例不存在') return } // 判断经纬度是否齐全 if (!slng || !slat || !elng || !elat) { fail && fail('经纬度参数不完整') console.error('经纬度参数不完整') return } const options = { origin: `${slng},${slat}`, destination: `${elng},${elat}`, success: (res: any) => { const points = [] let distance = 0 if (res?.paths[0]?.steps) { const steps = res.paths[0].steps distance = res.paths[0].distance for (let i = 0; i < steps.length; i++) { const poLen = steps[i].polyline.split(';') for (let j = 0; j < poLen.length; j++) { points.push({ longitude: Number.parseFloat(poLen[j].split(',')[0]), latitude: Number.parseFloat(poLen[j].split(',')[1]), }) } } } const cnt = (distance / 1000).toFixed(2) let sdistance = `${distance}m` if (Number.parseFloat(cnt) >= 1) { sdistance = `${cnt}km` } const data = { arrPoint: points, distance: sdistance, } if (success) success(data) }, fail: (error: any) => { fail && fail(error) }, } mapsdk.getDrivingRoute(options) }