Search code examples
csvleafletgeojsonogr

Creating GeoJson from csv: How do I set geometry properties?


I have a csv file that I want to convert to GeoJson.

lon,lat,val,id
-97.1589432,25.9642008,0,2690
-97.1682294,25.9761856,0,2691
-97.1775156,25.9881704,0,2692

I run the following ogr2ogr command

ogr2ogr -f GEOJson geo_result.json source.csv

and I get this result

{
"type": "FeatureCollection",

"features": [
{ "type": "Feature", "properties": { "lon": "-97.1589432", "lat": "25.9642008", "val": "0", "id": "2690" }, "geometry": null },
{ "type": "Feature", "properties": { "lon": "-97.1682294", "lat": "25.9761856", "val": "0", "id": "2691" }, "geometry": null },
{ "type": "Feature", "properties": { "lon": "-97.1775156", "lat": "25.9881704", "val": "0", "id": "2692" }, "geometry": null }
]
}

Why is geometry null? How can I tell ogr2ogr which values are lat & lon?


Solution

  • You need to wrap the CSV file in a VRT file which specifies the meaning of the columns.

    <OGRVRTDataSource>
        <OGRVRTLayer name="source">
            <SrcDataSource>source.csv</SrcDataSource>
            <GeometryType>wkbPoint</GeometryType>
            <LayerSRS>WGS84</LayerSRS>
            <GeometryField encoding="PointFromColumns" x="lon" y="lat"/>
        </OGRVRTLayer>
    </OGRVRTDataSource>
    

    And then use the VRT file as the input:

    ogr2ogr -f GEOJson geo_result.json source.vrt
    

    QGIS (which uses OGR) has an interface which cleverly guesses the columns, and that works very well. So if you have to use your conversion only once it might be worth trying it with a GUI like QGIS.

    See the CSV driver page from OGR for more details: http://www.gdal.org/ogr/drv_csv.html