Ashfaq Ahmed Ashfaq Ahmed - 8 days ago 9
C# Question

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

Answer

Here is Solution

var constValue = 57.2957795130823D

var constValue2 = 3958.75586574D;

var searchWithin = 20;

double latitude = ConversionHelper.SafeConvertToDoubleCultureInd(Latitude, 0),
                    longitude = ConversionHelper.SafeConvertToDoubleCultureInd(Longitude, 0);
var loc = (from l in DB.locations
let temp = Math.Sin(Convert.ToDouble(l.Latitude) / constValue) *  Math.Sin(Convert.ToDouble(latitude) / constValue) +
                                 Math.Cos(Convert.ToDouble(l.Latitude) / constValue) *
                                 Math.Cos(Convert.ToDouble(latitude) / constValue) *
                                 Math.Cos((Convert.ToDouble(longitude) / constValue) - (Convert.ToDouble(l.Longitude) / constValue))
                             let calMiles = (constValue2 * Math.Acos(temp > 1 ? 1 : (temp < -1 ? -1 : temp)))
                             where (l.Latitude > 0 && l.Longitude > 0)
                             orderby calMiles

select new location
  {
     Name = l.name
  });
  return loc .ToList();
Comments