Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active January 31, 2021 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abelcallejo/882efec5356fb78820e912b20f8f48d6 to your computer and use it in GitHub Desktop.
Save abelcallejo/882efec5356fb78820e912b20f8f48d6 to your computer and use it in GitHub Desktop.
Converting a shapefile with multiple features into independent GeoJSON files

Converting a shapefile with multiple features into independent GeoJSON files

GDAL JSON Terminal.app

Usage

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

Parameters

  • /path/to/shp2geojson.sh - the relative or full path to the shp2geojson.sh script
  • /path/to/input.shp - the relative or full path to the shapefile that contains multiple features
  • unique_column - the column in the attribute table of the shapefile which contains unique entries that can serve as identifiers such as IDs. If your shapefile does not contain a column with unique IDs, I would suggest not to use this literature and use the alternative guide instead.
  • /path/to/output-dir - the relative or full path to the directory/folder where you want the GeoJSON files to be stored. You don't need to create this folder beforehand. The script can create the folder if it currently does not exist.

Example

bash shp2geojson.sh /Users/john/Downloads/input.shp id /Users/john/Desktop/geojsons

Full tutorial

  1. Download the shp2geojson.sh script 😋

  2. Open the Terminal app 🤓

  3. Issue the command 😎

    bash /Users/john/Downloads/shp2geojson.sh /Users/john/Downloads/input.shp id /Users/john/Desktop/geojsons

    Replace the certain parts of the command depending on your case. See the Parameters section for reference.

Use cases

#!/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 $3 ]; then
echo "The directory $3 is now ready."
else
mkdir -p "$3"
echo "The directory $3 is has just been created and now ready."
fi
for (( i=0; i<$count; i++ )); do
echo "Processing feature #$i..."
filename=$(ogrinfo -fid $i -ro -noextent -nomd -geom=NO "$1" "$layername" | grep "$2 " | awk '{print $4}')
ogr2ogr -f GeoJSON -t_srs EPSG:4326 -fid "$i" "$3/$filename.geojson" "$1"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment