110 lines
2.7 KiB
JavaScript
110 lines
2.7 KiB
JavaScript
/**
|
||
* 高德地图微信小程序SDK - 纯定位版
|
||
* 只负责GPS定位,地址解析由后端处理
|
||
*/
|
||
|
||
class AMapWX {
|
||
constructor(options = {}) {
|
||
this.key = options.key || '';
|
||
this.version = '1.5.0';
|
||
|
||
if (this.key) {
|
||
console.log(`API Key: ${this.key.substring(0, 8)}...`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取微信定位 - 主要功能
|
||
* @param {function} callback - 定位回调函数 callback(location, error)
|
||
* @param {object} options - 定位选项
|
||
*/
|
||
getWxLocation(callback, options = {}) {
|
||
const defaultOptions = {
|
||
type: 'gcj02',
|
||
isHighAccuracy: true,
|
||
highAccuracyExpireTime: 4000,
|
||
...options
|
||
};
|
||
|
||
wx.getLocation({
|
||
...defaultOptions,
|
||
success: (res) => {
|
||
|
||
const location = {
|
||
longitude: res.longitude,
|
||
latitude: res.latitude,
|
||
accuracy: res.accuracy || 0,
|
||
altitude: res.altitude || 0,
|
||
speed: res.speed || 0,
|
||
horizontalAccuracy: res.horizontalAccuracy || 0,
|
||
verticalAccuracy: res.verticalAccuracy || 0
|
||
};
|
||
|
||
if (typeof callback === 'function') {
|
||
callback(location, null);
|
||
}
|
||
},
|
||
fail: (err) => {
|
||
console.error('[AMapWX] 微信定位失败:', err);
|
||
|
||
if (typeof callback === 'function') {
|
||
callback(null, err);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 计算两点间距离
|
||
* @param {object} point1 - 起点 {longitude, latitude}
|
||
* @param {object} point2 - 终点 {longitude, latitude}
|
||
* @returns {number} 距离(米)
|
||
*/
|
||
calculateDistance(point1, point2) {
|
||
const R = 6371000; // 地球半径(米)
|
||
const lat1 = point1.latitude * Math.PI / 180;
|
||
const lat2 = point2.latitude * Math.PI / 180;
|
||
const deltaLat = (point2.latitude - point1.latitude) * Math.PI / 180;
|
||
const deltaLng = (point2.longitude - point1.longitude) * Math.PI / 180;
|
||
|
||
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
|
||
Math.cos(lat1) * Math.cos(lat2) *
|
||
Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
|
||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||
|
||
return R * c;
|
||
}
|
||
}
|
||
|
||
// 创建单例实例
|
||
let amapInstance = null;
|
||
|
||
const AmapWX = {
|
||
/**
|
||
* 获取SDK实例
|
||
* @param {object} options - 配置选项
|
||
* @returns {AMapWX}
|
||
*/
|
||
getInstance(options = {}) {
|
||
if (!amapInstance) {
|
||
amapInstance = new AMapWX(options);
|
||
}
|
||
return amapInstance;
|
||
},
|
||
|
||
/**
|
||
* 重置SDK实例
|
||
* @param {object} options - 配置选项
|
||
* @returns {AMapWX}
|
||
*/
|
||
resetInstance(options = {}) {
|
||
amapInstance = new AMapWX(options);
|
||
return amapInstance;
|
||
}
|
||
};
|
||
|
||
// 导出模块
|
||
module.exports = {
|
||
AMapWX,
|
||
AmapWX
|
||
};
|