Source code for shapelib.core.handlers.kml_handler
from pathlib import Path
from typing import Any
import fiona
import fiona.drvsupport as drv
import geopandas as gpd
from geopandas import GeoDataFrame
from shapelib.core.geometries.base import BaseShapes
from shapelib.core.handlers.geo_file_handler import GeoFileHandler
from shapelib.factories.registry import register_handler
drv.supported_drivers.setdefault("KML", "r") # ensure KML support if GDAL compiled with it
[docs]
@register_handler(file_extension=".kml")
class KmlHandler(GeoFileHandler):
driver: str = "KML"
extension: str = ".kml"
def __init__(self, path: Path) -> None:
super().__init__(path)
self.validate_file()
[docs]
def validate_file(self) -> None:
try:
with fiona.open(self.path, mode="r") as src:
if len(src) == 0:
print(f"KML '{self.path.name}' contains zero features.")
except Exception as e:
raise ValueError(
f"Could not open the KML file: {self.path.as_posix()}\n"
f"Ensure the file is valid KML and not corrupted. ({e})"
) from e
[docs]
def load_data(self, **kwargs: Any) -> GeoDataFrame:
return gpd.read_file(self.path, **kwargs)
[docs]
def create_obj(self, **kwargs: Any) -> BaseShapes:
data = self.load_data(**kwargs)
return self.create_geometry_instance(data=data, driver=self.driver)