如何使用fastkml与Python3.6创建多几何体(含多点与线)
I’ve dealt with this exact mismatch between Shapely and fastkml’s expected geometry types before—no need to hack the library source! Here are two reliable approaches:
Option 1: Convert Shapely Geometry to pygeoif Types
Since fastkml is designed to work with pygeoif geometric objects under the hood, you can convert your existing Shapely geometries to their pygeoif equivalents seamlessly:
First, import the required modules:
from shapely.geometry import Point, LineString, GeometryCollection as ShapelyGC from pygeoif import GeometryCollection as PygeoifGC from fastkml import KML, Placemark
Build your Shapely geometries, then convert the collection to pygeoif:
# Define your points and line using Shapely point1 = Point(0, 0) point2 = Point(1, 1) connecting_line = LineString([(0, 0), (1, 1)]) # Create a Shapely GeometryCollection, then convert to pygeoif's version shapely_collection = ShapelyGC([point1, point2, connecting_line]) pygeoif_collection = PygeoifGC(shapely_collection)
Assign the converted collection to your Placemark and generate the KML:
# Set up the KML structure kml_doc = KML() main_folder = kml_doc.new_folder(name="Multi-Geometry Items") multi_geom_placemark = main_folder.new_placemark(name="Two Points + Connecting Line") # Assign the pygeoif geometry (this won't throw type errors!) multi_geom_placemark.geometry = pygeoif_collection # Output the formatted KML print(kml_doc.to_string(prettyprint=True))
Option 2: Use pygeoif Directly
If you don’t strictly need Shapely’s advanced features, you can build your geometries directly with pygeoif to avoid conversion entirely:
from pygeoif import Point, LineString, GeometryCollection from fastkml import KML, Placemark # Build geometries directly with pygeoif point1 = Point(0, 0) point2 = Point(1, 1) connecting_line = LineString([(0, 0), (1, 1)]) multi_geometry = GeometryCollection([point1, point2, connecting_line]) # Assemble the KML kml_doc = KML() main_folder = kml_doc.new_folder(name="Multi-Geometry Items") multi_geom_placemark = main_folder.new_placemark(name="Two Points + Connecting Line") multi_geom_placemark.geometry = multi_geometry # Generate KML output print(kml_doc.to_string(prettyprint=True))
Why Your Original Approach Failed
Fastkml’s geometry.py explicitly imports and expects pygeoif.GeometryCollection, not shapely.geometry.GeometryCollection. These are distinct classes, so passing a Shapely collection triggers a type check error. By either converting Shapely objects to pygeoif or using pygeoif directly, you align with the library’s expected types without modifying its source code.
内容的提问来源于stack exchange,提问作者bricoldur

