参考文末的链接,直接给出通用答案:

1
2
3
4
5
6
7
const kRad = Math.PI / 180;
export const getDistance = (a, b) => {
const kx = Math.cos(a.lat * kRad) * 111.321;
const dx = (a.lng - b.lng) * kx;
const dy = (a.lat - b.lat) * 111.139;
return Math.sqrt((dx * dx) + (dy * dy));
};

如果是一个位置到其他多个位置的距离,可以重复使用kx

1
2
3
4
5
6
7
8
9
const kRad = Math.PI / 180;
export const ruler = (a) => {
const kx = Math.cos(a.lat * kRad) * 111.321;
return (b) => {
const dx = (a.lng - b.lng) * kx;
const dy = (a.lat - b.lat) * 111.139;
return Math.sqrt((dx * dx) + (dy * dy));
}
};

如果只想对各个距离做比较,而不是计算准确距离,可以省略平方根 Math.sqrt()


参考:
https://jamesloper.com/fastest-way-to-calculate-distance-between-two-coordinates