我尝试使用 EF 中的 NpSql 计算地理距离,但返回的结果始终为几何。
NetTopologySuite.Geometries.Coordinate coordinate1 = new NetTopologySuite.Geometries.Coordinate(12.25, 51.25);
NetTopologySuite.Geometries.Point point1 = new NetTopologySuite.Geometries.Point(coordinate1);
point1.SRID= 4326;
NetTopologySuite.Geometries.Coordinate coordinate2 = new NetTopologySuite.Geometries.Coordinate(12.50, 51.25);
NetTopologySuite.Geometries.Point point2 = new NetTopologySuite.Geometries.Point(coordinate2);
point2.SRID = 4326;
Console.WriteLine(point1.Distance(point2));
最后,写了新课程并通过半正弦公式计算了地理距离
public static class Distance
{
/// <summary>
/// Distance on a sphere: The Haversine Formula
/// </summary>
/// <returns>distance in meters</returns>
public static double Haversine(Coordinate coordinateFirstPoint, Coordinate coordinateSecondPoint)
{
// Coordinate (longitude, latitude)
double earthRadius = 6371008.7714;
double temp = Math.Acos(Math.Sin(Math.PI * coordinateFirstPoint.Y / 180) * Math.Sin(Math.PI * coordinateSecondPoint.Y / 180) +
Math.Cos(Math.PI * coordinateFirstPoint.Y / 180) * Math.Cos(Math.PI * coordinateSecondPoint.Y / 180) * Math.Cos(Math.PI * coordinateFirstPoint.X / 180 - Math.PI * coordinateSecondPoint.X / 180));
return temp*earthRadius;
}
}