views:

348

answers:

2

I have a database table of zipcodes with their Lat/Longs. I'm trying to find some code that shows a query that takes a zipcode and x miles and then return set of results that include all the zipcodes that are within that radius (precision is not very important - as long as it's close).

Can this be done with a Linq to SQL query so I don't have to use a Stored Proc?

A: 

I would do this in a SProc.

Daniel A. White
A: 

I figured it out and it actually wasn't all that hard once i found the equation.

Public Function SearchStudents(ByVal SearchZip As String, ByVal Miles As Double) As IEnumerable(Of Student)
                Dim dc As New IMDataContext()

                Dim lat As Double
                Dim lng As Double
                Dim maxlat As Double
                Dim minlat As Double
                Dim maxlng As Double
                Dim minlng As Double

                Dim zip As ZipCode = (From z In dc.ZipCodes Where z.ZipCode = SearchZip).SingleOrDefault()

                lat = zip.Latitude
                lng = zip.Longitude

                maxlat = lat + Miles / 69.17
                minlat = lat - (maxlat - lat)
                maxlng = lng + Miles / (Math.Cos(minlat * Math.PI / 180) * 69.17)
                minlng = lng - (maxlng - lng)

                Dim ziplist = From z In dc.ZipCodes Where z.Latitude >= minlat _
                       And z.Latitude <= maxlat _
                       And z.Longitude >= minlng _
                       And z.Longitude <= maxlng Select z.ZipCode

                Return From i In dc.Students Where ziplist.Contains(i.Zip)
            End Function
EdenMachine
That checks if it is within a square, not a radius. You need to compare the distance between lat/long pairs to get a radius...
KristoferA - Huagati.com
@KristoferA - I personally didn't really care as long as it was pretty close but if you have a better formula that fits this function, I certainly wouldn't mind the increased accuracy.
EdenMachine