1

Taking a long shot but does anyone have an idea of whether GDAL or OGR has a function to determine a shapefile or layer geometry type using python? I specifically want the output to print "POINT" for example.

I understand that the geometry can be printed to well-known text format and have the code to complete that, but specifically require the string format.

6 Answers 6

7

See the cookbook

print(geom.GetGeometryName())
7

It's possible to get the layer geometry type without reading a feature.

ds = ogr.Open(your_input_file)
layer = ds.GetLayer()
layer_defn = layer.GetLayerDefn()
ogr.GeometryTypeToName(layer_defn.GetGeomType())
'Polygon'
6

I don´t want to be punctilious with the code, but you don´t need to loop all the features, the shapefile always store only one geometry type:

        # get the data layer
    layer = datasource.GetLayer()

    # get the first feature
    feature = layer.GetNextFeature()

    geometry = feature.GetGeometryRef()
    print(geometry.GetGeometryName())
0
5

I solved the problem as such:

def geom_type():
    
    shapefile_location = r"E:\Cameron\Python\GDAL\SHP\Cadastral_Parcels\Parcels.shp"
    shapefile = ogr.Open(shapefile_location)
    layer = shapefile.GetLayer()

    for feature in layer:
        geometry = feature.GetGeometryRef()
        print(geometry.GetGeometryName())
        
geom_type()
1

Why not directly use the layer.GetGeomType() method? > Gdal/Ogr python API

print(layer.GetGeomType() == wkbLineString)
>>> True
2
  • This returns the layer's type (LineString) and format (wkb), but the function isn't designed for individual geometries (returns a negative integer in my test). GetGeometryName() works on geometries and doesn't include the format (wkb) in the string return. Oct 25, 2018 at 21:06
  • Negative integers may be OK because codes for 25D geometries are small negative integers.
    – user30184
    May 19, 2020 at 7:20
1

One gotcha to be aware of, which caught me out. Don't forget to add:

layer.ResetReading()

If you want to process the features after determining the geometry type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.