Finding a geography point within a range of another - SQL Server

百般思念 提交于 2019-11-30 07:37:29

Assuming you have lat and long values of the points in the db.

select * from yourtable where SQRT 
( POWER((yourtable.lat - reflat) * COS(reflat/180) * 40000 / 360, 2) 
+ POWER((yourtable.long - reflong) * 40000 / 360, 2)) < radiusofinterest

reflat and reflong is the point from which you want to know the places close to. radiusofinterest is the distance from this point. 40000 is the circumference of the earth. you could use more accurate figures.

i havent checked the syntax with SQLServer though.... so there may be some errors there.

the cos(reflat) corrects the circumference based on the lat you are in. It should work ok for smaller distances.

You are already using SQL Server Spatial and geography columns, so you can just use the following to get the result. There are two ways:

Using STDistance():

-- Get the center point
DECLARE @g geography
SELECT @g = geo FROM yourTable WHERE PointId = something

-- Get the results, radius 100m
SELECT * FROM yourTable WHERE @g.STDistance(geo) <= 100

Using STBuffer() and STIntersects

-- Get the center buffer, 100m radius
DECLARE @g geography
SELECT @g = geo.STBuffer(100) FROM yourTable WHERE PointId = something

-- Get the results within the buffer
SELECT * FROM yourTable WHERE @g.STIntersects(geo) = 1

From my experience the performance of two methods varies with data distribution and spatial index grid size, so test on your own data to decide which one to use. Remember to have Spatial Index created on the geo column.

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