如何计算TSQL中沿线两点的距离

时间:2015-11-29 06:57:41

标签: sql-server distance geography

我在MSSQL数据库中添加了一行代表map.As,

中的路由
update route
  set locationArray=geography::STGeomFromText('LINESTRING(7.068419558716859 80.140939950943,7.070868430303301 80.14106869697571,7.072976578922316 80.14136910438538,7.074339417352194 80.14203429222107,7.07631978477513 80.14278531074524,7.078491790888004 80.14435172080994,7.078300143701023 80.14649748802185,7.078449202631107 80.14877200126648,7.076617903866453 80.15068173408508,7.074978246481405 80.15248417854309,7.074105179783337 80.15490889549255,7.0723803358444135 80.15643239021301)', 4326)
  where routeID=45;

现在我在线上选择了两个点,我用它来计算沿线的两条线之间的距离(不是直接距离或位移),类似于图像。 enter image description here

我尝试了两种STLength()函数和STDistance()函数。但他们两人都提供直接距离。有人可以帮我用TSQL来计算沿线的距离吗?

1 个答案:

答案 0 :(得分:2)

STLength (geometry Data Type)

  

返回几何实例中元素的总长度。

STLength (geography Data Type)

  

返回地理位置实例中元素的总长度   GeometryCollection中的地理实例。

我在Excel中计算了每个段SQRT(X*X + Y*Y)的简单长度之和,并将其与SQL Server进行了比较。 Excel为STLength类型提供了与geometry相同的结果。 STLength 计算从起点到终点的距离,它会计算每个段的长度,然后按预期将它们相加。

DECLARE @G1 geometry  = geometry::STGeomFromText ('LINESTRING(7.068419558716859 80.140939950943,7.070868430303301 80.14106869697571,7.072976578922316 80.14136910438538,7.074339417352194 80.14203429222107,7.07631978477513 80.14278531074524,7.078491790888004 80.14435172080994,7.078300143701023 80.14649748802185,7.078449202631107 80.14877200126648,7.076617903866453 80.15068173408508,7.074978246481405 80.15248417854309,7.074105179783337 80.15490889549255,7.0723803358444135 80.15643239021301)', 4326);
DECLARE @G2 geography = geography::STGeomFromText('LINESTRING(7.068419558716859 80.140939950943,7.070868430303301 80.14106869697571,7.072976578922316 80.14136910438538,7.074339417352194 80.14203429222107,7.07631978477513 80.14278531074524,7.078491790888004 80.14435172080994,7.078300143701023 80.14649748802185,7.078449202631107 80.14877200126648,7.076617903866453 80.15068173408508,7.074978246481405 80.15248417854309,7.074105179783337 80.15490889549255,7.0723803358444135 80.15643239021301)', 4326);

SELECT @G1.STLength() AS LGeometry, @G2.STLength() AS LGeography;

<强>结果

LGeometry             LGeography
0.0252888043080671    1809.85271737151

因此,STLength正常工作,请检查您的代码。检查您使用的是正确的类型(geometry vs geography)。