我需要计算两点之间的距离(给定纬度和经度)。我在 C# 中实现了标准半正矢公式
private double toRadian(double val)
{
return (Math.PI / 180) *
}
public double Distance(Position pos1, Position pos2,DistanceType type)
{
double R = (type == DistanceType.Miles) ? 3960 : 6378137; // 6318137 in meters
double dLat = toRadian(pos2.Latitude - pos1.Latitude);
double dLon = toRadian(pos2.Longitude - pos2.Longitude);
double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Cos(this.toRadian(pos1.Latitude)) * Math.Cos(this.toRadian(pos2.Latitude)) *
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
double d = R * c;
return d;
}
Run Code Online (Sandbox Code Playgroud)
但我从代码和网站http://www.movable-type.co.uk/scripts/latlong.html中得到了不同的答案。例如,对于输入:pos1.Latitude = 12.916822and Pos1.Longitude = 77.599816
and pos2.Latitude = 12.917135 and Pos2.Longitude = 77.585783 我的程序返回 34.843 (当我对Math.Round((dist), 4)答案执行 a 时),而网站给出 1.521 Kms 谁能指出问题所在吗?PS:我的程序以米为单位计算距离。
当我快速查看它时,这应该是一个简单的修复。更改以下内容如何:
double dLon = toRadian(pos2.Longitude - pos2.Longitude);
Run Code Online (Sandbox Code Playgroud)
... 进入:
double dLon = toRadian(pos2.Longitude - pos1.Longitude);
Run Code Online (Sandbox Code Playgroud)
注意到 pos1/pos2 拼写错误了吗?:)