Sunday, 16 September 2018

GDAL OGR API GeoJSON from other datasource as string NOT file


Using the GDAL/OGR API, I need to be able to convert various types of GDAL datasources into GeoJSON. However, I do not want to write the GeoJSON to a file, but rather I need to just return the text string within the application.


For example, if I have a set of shapefiles, I want to be able to extract the data from one of these shapefiles as a GeoJSON text string.



I want to avoid the slow I/O penalty of writing it to a file and then reading the file and then deleting the file. Such I/O would likely slow things down too much, as I would be running such tasks very frequently (if I can ever get it to work).


Is there some way to get GDAL data as GeoJSON text without writing it to a file first?


Note that I'm using the C API for GDAL/OGR within an application. So a C or C++ solution would be preferred. However, I'm also open to other suggestions which may give me other ideas.


PS . This is on iOS.



Answer



Based on the suggestion from @NathanW I'm going to use OGR_G_ExportToJson() for each geometry in the layer (filtered by spatial extent). I don't think I need non-spatial attributes for this, but if I do, I could theoretically build up JSON properties to include alongside the geometry. So my plan is to do it this way:



  1. Set a spatial filter on the layer with OGR_L_SetSpatialFilterRect()

  2. Cycle through the filtered features with OGR_L_GetNextFeature()

  3. Get the geometry of each feature with OGR_F_GetGeometryRef()


  4. Get GeoJSON string of each geometry with OGR_G_ExportToJson()

  5. Construct a GeoJSON feature string for each geometry based on a template string, including the GeoJSON geometry string obtained earlier, and add it to an array of GeoJSON feature strings

  6. Construct a full GeoJSON string for a feature collection, including converting the array to a GeoJSON feature list


I've implemented most of this now, but haven't actually tested it properly yet.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...