2

A C# web application I'm working on needs to be able to load GeoJSON data and save it as an ESRI shapefile (either for download or to view in the browser). The GeoJSON is stored in a database and retrieved as a string.

The GDAL/OGR site says that the OGR GeoJSON driver accepts data as "text passed directly and encoded in GeoJSON" but doesn't say how to do so and there are no code samples that show how to use it.

How can I load the GeoJSON data from a string into a DataSource (or DataSet) using the GDAL/OGR API so I can export as a shapefile?

Note: I've searched GIS.SE and while GDAL OGR API GeoJSON from other datasource as string NOT file sounds like the same issue it is in fact the reverse, the OP wants to serialize the shapefile's data as GeoJSON.

  • Could you just export from GeoJSON directly to shapefile? ogr2ogr -f "ESRI Shapefile" destination_data.shp "source-data.json" – Makosak Jan 13 '17 at 19:56
  • @Makosak I could save the GeoJSON from the database into a temp file and do it that way, but I'd rather do it all in my C# web app rather than calling external applications if possible. – Dan Price Jan 18 '17 at 9:28
1

You pass the geojson string directly to the gdal OpenEx function.

In python it's just:

# GDAL 2+
ds = gdal.OpenEx('some geojson string')


# GDAL 1.11
ds = ogr.Open('some geojson string')

An example to demonstrate:

from osgeo import gdal

geojson = '{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[146.7,-41.9]}}]}'
ds = gdal.OpenEx(geojson)
layer = ds.GetLayer()
feature = layer.GetFeature(0)

print(ds.GetDriver().ShortName)
print(feature.GetGeometryRef().ExportToWkt())

Output:

GeoJSON
POINT (146.7 -41.9)
  • I never realised it'd be that simple, since the docs always refer to it as the path. Related note, if I use Ogr.Open, the DataSource's name property is set to the entire text of the GeoJSON string - is there some driver option I'm missing? – Dan Price Jan 18 '17 at 9:26
  • ogr seems to work fine, gdal.OpenEx does not (at least not in the Java bindings, does it really work in C#?) – estani Jul 31 '18 at 14:58
  • @Luke what I meant is that at least in Java gdal.OpenEx does not work with strings. Have you tested it in PYthon then? Because it's very strange that different languages do different thinks, at the end is the same library that handles it all. – estani Aug 9 '18 at 12:55
  • @estani yes, I've tested and yes, gdal.OpenEx works with strings in python. – user2856 Aug 9 '18 at 20:26
  • @Luke thanks for checking. It's just strange then and a pity that it doesn't work with Java. – estani Aug 10 '18 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.