Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rbanick/1e96d77a3f5b8d575945 to your computer and use it in GitHub Desktop.
Save rbanick/1e96d77a3f5b8d575945 to your computer and use it in GitHub Desktop.
Using VRT files for CSV to Points conversion.
Sometimes, for whatever reason, QGIS hates your CSV of point data and mangles it so it can't be converted to points. Sometimes, it gets worse and command line GDAL also messes things up. In these cases you can fall back on a .vrt
A .vrt is a really simple file that tells GDAL *exactly* where your lat/long columns are and how to render them (e.g. as point geometry). You can also use this for non-point geometry if you want to get fancy and have columns of polygon data (or a non-csv file type that holds them in another fashion).
A .vrt is basically formatted as below:
<OGRVRTDataSource>
<OGRVRTLayer name="[Filename]">
<SrcDataSource>[Filename].csv</SrcDataSource>
<GeometryType>wkbPoint</GeometryType>
<LayerSRS>WGS84</LayerSRS>
<GeometryField encoding="PointFromColumns" x="your_longitude_column_name" y="your_latitude_column_name"/>
</OGRVRTLayer>
</OGRVRTDataSource>
Once this is setup you should be able to run the following GDAL to convert your file:
ogr2ogr -f "GEOJson" your_new_file.geojson your_old_file.vrt
So instead of running ogr2ogr on your .csv, now you run it on the .vrt and it automatically taps into the CSV and converts. This overcomes any confusion on QGIS's end. QGIS will not recognize the .vrt and will continue to be confused by your CSV, so this only works on the command line.
While I've converted to Geojson in the above example, you could easily convert to .shp or any vector format you like. Have at it MapInfo enthusiasts.
One really crucial thing to mention is that you can combine a .vrt with a .csvt. So not only do you get your points right but you get your column types correct.
For help on how to use a .csvt look here. It's pretty simple: http://anitagraser.com/2011/03/07/how-to-specify-data-types-of-csv-columns-for-use-in-qgis/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment