如何从SQL Server 2008地理线获取Latitude Longitude?

时间:2012-04-30 21:17:17

标签: sql sql-server sql-server-2008 mapping

我是地图世界的新手,我正在尝试将SQL Server地理线列转换回它的纬度\经度点以在地图上绘制。

这条线正如此设置

Set @GeoPoly = geography::STGeomFromText('LINESTRING('+@Polyline+')',4326)

任何人都知道如何做到这一点?提前致谢

3 个答案:

答案 0 :(得分:2)

我很幸运:

DECLARE @g geography;
SET @g = geography::STLineFromText(
   'LINESTRING(-122.360 47.656, -122.343 47.656 )'
    , 4326
); 
SELECT @g.STPointN(1).ToString(), @g.STPointN(2).ToString();

答案 1 :(得分:1)

你的LineString是否只包含一个连接两个点的直线段?如果是这样,您可以检索这些点的纬度和经度:

SELECT
  @GeoPoly.STStartPoint.Lat AS Start_Lat,
  @GeoPoly.STStartPoint.Long AS Start_Long,
  @GeoPoly.STEndPoint.Lat AS End_Lat,
  @GeoPoly.STEndPoint.Long AS End_Long;

如果您的LineString包含多个连接一系列点的线段,那么您可以使用ToString()方法检索已知文本表示​​,然后通过在逗号上拆分将结果字符串解析为坐标对:

SELECT @GeoPoly.ToString()

结果将采用以下格式:LINESTRING(Lon1 Lat1,Lon2,Lat2,....,Lonn,Latn)

答案 2 :(得分:0)

您可以通过组合STasText(),STRING_SPLIT(),CROSS APPLY和STRING_AGG()在查询中实现此目的。这是查询示例:

WITH Links AS (
    SELECT Id, REPLACE(REPLACE(PosList.STAsText(), 'LINESTRING (', ''), ')', '') as points_string
    FROM LinkSequenceProjections
    WHERE ImportFileId = 1
    AND Id < 5
)
, Points AS (
    SELECT Id, ltrim(value) as point_string, row_number() OVER (PARTITION BY Id ORDER By Id) as Nr
    FROM Links
    CROSS APPLY STRING_SPLIT(points_string, ',')
)
, Coords AS (
    SELECT Id, Nr, CAST(value AS [varchar](max)) AS coord
    FROM Points
    CROSS APPLY STRING_SPLIT(point_string, ' ')
)
, GroupedByNr AS (
    SELECT Id, Nr, MIN(coord) AS Lon, MAX(coord) AS Lat
    FROM Coords
    GROUP BY Id, Nr
)
, GroupedById AS (
    SELECT Id, 'LINSESTRING (' + STRING_AGG(Lon + ' ' + Lat, ', ') WITHIN GROUP (ORDER BY Nr) + ')' as wkt2
    FROM GroupedByNr
    GROUP BY Id
)
SELECT Id, geography::STGeomFromText(wkt2, 4326) AS PosList2
FROM GroupedById