def merge_feature_classes(feature_class_paths: List[str], boundary: BaseGeometry, out_layer_path: str): """[summary] Args: feature_class_paths (List[str]): [description] boundary (BaseGeometry): [description] out_layer_path (str): [description] """ log = Logger('merge_feature_classes') log.info('Merging {} feature classes.'.format(len(feature_class_paths))) with get_shp_or_gpkg(out_layer_path, write=True) as out_layer: fccount = 0 for in_layer_path in feature_class_paths: fccount += 1 log.info("Merging feature class {}/{}".format(fccount, len(feature_class_paths))) with get_shp_or_gpkg(in_layer_path) as in_layer: in_layer.SetSpatialFilter(VectorBase.shapely2ogr(boundary)) # First input spatial ref sets the SRS for the output file transform = in_layer.get_transform(out_layer) for i in range(in_layer.ogr_layer_def.GetFieldCount()): in_field_def = in_layer.ogr_layer_def.GetFieldDefn(i) # Only create fields if we really don't have them # NOTE: THIS ASSUMES ALL FIELDS OF THE SAME NAME HAVE THE SAME TYPE if out_layer.ogr_layer_def.GetFieldIndex(in_field_def.GetName()) == -1: out_layer.ogr_layer.CreateField(in_field_def) log.info('Processing feature: {}/{}'.format(fccount, len(feature_class_paths))) for feature, _counter, progbar in in_layer.iterate_features('Processing feature'): geom = feature.GetGeometryRef() if geom is None: progbar.erase() # get around the progressbar log.warning('Feature with FID={} has no geometry. Skipping'.format(feature.GetFID())) continue geom.Transform(transform) out_feature = ogr.Feature(out_layer.ogr_layer_def) for i in range(in_layer.ogr_layer_def.GetFieldCount()): out_feature.SetField(out_layer.ogr_layer_def.GetFieldDefn(i).GetNameRef(), feature.GetField(i)) out_feature.SetGeometry(geom) out_layer.ogr_layer.CreateFeature(out_feature) log.info('Merge complete.') return fccount
def simple_save(list_geoms, ogr_type, srs, layer_name, gpkg_path): with GeopackageLayer(gpkg_path, layer_name, write=True) as lyr: lyr.create_layer(ogr_type, spatial_ref=srs) progbar = ProgressBar(len(list_geoms), 50, f"Saving {gpkg_path}/{layer_name}") counter = 0 progbar.update(counter) lyr.ogr_layer.StartTransaction() for geom in list_geoms: counter += 1 progbar.update(counter) feature = ogr.Feature(lyr.ogr_layer_def) geom_ogr = VectorBase.shapely2ogr(geom) feature.SetGeometry(geom_ogr) # if attributes: # for field, value in attributes.items(): # feature.SetField(field, value) lyr.ogr_layer.CreateFeature(feature) feature = None progbar.finish() lyr.ogr_layer.CommitTransaction()