2

Let's say there's a single shapefile that contains multiple features. Most of which are polygons.

How can one convert those features into separate independent GeoJSON files?

Can this be done with ogr2ogr?

4
  • 2
    Ogr2ogr writes out one dataset so you must select and convert the features one by one in a loop. Ogr2ogr options -sql or -fid can be used for selecting. – user30184 Jan 26 at 6:39
  • @user30184 So that would be like using ogrinfo to list the features and then loop them? Worth a shot though. – Abel Melquiades Callejo Jan 26 at 7:06
  • I think that in shapefile the FIDs run from 1 to the last so checking the number of features might be enough. – user30184 Jan 26 at 7:10
  • Upon doing the solution for this, I learned that FIDs are indexes. That means FIDs start from 0 and the last one is count - 1. I did exactly what you said, which is to select features one-by-one and in a loop. – Abel Melquiades Callejo Jan 31 at 5:38
2

TL;DR

bash /path/to/shp2geojson.sh /path/to/input.shp /path/to/output-dir

shp2geojson.sh

#!/bin/bash
clear;

layername=$(ogrinfo -nogeomtype "$1" | grep "1:" | awk '{print $2}')
count=$(ogrinfo -so -ro "$1" "$layername" | grep "Feature Count:" | awk '{print $3}')

if [ -d $2 ]; then
    echo "The directory $2 is now ready."
else
    mkdir "$2"
    echo "The directory $2 has just been created and now ready."
fi

for (( i=0; i<$count; i++ )); do
   echo "Processing feature #$i..."
   ogr2ogr -f GeoJSON -t_srs EPSG:4326 -fid "$i" "$2/$i.geojson" "$1"
done

This bash script works for Mac and Linux machines. I do not know how to do it in batch script for Windows.

Alternatively

If one wants to use a certain column from the attribute table (instead of the feature index) for the naming of the GeoJSON files, I have made a derivative solution similar to the above script.

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.