Making query to find nearest multiple(Lat,Long) from the single(Lat,Long)

北战南征 提交于 2019-12-06 16:36:28

You can use SQL Server's geography functions for this.

DECLARE @InputLatitude FLOAT = 1.64
DECLARE @InputLongitude FLOAT = 4.25

DECLARE @GPS GEOGRAPHY = GEOGRAPHY::Point(@InputLatitude, @InputLongitude, 4326)

SELECT TOP 1
    P.*,
    Distance = @GPS.STDistance(GEOGRAPHY::Point(P.Lat, P.Long, 4326))
FROM
    dbo.Place AS P
ORDER BY
    @GPS.STDistance(GEOGRAPHY::Point(P.Lat, P.Long, 4326)) ASC

You should consider adding a GEOGRAPHY column on your table with the GPS points already converted and adding a SPATIAL INDEX to speed up queries.

Besides the recommended geography types, you can also achieve the similar result using regular data types like float.

DECLARE @latitude FLOAT = 4.5678; -- Latitude of the place to search around
DECLARE @longitude FLOAT = 51.234; -- Longitude of the place to search around
DECLARE @range FLOAT = 100000; -- Max range in meters

SELECT TOP(1000)
    [place].[Lat],
    [place].[Long],
    ((((ACOS((SIN((PI() * [place].[Lat]) / 180.0) * SIN((PI() * @latitude) / 180.0)) + ((COS((PI() * [place].[Lat]) / 180.0) * COS((PI() * @latitude) / 180.0)) * COS((PI() * ([place].[Long] - @longitude)) / 180.0))) * 180.0) * 60.0) * 1.1515) * 1609.344) / PI() AS [Distance]
FROM [dbo].[Place] AS [place]
WHERE (((((ACOS((SIN((PI() * [place].[Lat]) / 180.0) * SIN((PI() * @latitude) / 180.0)) + ((COS((PI() * [place].[Lat]) / 180.0) * COS((PI() * @latitude) / 180.0)) * COS((PI() * ([place].[Long] - @longitude)) / 180.0))) * 180.0) * 60.0) * 1.1515) * 1609.344) / PI()) <= @range
ORDER BY [Distance]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!