sql-serverkmlsqlgeography

Export SQL Server geography to kml with altitude


I need to export a bunch of geography objects to kml, and with that include a 3rd element, altitude. Luckily it can be hard coded as 0.

This tutorial implies the coordinates need to be in the format of lat,long,alt

<coordinates>
    -77.05788457660967,38.87253259892824,100 
    -77.05465973756702,38.87291016281703,100 
    -77.05315536854791,38.87053267794386,100 
    -77.05552622493516,38.868757801256,100 
    -77.05844056290393,38.86996206506943,100 
    -77.05788457660967,38.87253259892824,100
</coordinates>

How do I extract the coordinate list from my geography objects?

Is it possible to include injecting the altitude?


Solution

  • The part I was really looking for was .Lat and .Long. They only work on POINT's, not POLYGON's, so you have to break that down the @input into points

    This returns a varchar(MAX) string like long,lat,altcr/lf

    CREATE FUNCTION [dbo].[uf_ConvertGeographyToCoordinates]
    (
        @input geography
    )
    RETURNS nvarchar(MAX)
    AS
    BEGIN
        -- Declare the return variable here
        DECLARE @result nvarchar(max) = '' -- Out needs to be not null
        DECLARE @long nvarchar(25)
        DECLARE @lat nvarchar(25)
        DECLARE @alt nvarchar(25)
        DECLARE @altitude nvarchar(1) = '0'
        DECLARE @i int = 1 
        DECLARE @crlf nvarchar(2) = char(13) + char(10)
    
    
        WHILE @i <@input.STNumPoints() 
        BEGIN 
    
            SET @long = ISNULL(LTRIM(STR(@input.STPointN(@i).Long, 25, 8)), 'null_long') 
        
            SET @lat = ISNULL(LTRIM(STR(@input.STPointN(@i).Lat, 25, 8)), 'null_lat') 
        
            SET @alt = ISNULL(@altitude, 'null_alt')
    
            SET @result = @result + @long + ',' + @lat + ',' + @alt + @crlf
    
            SET @i = @i + 1; 
        END 
    
        return @result
    END
    GO