I am trying to write a GeoDataFrame's GeometryCollection geometry to a GPKG file and open the result in QGIS. This is the way I create the GPKG file:
import shapely
import geopandas as gpd
gpd.GeoSeries(
shapely.geometry.GeometryCollection(
[
shapely.geometry.LineString([[0, 0], [0, 1]]),
shapely.geometry.LineString([[1, 0], [1, 1]]),
]
)
).set_crs(3857).to_file(
"geomcolltest.gpkg", engine="pyogrio", geometry_type="GeometryCollection"
)
However, when I try opening geomcolltest.gpkg
in QGIS, I get this error message:
At other times, no error message, no shown geometries, just a warning next to the layer title:
Yet other times, I get:
(Interestingly, using shapely.geometry.MultiLineString
instead of shapely.geometry.GeometryCollection
seems to consistently lead to this last error message. The problem is not isolated to GeometryCollection
s.)
Conversely, ogrinfo
does seem to indicate the geometry type is not Unknown Type
but it is Geometry Collection
, as ogrinfo geomcolltest.gpkg
returns:
INFO: Open of `geomcolltest.gpkg'
using driver `GPKG' successful.
1: geomcolltest (Geometry Collection)
I check that my GeoSeries is valid this way:
gpd.GeoSeries(
shapely.geometry.GeometryCollection(
[
shapely.geometry.LineString([[0, 0], [0, 1]]),
shapely.geometry.LineString([[1, 0], [1, 1]]),
]
)).is_valid
Output:
0 True
dtype: bool
To investigate further, I convert the GPKG file in question to a GeoJSON via ogr2ogr geomcolltest.geojson geomcolltest.gpkg
. I end up with geomcolltest.geojson
:
{
"type": "FeatureCollection",
"name": "geomcolltest",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::3857" } },
"features": [
{ "type": "Feature", "properties": { }, "geometry": { "type": "GeometryCollection", "geometries": [ { "type": "LineString", "coordinates": [ [ 0.0, 0.0 ], [ 0.0, 1.0 ] ] }, { "type": "LineString", "coordinates": [ [ 1.0, 0.0 ], [ 1.0, 1.0 ] ] } ] } }
]
}
When I drag-and-drop this file to QGIS, I again get the latest screenshot posted above, just as in the GPKG case. geojson.io seems to have no problem processing & visualizing the file:
However, another GeoJSON visualizing tool, geojson.tools has the following to say when I try to visualize this GeoJSON:
1 feature(s) added successfully and 1 feature(s) failed to load.
while not displaying the correct geometries:
These few lines from the comment section summarizes the situation very well:
We can say that at this moment: ogr recognizes de geometry collection geometry, so geopandas (through pyogrio) is writing a valid geopackage; QGIS doesn't visualize geometry collections from both geopackage and geojson; neither geojson.tools but geojson.io does.
To return to the premise: I am trying to write a GeoDataFrame's GeometryCollection geometry to a GPKG file and open the result in QGIS.
How to write a GeometryCollection to a GPKG file and open it in QGIS?
ogr2ogr -f GPKG demo.gpkg demo.geojson -nln demo
(work for all GeoJSON Feature types, not onlyGeometryCollection
)