简体   繁体   English

.NET等效的SQL Server STDistance

[英].NET Equivalent of SQL Server STDistance

I can use the following SQL to calculate the distance between a fixed location and the location against the venues in the database. 我可以使用以下SQL来计算固定位置与数据库中场地的位置之间的距离。

SELECT Location.STDistance(geography::Point(51, -2, 4326)) * 0.00062137119 FROM Venues

Please note the distance returned is in miles and the Location field is a geography type. 请注意,返回的距离以英里为单位,位置字段是地理类型。

I was wondering what is the equivalent of this in .NET which would return the same values. 我想知道在.NET中它的等价物会返回相同的值。 This method would have the following signature: 此方法将具有以下签名:

public static double Distance(location1Latitude, location1Longitude, location2Latitude, location2Longitude) {
    return ...;
}

I know I could call the database method in .NET but I don't wish to do this. 我知道我可以在.NET中调用数据库方法,但我不希望这样做。 I'm hoping there is a formula to calculate the distance. 我希望有一个计算距离的公式。 Thanks 谢谢

我相信您可以简单地添加Microsoft.SqlServer.Types.dll作为引用,然后像任何其他.NET类型一样使用SqlGeometry类型,包括调用STDistance方法。

You would need to compute the Geographical distance to compute the distance manually. 您需要计算地理距离以手动计算距离。 There are many different techniques and formulas to do this , each with different underlying assumptions (ie: a spherical earth, ellipsoidal earth, etc). 许多不同的技术和公式可以做到这一点 ,每个都有不同的基本假设(即:球形地球,椭圆形地球等)。

A common option is the haversine formula, with a C# implementation available here . 常见的选项是hasrsine公式, 此处提供C#实现

this is very well explained here . 这里有很好的解释 Shortly: with EF5 (to be more specific, with .net 4.5) Microsoft included the type DbGeography . 简而言之:使用EF5(更具体地说,使用.net 4.5)微软包括DbGeography类型。 Let say you already have a bunch of lat/long, you can then create a DbGeography object easily using an helper like: 假设你已经有一堆lat / long,你可以使用一个帮助器轻松创建一个DbGeography对象:

public static DbGeography CreatePoint(double latitude, double longitude)
{
    var text = string.Format(CultureInfo.InvariantCulture.NumberFormat,
                             "POINT({0} {1})", longitude, latitude);
    // 4326 is most common coordinate system used by GPS/Maps
    return DbGeography.PointFromText(text, 4326);
}

Once you got a two or more points (DbGeography) you got everything to calculate the Distance between them: 一旦你得到两个或更多点(DbGeography),你就可以得到一切来计算它们之间的距离

var distance = point1.Distance(point2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM