Skip to main content
 首页 » 编程设计

c# haversine 实现给出了与 googlemaps/movable-type.co.uk 不同的答案

2024年02月06日30JeffreyZhao

我需要计算两点之间的距离(给定纬度和经度)。我在 C# 中实现了标准的 haversine 公式

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;    
} 

但是我从代码和网站上得到了不同的答案http://www.movable-type.co.uk/scripts/latlong.html . 例如对于输入:pos1.Latitude = 12.916822 和 Pos1.Longitude = 77.599816 和 pos2.Latitude = 12.917135 和 Pos2.Longitude = 77.585783 我的程序返回 34.843(当我在答案上执行 Math.Round((dist), 4) 时)网站给出 1.521 Kms 任何人都可以指出错误吗? PS:我的程序以米为单位计算距离。

请您参考如下方法:

我正在快速查看它,这应该是一个简单的修复。如何更改以下内容:

double dLon = toRadian(pos2.Longitude - pos2.Longitude); 

...进入:

double dLon = toRadian(pos2.Longitude - pos1.Longitude); 

注意到 pos1/pos2 错别字了吗? :)