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

前端 未结 3 1544
甜味超标
甜味超标 2021-02-14 16:38

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

3条回答
  •  孤城傲影
    2021-02-14 17:13

    I post here my solution which I am using for now. But I choose GwynnBliedd answer because he solves my problem in question.

    I added DbGeography type to my class and I am using it instead of saving latitude and longitude in database.

    locationField = DbGeography.FromText(String.Format("POINT({0} {1})", orig.gps.lat.ToString().Replace(",", "."), orig.gps.lng.ToString().Replace(",", ".")));
    

    Then it's very easy to use linq:

    var coord = DbGeography.FromText(String.Format("POINT({0} {1})", latitude.ToString().Replace(",", "."), longitude.ToString().Replace(",", ".")));
                var nearest = (from h in db.hotels
                               where h.location != null
                               orderby h.location.Distance(coord)
                               select h).Take(limit);
                return nearest;
    

    For now this is working solution and it's good. For sometime I would be using this but as few users said here I'll maybe try UDF with implementing Haversine formula (like in this answer).

提交回复
热议问题