Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

c# - Find closest location with longitude and latitude

I am working on a application where I need to get nearby location, my web service will receive 2 parameters (decimal longitude, decimal latitude )

I have a table where the locations are saved in database with longitude and latitude fields,

I want to retrieve the nearest locations.

Can anyone help?

Here is my code:

 var locations = from l in locations

     select l

Here are further details about this : i have a 2 fields (decimal(18, 2) null) 1 latitude, 2 longitude inside a database table,

and i have a method

public List<Locations>  GetLocation(decimal? Long, decimal? lat) 
{
var Loc = from l in Locations
  //// now here is how to get nearest location ? how to query?
  //// i have also tried Math.Abs(l.Lat - lat) its giving error about nullable decimal always hence i have seted decimal to nullable or converted to nullable
 //// also i have tried where (l.lat - Lat) * (l.lon - Long)  this is also giving error about can not convert decimal to bool
return Loc.ToList();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...