Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 306
Libor Zapletal Avatar asked Jan 18 '13 16:01

Libor Zapletal


1 Answers

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?

like image 166
TKharaishvili Avatar answered Oct 14 '22 07:10

TKharaishvili