我从这个网站得到了这个问题的答案,但我得到的答案是错误的。
DECLARE @orig_lat DECIMAL
DECLARE @orig_lng DECIMAL
SET @orig_lat=52.676 set @orig_lng=-1.6193
DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);
SELECT @orig.STDistance(geography::Point(Latitude, longitude, 4326)) AS distance
From ...
但是我得到了错误的答案 例如距离234229北纬55.0853,经度-1.595
我必须承认我只是复制了代码并且不理解它。答案应该是166英里,即267公里。
有什么想法吗?
答案 0 :(得分:0)
答案是以米为单位,除以1000,你就有公里。
我试着把它分解给你:
-- I assume you already know that this part is only declaring variables
-- and setting them.
-- In this case they are the variables for your starting coordinates.
DECLARE @orig_lat DECIMAL
DECLARE @orig_lng DECIMAL
SET @orig_lat=52.676 set @orig_lng=-1.6193
-- MS SQL has built in geography functions
-- like a function to determine the distance between 2 points.
-- But it uses an own unit instead of longitude/latitude: point.
-- So you have to use the geography::Point-function to convert
-- a lat/lon coordinate into a point value:
DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);
-- The rest is basically the same again with the target coordinates,
-- namely this part: geography::Point(Latitude, longitude, 4326)
-- embedded in the STDistance function. This function calculates the distance
-- between 2 point values.
SELECT @orig.STDistance(geography::Point(Latitude, Longitude, 4326)) AS distance
From ...
-- where Latitude and Longitude would be your destination coordinates.
如果你想要你可以写自己的陈述,那么这个数学背景就是基本上测量球体上2个点之间距离的Haversine公式。
答案 1 :(得分:0)
简答:
制作@orig_lat
类型@orig_lng
和decimal(19,6)
(例如)或float
。
答案很长:
问题是因为你的decimals
没有实际小数(你使用的是默认精度,decimal(18,0)
),所以它们最终是53和-2。您应该定义它们的精度(例如decimal(19,6)
)或仅使用float
,这是函数期望的类型。如果您只是更改它,它可以正常工作:
DECLARE @orig_lat float
DECLARE @orig_lng float
SET @orig_lat=52.676 set @orig_lng=-1.6193
DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);
DECLARE @dest geography = geography::Point(55.0853, -1.595, 4326);
select @orig.STDistance(@dest)
返回268166.415685712
。
我通过简单地打印varchar
的等效geography
来发现这一点:
DECLARE @orig_lat decimal
DECLARE @orig_lng decimal
SET @orig_lat=52.676 set @orig_lng=-1.6193
DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326);
select cast(@orig as varchar)
这将打印POINT (-2 53)
,除了舍入外,它还为您提供了另一条信息:varchar格式使用经度 - 纬度而不是纬度 - 经度。因此,如果您想以另一种方式创建这些点,则应使用:
DECLARE @orig geography = 'POINT(-1.6193 52.676)'
DECLARE @dest geography = 'POINT(-1.595 55.0853)'
SELECT @orig.STDistance(@dest)
答案 2 :(得分:-1)
更简单的方法是:
DECLARE @source geography = 'POINT(52.676 -1.6193)'
DECLARE @target geography = 'POINT(55.0853 -1.595)'
SELECT @source.STDistance(@target)