Find closest location with longitude and latitude

To elaborate on the comment by @Fung, if you are using Entity Framework / LINQ to Entities, if you try to use the GeoCoordinate.GetDistanceTo method in a LINQ query, you'll get a runtime NotSupportedException with the message:

LINQ to Entities does not recognize the method 'Double GetDistanceTo(System.Device.Location.GeoCoordinate)' method, and this method cannot be translated into a store expression.

With Entity Framework version 5 or 6, an alternative is to use the System.Data.Spatial.DbGeography class. For example:

DbGeography searchLocation = DbGeography.FromText(String.Format("POINT({0} {1})", longitude, latitude));

var nearbyLocations = 
    (from location in _context.Locations
     where  // (Additional filtering criteria here...)
     select new 
     {
         LocationID = location.ID,
         Address1 = location.Address1,
         City = location.City,
         State = location.State,
         Zip = location.Zip,
         Latitude = location.Latitude,
         Longitude = location.Longitude,
         Distance = searchLocation.Distance(
             DbGeography.FromText("POINT(" + location.Longitude + " " + location.Latitude + ")"))
     })
    .OrderBy(location => location.Distance)
    .ToList();

_context in this example is your previously-instantiated DbContext instance.

Although it's currently undocumented in MSDN, the units returned by the DbGeography.Distance method appear to be meters. See: System.Data.Spatial DbGeography.Distance units?


You could first convert the location data in database to System.Device.Location.GeoCoordinate, then use LINQ to find the nearest one.

var coord = new GeoCoordinate(latitude, longitude);
var nearest = locations.Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
                       .OrderBy(x => x.GetDistanceTo(coord))
                       .First();

Tags:

C#

Linq