ef表达式获取距离内的位置

gmxoilav  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(408)

我正在尝试查询我的数据库以查找某个位置内的所有事件。我想能够通过数据库查询,这样我就不必拉所有的事件,所以我试图转换成一个表达式一些代码。原始代码在此处找到:

  1. public static Expression<Func<Location, bool>> GetWithinDistanceExpression(this Location current, double withinDistance, DistanceUnits units)
  2. {
  3. //in the EQ converts something to meters
  4. double toMeters = 6376500;
  5. double toRadiants = 0.0174532925199433;
  6. double currentLat = current.Latitude * toRadiants;
  7. double currentLong = current.Longitude * toRadiants;
  8. return loc =>
  9. (2 * Math.Atan2(
  10. Math.Sqrt(
  11. //TODO: Merge Expressions instead of copy pasta.
  12. Math.Pow(Math.Sin((loc.Latitude - currentLat) / 2), 2) + Math.Cos(currentLat) * Math.Cos(loc.Latitude * toRadiants)
  13. * Math.Pow(Math.Sin((loc.Longitude - currentLong) / 2), 2)
  14. ),
  15. Math.Sqrt(1 -
  16. //TODO: Merge Expressions instead of copy pasta.
  17. Math.Pow(Math.Sin((loc.Latitude - currentLat) / 2), 2) + Math.Cos(currentLat)
  18. * Math.Cos(loc.Latitude * toRadiants) * Math.Pow(Math.Sin((loc.Longitude - currentLong) / 2), 2)
  19. )
  20. )
  21. )
  22. * toMeters
  23. < withinDistance;
  24. }

但是,当我在db中查询location中的东西时,这不会返回任何结果。我猜这和铸造时的精密度有关。
如何在2个坐标的特定距离内获取位置?

ngynwnxp

ngynwnxp1#

  1. public static IQueryable<Location> GetLocationsWithinMeter(this DbSet<Location> locations, double lat, double longitude, double withinMeters)
  2. {
  3. //Use Interpolated to create parameterized Query
  4. return locations.FromSqlInterpolated(
  5. @$"
  6. SELECT * FROM(
  7. SELECT l.*, (
  8. 6371392.896 * acos (
  9. cos ( radians({lat}) )
  10. * cos( radians( l.[Latitude] ) )
  11. * cos( radians( l.[Longitude] ) - radians({longitude}) )
  12. + sin ( radians({lat}) )
  13. * sin( radians( [Latitude] ) )
  14. )
  15. ) AS distance
  16. FROM Locations l) locInfo
  17. WHERE distance < {withinMeters}"
  18. );
  19. }
展开查看全部

相关问题