开发者

Using Linq to Sql to find ZipCodes within Radius distance

开发者 https://www.devze.com 2022-12-10 00:13 出处:网络
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

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 开发者_StackOverflow社区don't have to use a Stored Procedure?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号