YuChun's Blog
Published on

Convert CSV to GeoJSON using GDAL

Authors
  • avatar
    Name
    YuChun Tsao
    Twitter

If you have a csv file with columns for coordinates, you can convert the csv to geojson using GDAL.

Environment

  • GDAL 3.5.1

Data

Prepare a csv file with latitude and longitude columns.

input.csv

This example input.csv file was extracted from Nature Earth Populated Places
ogr2ogr -f CSV input.csv ne_110m_populated_places_simple.shp

Example 1

You can use X_POSSIBLE_NAMES and Y_POSSIBLE_NAMES options to match column of input csv file.

ogr2ogr \
    -f GeoJSON \
    output_1.geojson \
    input.csv \
    -oo X_POSSIBLE_NAMES=LONGITUDE \
    -oo Y_POSSIBLE_NAMES=LATITUDE

output_1.geojson

Example 2

If you don't want to write all csv columns into geojson properties, you can filter columns or data through SQL syntax.

ogr2ogr \
    -f GeoJSON \
    output_2.geojson \
    -oo X_POSSIBLE_NAMES=LONGITUDE \
    -oo Y_POSSIBLE_NAMES=LATITUDE \
    -sql "SELECT NAME FROM input" \
    input.csv

output_2.geojson

Example 3

You can also add some options to create geojson. (geojson layer-creation-options)

ogr2ogr \
    -f GeoJSON \
    output_3.geojson \
    -oo X_POSSIBLE_NAMES=LONGITUDE \
    -oo Y_POSSIBLE_NAMES=LATITUDE \
    -lco RFC7946=YES \
    -lco ID_GENERATE=YES \
    -lco ID_TYPE=String \
    -lco WRITE_NAME=NO \
    -sql "SELECT NAME FROM input" \
    input.csv

output_3.geojson

References