Skip to content

Instantly share code, notes, and snippets.

@esgn
Last active October 29, 2024 13:13
Show Gist options
  • Save esgn/06db6f1bd423fc5eed493e02a17bf0a4 to your computer and use it in GitHub Desktop.
Save esgn/06db6f1bd423fc5eed493e02a17bf0a4 to your computer and use it in GitHub Desktop.
Download GPKG from WFS example
import sys
try:
from osgeo import ogr, osr, gdal
except:
sys.exit('ERROR: cannot find GDAL/OGR modules')
# create the spatial reference
srs = osr.SpatialReference()
srs.ImportFromEPSG(2154)
# Set the driver (optional)
wfs_drv = ogr.GetDriverByName('WFS')
# Speeds up querying WFS capabilities for services with alot of layers
gdal.SetConfigOption('OGR_WFS_LOAD_MULTIPLE_LAYER_DEFN', 'NO')
# Set config for paging. Works on WFS 2.0 services and WFS 1.0 and 1.1 with some other services.
gdal.SetConfigOption('OGR_WFS_PAGING_ALLOWED', 'YES')
gdal.SetConfigOption('OGR_WFS_PAGE_SIZE', '5000')
# Open the webservice
# Get features in EPSG:2154 with only the cleabs attribute
url = 'https://data.geopf.fr/wfs?SERVICE=WFS&SRSNAME=EPSG:2154&PROPERTYNAME=cleabs,geometrie'
wfs_ds = wfs_drv.Open('WFS:' + url)
if not wfs_ds:
sys.exit('ERROR: cannot open WFS datasource')
else:
pass
# Get a specific layer
layer = wfs_ds.GetLayerByName('BDTOPO_V3:batiment')
# Set spatial filter (bounding box as wkt polygon)
wkt = "POLYGON ((632172 6829666,651278 6829666,651278 6842525,632172 6842525,632172 6829666))"
geometry = ogr.CreateGeometryFromWkt(wkt, srs)
layer.SetSpatialFilter(geometry)
# Write to gpkg
dr = ogr.GetDriverByName( 'GPKG' )
ds = dr.CreateDataSource( 'batiments.gpkg' )
ds.CopyLayer(layer, 'local_copy')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment