Skip to content

Instantly share code, notes, and snippets.

@hsavran
Forked from matt40k/GetGeoJSON.sql
Created September 9, 2017 18:38
Show Gist options
  • Save hsavran/585c585bc5e96e8bc29cd8d0f5fba1e5 to your computer and use it in GitHub Desktop.
Save hsavran/585c585bc5e96e8bc29cd8d0f5fba1e5 to your computer and use it in GitHub Desktop.
Turns SQL Server Geography to GeoJSON
CREATE FUNCTION GetGeoJSON (@geo geography)
RETURNS varchar(max)
WITH SCHEMABINDING
/*
* Reference: http://stackoverflow.com/questions/6506720/reformat-sqlgeography-polygons-to-json
*/
AS
BEGIN
DECLARE @Result varchar(max)
SELECT @Result = '{' +
CASE @geo.STGeometryType()
WHEN 'POINT' THEN
'"type": "Point","coordinates":' +
REPLACE(REPLACE(REPLACE(REPLACE(@geo.ToString(),'POINT ',''),'(','['),')',']'),' ',',')
WHEN 'POLYGON' THEN
'"type": "Polygon","coordinates":' +
'[' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@geo.ToString(),'POLYGON ',''),'(','['),')',']'),'], ',']],['),', ','],['),' ',',') + ']'
WHEN 'MULTIPOLYGON' THEN
'"type": "MultiPolygon","coordinates":' +
'[' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@geo.ToString(),'MULTIPOLYGON ',''),'(','['),')',']'),'], ',']],['),', ','],['),' ',',') + ']'
ELSE NULL
END
+'}'
RETURN @Result
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment