C# - LINQ - shortest distance by GPS latitude and longitude

c# entity-framework gps linq linq-to-entities

Question

I have database and in it I have class hotel with gps coordinates. I want to get closest places to coordinates which I choose.

I think It should look like this (I found many example codes here and like this one):

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);

The problem is that I have this error when I tried to search for something:

Only parameterless constructors and initializers are supported in LINQ to Entities

I tried to google it and I found that dividing that linq into two can help me but I am not sure how. Thanks for help.

1
8
1/18/2013 4:00:42 PM

Accepted Answer

You can use the object initializer instead of parameterized constructor:

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);

But you will likely have problems caused by the GetDistanceTo method, could you provide the implementation of that method?

6
1/18/2013 4:07:06 PM

Popular Answer

I have had a reasonable about of success using this implementation of the Haversine Distance formula

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);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow