James Trotter James Trotter - 1 year ago 127
C# Question

Is there any way to parse Microsoft.SqlServer.Types.SqlGeometry to SVG?

I have a Table in my database where on of the columns is of type "geometry".
I want to take the data contained in this column (polygons and circles) and convert them into something easily parse-able and rendered in HTML (preferably as SVG), but i cannot seem to be able to do it.

I have been able to extract GML and WKT from the database, but neither of these seem to get me closer to my goal without additional parsing on the front-end that will be prone to error. Are there any built-ins or third party librarys that are capable of doing this? Is there a simple conversion I can make that I am overlooking? I am at a loss to why this cant be done, as i would have thought this would be a useful tool others would need.

Answer Source

It is relatively easy to convert to GeoJson from GEOMETRY and GEOGRAPHY SQL types.

From there it is easier to convert to SVG.

Edit:

NPM package for GeoJson to SVG converter

GitHub repo for another GeoJson to SVG converter

SQL: Returning Spatial Data in GeoJson Format (part 1)

SQL: Returning Spatial Data in GeoJson Format (part 1)

And the relevant SQL function from the second tutorial:

CREATE FUNCTION dbo.geometry2json ( @geo GEOMETRY )
RETURNS NVARCHAR(MAX)
AS
    BEGIN
        RETURN (
     '{' +
     (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 ',''),'(','['),')',']'),'], ',']],['),', ','],['),' ',',') + ']'
     WHEN 'MULTIPOINT' THEN
     '"type": "MultiPoint","coordinates":' +
     '[' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@geo.ToString(),'MULTIPOINT ',''),'(','['),')',']'),'], ',']],['),', ','],['),' ',',') + ']'
     WHEN 'LINESTRING' THEN
     '"type": "LineString","coordinates":' +
     '[' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@geo.ToString(),'LINESTRING ',''),'(','['),')',']'),'], ',']],['),', ','],['),' ',',') + ']'
     ELSE NULL
     END)
     +'}');
    END;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download