Using Linq to Sql to find ZipCodes within Radius distance

拜拜、爱过 提交于 2019-12-06 08:04:49

问题


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 Procedure?


回答1:


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


来源:https://stackoverflow.com/questions/1647521/using-linq-to-sql-to-find-zipcodes-within-radius-distance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!