Where would you like to go, Toady? RSS 2.0
# Sunday, July 26, 2009

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.

Sunday, July 26, 2009 11:34:18 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] -
Bookmark, Tweet, or Share
Stackoverflow.com Rep
Flickr stream
Archive
<July 2009>
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Chris Ballance
Sign In
Statistics
Total Posts: 46
This Year: 11
This Month: 2
This Week: 0
Comments: 11
All Content © 2010, Chris Ballance

Valid XHTML 1.0 Transitional