Source code for shapelib.core.handlers.geojson_handler

from pathlib import Path
from typing import Any

import fiona
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


[docs] @register_handler(file_extension=".json") @register_handler(file_extension=".geojson") class GeojsonHandler(GeoFileHandler): driver: str = "GeoJSON" extension: str = ".geojson" 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", driver="GeoJSON") as src: if len(src) == 0: print(f"Warning: GeoJSON '{self.path.name}' contains zero features.") except Exception as e: raise ValueError( f"Could not open the GeoJSON: {self.path.as_posix()}\n" f"Ensure the file is valid JSON 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)