Skip to content

Instantly share code, notes, and snippets.

@matt40k
Created November 29, 2015 20:57
Show Gist options
  • Save matt40k/57fcd897d654c545bc95 to your computer and use it in GitHub Desktop.
Save matt40k/57fcd897d654c545bc95 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
@lovelyAphorist
Copy link

lovelyAphorist commented Mar 24, 2022

Thank you! Found this very useful today. Though it seems to not be working due to the conversion not following the right hand rule just FYI. I'll send it to you if I figure out a fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment