Reputation: 4484
I'm new to the mapping world and I'm trying to convert a SQL Server geography line column back into it's latitude \ longitude points to draw on a map.
The line is being set like this
Set @GeoPoly = geography::STGeomFromText('LINESTRING('+@Polyline+')',4326)
Anyone know how to do this? Thanks in advance
Upvotes: 2
Views: 8040
Reputation: 386
You can achieve this in a query by combining STasText(), STRING_SPLIT(), CROSS APPLY and STRING_AGG(). Here is an example query:
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
Upvotes: 0
Reputation: 3532
Does your LineString consist of only one straight line segment connecting two points? If so, you can retrieve the latitude and longitude of those points as:
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;
If your LineString consists of multiple line segments connecting a series of points then you can retrieve the Well-Known Text representation using the ToString() method, and then parse the resulting string into coordinate pairs by splitting on commas:
SELECT @GeoPoly.ToString()
The result will be in the format: LINESTRING(Lon1 Lat1, Lon2, Lat2, .... , Lonn, Latn)
Upvotes: 1
Reputation: 32697
I had luck with this:
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();
Upvotes: 2