Created
April 25, 2014 09:52
-
-
Save sir4ju1/11284065 to your computer and use it in GitHub Desktop.
Find Closest Location from longitude and latitude within Sql database using Linq
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
How to reference ConversionHelper?
Also how to get just first record back with the nearest location?
@apixu I have never used this code myself, was just collecting references how to calculate distance in various solutions. Later I resolved to use storedprocedure in MS SQL. In other database like MongoDB they have built in Geo function. But if you are using this code, I think you can avoid using ConversionHelper
if you have Latitude already in double type but if it is string
you can use Double.TryParse
method.
To get first value in Linq you can use .First()
method.
what constValue? why u need that?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My code ;)
https://stackoverflow.com/questions/12835851/find-closest-location-with-longitude-and-latitude/12860259?noredirect=1#comment80313131_12860259
(y)