Find nearest object query with LINQ
While LINQ simplifies your DAL in myriad ways, this seemingly simple query made me stop and think about how to properly explain this to the query engine
Problem: Given an input of a current location (latitude and longitude) find all objects in the database within a specified radius
Disclaimer: This is using a bounding box hack rather than an accurate radius forumula, use at your own risk as there is some loss of precision.
/// Find all courts within a specified radius (in miles) to a point (latitude & longitude)
/// <param name="latitude">degrees(decimal)</param>
/// <param name="longitude">degrees(decimal)</param>
/// <param name="radius">miles</param>
/// <returns></returns>
public IQueryable<Court> FindNearbyCourts(decimal latitude, decimal longitude, decimal radius);
The first order of business is to convert miles to degrees of latitude and longitude, respectively.
| Latitude: | Factor out Equatorial bulge, and a degree of latitude is simply 69.04 statute miles. |
| Longitude: | On the other hand, longitude varies in length depending on your current latitude. For this example, I am assuming 30°N. Thus, one degree of longitude is 59.96 statute miles. |
decimal radiusLatitude = radius / 69.04;
decimal radiusLongitude = radius / 59.96;
Once we have these conversions in place, we are ready to build our LINQ query:
IQueryable<Court> nearbyCourts = from court in _db.Courts
where (Math.Abs(court.latitude - latitude) < radiusLatitude)
where (Math.Abs(court.longitude - longitude) < radiusLongitude)
select court;
Return the IQueryable object nearbyCourts you just generated and you're all set.