[GIS] Convert Sql Server Spatial data to GeoJSON & plot on map

cgeojsonjsonsql server

I have a sql server table with Geo spatial data. An example of row would be (with Column names):

type: streetline
code: 231001
geog: 0xE6100000011 ........
Centroid 0xE61000000C.......
geom: 0xE6100000011 ........

I am using C# with MVC3 to draw the above shapes on leaflet map. I am fetching the above sql data into a datatable. Using the sql function "ToString()" on column "geom" I get the following:

"LINESTRING (-1.131510412 52.65531, -1.13286 52.65559)",
"POLYGON ((-1.1116360 52.6409953, -1.1116683 52.6413, -1.11146723 52.641317, -1.11133263 52.6413572, -1.1113059))",

The question is how do I convert the above to GeoJSON to be able to plot on the leaflet map. Here is an example of the expected output (GeoJSON) I want:

var geojsonFeature = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
};

Best Answer

ogr2ogr should do this for you. Looks like you have multiple geometry types in the dataset, not sure how that will work out. You might have to filter out by geometry type. Below not tested. See docs linked to above for inputs and flags.

ogr2ogr -f "GeoJSON" "sqlexport.geojson"
"MSSQL:server=localhost\sqlexpress;database=tempdb;trusted_connection=yes;"
-sql "SELECT * FROM tbl"