T-SQL: Finding the closest location of an object on a map grid

心已入冬 提交于 2019-12-10 10:34:16

问题


I have grid showing on a map. I know your location and the location of 2 objects on the map. Objects appear where grid lines cross. Consider the world flat and not round since the area on the map is only a short distance. I want to determine which object is closest to you without using trigonometry and multiplication for performance reasons. I'm not looking for accuracy as much as just getting a ballpark indication. I should be able to determine the shortest distance between the difference in latitude and longitude from my current location. My table, Locations, looks like this:

ID   Latitude   Longitude
1       50         70
2       30         40

If my location is Latitude = 40 and Longitude = 60, then the location with ID = 1 would be closer to me.

If my location is Latitude = 30 and Longitude = 60, probably both locations are about the same distance, so just pick one.

If my location is latitude = 30 and Longitude = 50, then the location with ID = 2 would be closer.


回答1:


I would just do a min of the sum of the differences. I tried it out,and it works pretty well.

SELECT MIN(ABS(s.Latitude - 47) + ABS(s.Longitude - -122)), s.ID FROM Sites as s Group By ID;



回答2:


You really need to use some trigonometry to get any kind of accuracy:

DECLARE @LocationTable TABLE(ID int, Latitude int, Longitude int)
INSERT INTO @LocationTable(ID, Latitude, Longitude)
VALUES
    (1,50,70),
    (2,30,40)

DECLARE
    @MyLatitude int = 90,
    @MyLongitude int = 40

WITH DistanceTable AS
(
    SELECT ID, Latitude, Longitude,
        SQRT(POWER(Latitude - @MyLatitude,2) + POWER(Longitude - @MyLongitude, 2)) AS Distance
    FROM @LocationTable
)
SELECT ODT.ID, ODT.Latitude, ODT.Longitude, ODT.Distance
FROM (SELECT ID, Latitude, Longitude, Distance, ROW_NUMBER() OVER(ORDER BY Distance) AS Position
    FROM DistanceTable) AS ODT
WHERE ODT.Position = 1;



回答3:


SELECT MIN(((s.Latitude - @lat)(s.Latitude - @lat)) + ((s.Longitude - @lon)(s.Longitude - @lon))), s.ID FROM Sites as s Group By ID;



来源:https://stackoverflow.com/questions/10382915/t-sql-finding-the-closest-location-of-an-object-on-a-map-grid

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