I have some shapefile which I want to convert to GeoJSON and store in MongoDB for querying.
Is it possible to take a shapefile and convert it to GeoJSON format in C#? I have been able to convert shapefiles to GeoJSON from the drivers available online and then import the documents in MongoDB, but I wish to get this all done in C# only. Reason being the ability to let me do some changes to the document on the fly.
If there is no solution available as such, then pointing me in the right direction would be helpful.
Answer
I was working on something close to this morning (except my source is PostgreSQL) and I'm coming at it from the GDAL C# bindings. But I haven't worked it out yet. Most of the posts (not recent) mention implementing the ogr2ogr.cpp in .NET. But I'm hoping someone posts something more recent.
For testing, this would be what you would call from the command line (and this is what we both want from c#):ogr2ogr -f GeoJSON outshp.json c:\temp\us_counties_.shp
This gets the Geometry JSON, and you could probably build out the rest and get the full GeoJSON feature. But I don't know if there is something that already exists in the c# bindings.
[TestMethod()]
public void WriteGeoJSONTest3()
{
string shapeFilePath = @"c:\temp\us_counties_.shp";
OSGeo.OGR.Ogr.RegisterAll();
Driver drv = Ogr.GetDriverByName("ESRI Shapefile");
var ds = drv.Open(shapeFilePath, 0);
/*
Driver geoJSONDriver = Ogr.GetDriverByName("GeoJSON");
string geojsonfilepath = @"c:\temp\us_counties_test.json";
if (System.IO.File.Exists(geojsonfilepath))
System.IO.File.Delete(geojsonfilepath);
geoJSONDriver.CreateDataSource(@"c:\temp\us_counties_test.json", null);
*/
OSGeo.OGR.Layer layer = ds.GetLayerByIndex(0);
OSGeo.OGR.Feature f;
layer.ResetReading();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while ((f = layer.GetNextFeature()) != null)
{
var geom = f.GetGeometryRef();
if (geom != null)
{
var geometryJson = geom.ExportToJson();
sb.AppendLine(geometryJson);
}
}
Trace.WriteLine(sb.ToString());
Assert.IsNotNull(sb.Length > 0);
}
No comments:
Post a Comment