C# - LINQ - 通过GPS经纬度最短距离(C# - LINQ - shortest di

2019-08-07 07:55发布

我有数据库,并在其中我有一流的酒店,拥有GPS坐标。 我想最近的地方,这是我选择的坐标。

我想应该是这样的(我发现很多例子的代码这里像这样的):

var coord = new GeoCoordinate(latitude, longitude);
var nearest = (from h in db.hotels
               let geo = new GeoCoordinate(h.gps.lat, h.gps.lng)
               orderby geo.GetDistanceTo(coord)
               select h).Take(10);

问题是,我有这样的错误,当我试图寻找的东西:

只有参数构造函数初始化和LINQ中支持到实体

我试图谷歌,而且我发现,除以LINQ分成两个能帮助我,但我不知道怎么样。 感谢帮助。

Answer 1:

您可以使用对象初始化,而不是参数的构造函数:

var nearest = (from h in db.hotels
           let geo = new GeoCoordinate{ Latitude = h.gps.lat, Longitude = h.gps.lng}
           orderby geo.GetDistanceTo(coord)
           select h).Take(10);

但是,你将有可能造成GetDistanceTo方法的问题,你能提供该方法的实现?



Answer 2:

我有一个合理的有关使用此实施成功的半正矢距离公式

var startPoint = new { Latitude = 1.123, Longitude = 12.3 };

var closest = entities.Something.OrderBy(x => 12742 * SqlFunctions.Asin(SqlFunctions.SquareRoot(SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (x.Latitude - startPoint.Latitude)) / 2) * SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (x.Latitude - startPoint.Latitude)) / 2) +
                                    SqlFunctions.Cos((SqlFunctions.Pi() / 180) * startPoint.Latitude) * SqlFunctions.Cos((SqlFunctions.Pi() / 180) * (x.Latitude)) *
                                    SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (x.Longitude - startPoint.Longitude)) / 2) * SqlFunctions.Sin(((SqlFunctions.Pi() / 180) * (x.Longitude - startPoint.Longitude)) / 2)))).Take(5);


Answer 3:

我在这里发布我的解决方案,我使用的现在。 但我选择GwynnBliedd的答案,因为他解决了问题,我的问题。

我加DbGeography类型上我的课,我使用它,而不是保存在数据库中的经度和纬度。

locationField = DbGeography.FromText(String.Format("POINT({0} {1})", orig.gps.lat.ToString().Replace(",", "."), orig.gps.lng.ToString().Replace(",", ".")));

然后,它非常容易使用LINQ:

var coord = DbGeography.FromText(String.Format("POINT({0} {1})", latitude.ToString().Replace(",", "."), longitude.ToString().Replace(",", ".")));
            var nearest = (from h in db.hotels
                           where h.location != null
                           orderby h.location.Distance(coord)
                           select h).Take(limit);
            return nearest;

现在这个工作解决方案,这是很好的。 对于有时我会使用这一点,但尽可能少的用户在这里说,我也许尝试使用UDF(像实施haversine公式这个答案 )。



文章来源: C# - LINQ - shortest distance by GPS latitude and longitude