Files
wechatWeb/tool/funTool.js
张成 aa8eaa6ccd init
2026-03-24 16:07:02 +08:00

77 lines
1.8 KiB
JavaScript
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.
const fs = require("fs");
const request = require("request");
const path = require("path");
module.exports = {
delay(seconds = 1, callback) {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (callback) {
callback();
}
resolve(true);
}, seconds * 1000);
});
return promise;
},
mkdirsSync(dirname) {
if (fs.existsSync(dirname)) {
return true;
} else {
if (this.mkdirsSync(path.dirname(dirname))) {
fs.mkdirSync(dirname);
return true;
}
}
},
isExist(path) {
let promise = new Promise((resolve, reject) => {
fs.access(path, function (err) {
if (err && err.code == "ENOENT") {
resolve(false);
}
resolve(true);
});
});
return promise;
},
/**
* 计算两个地理坐标点之间的距离Haversine公式
* @param {number} lat1 起点纬度
* @param {number} lng1 起点经度
* @param {number} lat2 终点纬度
* @param {number} lng2 终点经度
* @returns {number|null} 距离公里如果坐标无效则返回null
*/
calculateDistance(lat1, lng1, lat2, lng2) {
// 验证坐标参数
if (!lat1 || !lng1 || !lat2 || !lng2 ||
isNaN(lat1) || isNaN(lng1) || isNaN(lat2) || isNaN(lng2)) {
return null;
}
const R = 6371; // 地球半径(公里)
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLng = (lng2 - lng1) * Math.PI / 180;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;
// 保留两位小数
return Math.round(distance * 100) / 100;
},
};