Created
January 9, 2026 05:25
-
-
Save naogify/e92295e27bc91c9159cc618c15b4c02d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| set -ex | |
| # Convert all KML files under the current directory to GeoJSON. | |
| # Output is written under ./GeoJSON mirroring the KML directory structure. | |
| if ! command -v ogr2ogr >/dev/null 2>&1; then | |
| echo "error: ogr2ogr not found. Install GDAL to use this script." >&2 | |
| exit 1 | |
| fi | |
| root_dir="$(pwd)" | |
| out_root="${root_dir}/GeoJSON" | |
| remove_if_empty() { | |
| local path="$1" | |
| if [ ! -f "${path}" ]; then | |
| return 0 | |
| fi | |
| local count | |
| count="$(ogrinfo -ro -al -so "${path}" 2>/dev/null | awk '/Feature Count/ {print $3; exit}')" | |
| if [ -z "${count}" ] || [ "${count}" -eq 0 ]; then | |
| rm -f "${path}" | |
| fi | |
| } | |
| # Find all .kml files and convert each to GeoJSON by geometry type. | |
| find "${root_dir}" -type f -name "*.kml" | while IFS= read -r kml_path; do | |
| rel_path="${kml_path#${root_dir}/}" | |
| out_base="${out_root}/${rel_path%.kml}" | |
| out_dir="$(dirname "${out_base}")" | |
| mkdir -p "${out_dir}" | |
| # Convert to GeoJSON, overwriting if it already exists. | |
| point_out="${out_base}_point.geojson" | |
| line_out="${out_base}_line.geojson" | |
| polygon_out="${out_base}_polygon.geojson" | |
| ogr2ogr -f GeoJSON "${point_out}" "${kml_path}" \ | |
| -where "OGR_GEOMETRY='Point' OR OGR_GEOMETRY='MultiPoint'" | |
| ogr2ogr -f GeoJSON "${line_out}" "${kml_path}" \ | |
| -where "OGR_GEOMETRY='LineString' OR OGR_GEOMETRY='MultiLineString'" | |
| ogr2ogr -f GeoJSON "${polygon_out}" "${kml_path}" \ | |
| -where "OGR_GEOMETRY='Polygon' OR OGR_GEOMETRY='MultiPolygon'" | |
| remove_if_empty "${point_out}" | |
| remove_if_empty "${line_out}" | |
| remove_if_empty "${polygon_out}" | |
| echo "converted: ${rel_path} -> ${out_base#${root_dir}/}_{point,line,polygon}.geojson" | |
| done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment