from pygeoif.geometry import mapping from shapely.geometry import shape def merge_features(geojson, condition, aggregate={}): """Merge the geometries using shapely's union for all the geojson's features that meet the condition, condition get's passed an item of feature. Then aggregate the properties in the aggregate dict using a function that get as input the list of property values off alle matched features. Operates inplace.""" indices = [index for index, feature in enumerate(geojson['features']) if condition(feature)] if len(indices) == 0: # also if there is one index, we return geojson properties = { prop: agg([ properties_[prop] for index in indices for properties_ in [geojson['features'][index]['properties']] if prop in properties_ ]) for prop, agg in aggregate.items() } properties.update({ key: value for index in indices for key, value in geojson['features'][index]['properties'].items() if key not in aggregate }) if len(indices) == 1: geojson['features'][indices[0]]['properties'] = properties return geojson union = shape(geojson['features'][indices[0]]['geometry']) for index in indices[1:]: union = union.union(shape(geojson['features'][index]['geometry'])) for index in indices[::-1]: # reverse, such that the 'todo' indices willnot change. del geojson['features'][index] geojson['features'].append({ 'geometry': mapping(union), 'properties': properties }) return geojson