[GIS] Import xyz data from csv into gdal

gdal

I have many CSV file in the form of lon, lat, Z that in would like to import into gdal for further processing. I need to do this on the fly in a python script so any step involving gdal_grid or anything else from the command line is not an option.

It seemed that creating a vrt xml would solve the problem but I am unable to get gdal to load the data.

Loading data this way seems to be such a common task I can't believe there is not a way to do this.

Best Answer

Step 1: Create CSV file "xyztest.csv"

x,y,z
1,2,3
4,5,6
7,8,9

Step 2: Write a VRT file "xyz.vrt" that maps the previous file

<OGRVRTDataSource>

    <OGRVRTLayer name="xyztest">
        <SrcDataSource>xyztest.csv</SrcDataSource> 
    <SrcLayer>xyztest</SrcLayer> 
    <GeometryType>wkbPoint</GeometryType> 
        <LayerSRS>WGS84</LayerSRS>
    <GeometryField encoding="PointFromColumns" x="x" y="y" z="z"/> 
    </OGRVRTLayer>

</OGRVRTDataSource>

Step 3: Test with ogrinfo

C:\temp>ogrinfo xyz.vrt -al
INFO: Open of `xyz.vrt'
      using driver `VRT' successful.

Layer name: xyztest
Geometry: Point
Feature Count: 3
Extent: (1.000000, 2.000000) - (7.000000, 8.000000)
Layer SRS WKT:
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        TOWGS84[0,0,0,0,0,0,0],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0,
        AUTHORITY["EPSG","8901"]],
    UNIT["degree",0.0174532925199433,
        AUTHORITY["EPSG","9108"]],
    AUTHORITY["EPSG","4326"]]
x: String (0.0)
y: String (0.0)
z: String (0.0)
OGRFeature(xyztest):1
  x (String) = 1
  y (String) = 2
  z (String) = 3
  POINT (1 2 3)

OGRFeature(xyztest):2
  x (String) = 4
  y (String) = 5
  z (String) = 6
  POINT (4 5 6)

OGRFeature(xyztest):3
  x (String) = 7
  y (String) = 8
  z (String) = 9
  POINT (7 8 9)

All done. It may still be necessary to explicitly define that the input vrt is 3D. For example ogr2ogr conversion into shapefile creates a "POINT" type shapefile unless "-SHPT POINTZ" is used as a parameter.

Related Question