How to use the geojson.base.GeoJSON function in geojson

To help you get started, we’ve selected a few geojson examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jazzband / geojson / geojson / base.py View on Github external
def errors(self):
        """Return validation errors (if any).
        Implement in each subclass.
        """

        # make sure that each subclass implements it's own validation function
        if self.__class__ != GeoJSON:
            raise NotImplementedError(self.__class__)
github jazzband / geojson / geojson / geometry.py View on Github external
def __getitem__(self, key):
        try:
            return self.get("geometries", ())[key]
        except (KeyError, TypeError, IndexError):
            return super(GeoJSON, self).__getitem__(key)
github jazzband / geojson / geojson / feature.py View on Github external
:return: Feature object
        :rtype: Feature
        """
        super(Feature, self).__init__(**extra)
        if id is not None:
            self["id"] = id
        self["geometry"] = (self.to_instance(geometry, strict=True)
                            if geometry else None)
        self["properties"] = properties or {}

    def errors(self):
        geo = self.get('geometry')
        return geo.errors() if geo else None


class FeatureCollection(GeoJSON):
    """
    Represents a FeatureCollection, a set of multiple Feature objects.
    """

    def __init__(self, features, **extra):
        """
        Initialises a FeatureCollection object from the
        :param features: List of features to constitute the FeatureCollection.
        :type features: list
        :return: FeatureCollection object
        :rtype: FeatureCollection
        """
        super(FeatureCollection, self).__init__(**extra)
        self["features"] = features

    def errors(self):
github jazzband / geojson / geojson / base.py View on Github external
:type default: GeoJSON
        :param strict: Raise error if unable to coerce particular keys or
        attributes to a valid GeoJSON structure.
        :type strict: bool
        :return: A GeoJSON object with the dict's elements as its constituents.
        :rtype: GeoJSON
        :raises TypeError: If the input dict contains items that are not valid
        GeoJSON types.
        :raises UnicodeEncodeError: If the input dict contains items of a type
        that contain non-ASCII characters.
        :raises AttributeError: If the input dict contains items that are not
        valid GeoJSON types.
        """
        if ob is None and default is not None:
            instance = default()
        elif isinstance(ob, GeoJSON):
            instance = ob
        else:
            mapping = to_mapping(ob)
            d = {}
            for k in mapping:
                d[k] = mapping[k]
            try:
                type_ = d.pop("type")
                try:
                    type_ = str(type_)
                except UnicodeEncodeError:
                    # If the type contains non-ascii characters, we can assume
                    # it's not a valid GeoJSON type
                    raise AttributeError(
                        "{0} is not a GeoJSON type").format(type_)
                geojson_factory = getattr(geojson.factory, type_)
github jazzband / geojson / geojson / codec.py View on Github external
def load(fp,
         cls=json.JSONDecoder,
         parse_constant=_enforce_strict_numbers,
         object_hook=geojson.base.GeoJSON.to_instance,
         **kwargs):
    return json.load(fp,
                     cls=cls, object_hook=object_hook,
                     parse_constant=parse_constant,
                     **kwargs)
github jazzband / geojson / geojson / feature.py View on Github external
"""
SimpleWebFeature is a working example of a class that satisfies the Python geo
interface.
"""

from geojson.base import GeoJSON


class Feature(GeoJSON):
    """
    Represents a WGS84 GIS feature.
    """

    def __init__(self, id=None, geometry=None, properties=None, **extra):
        """
        Initialises a Feature object with the given parameters.

        :param id: Feature identifier, such as a sequential number.
        :type id: str, int
        :param geometry: Geometry corresponding to the feature.
        :param properties: Dict containing properties of the feature.
        :type properties: dict
        :return: Feature object
        :rtype: Feature
        """
github jazzband / geojson / geojson / base.py View on Github external
def __init__(self, iterable=(), **extra):
        """
        Initialises a GeoJSON object

        :param iterable: iterable from which to draw the content of the GeoJSON
        object.
        :type iterable: dict, array, tuple
        :return: a GeoJSON object
        :rtype: GeoJSON
        """
        super(GeoJSON, self).__init__(iterable)
        self["type"] = getattr(self, "type", type(self).__name__)
        self.update(extra)
github jazzband / geojson / geojson / geometry.py View on Github external
new_coords = []
        if isinstance(coords, Geometry):
            coords = [coords]
        for coord in coords:
            if isinstance(coord, (list, tuple)):
                new_coords.append(cls.clean_coordinates(coord, precision))
            elif isinstance(coord, Geometry):
                new_coords.append(coord['coordinates'])
            elif isinstance(coord, _JSON_compliant_types):
                new_coords.append(round(coord, precision))
            else:
                raise ValueError("%r is not a JSON compliant number" % coord)
        return new_coords


class GeometryCollection(GeoJSON):
    """
    Represents an abstract base class for collections of WGS84 geometries.
    """

    def __init__(self, geometries=None, **extra):
        super(GeometryCollection, self).__init__(**extra)
        self["geometries"] = geometries or []

    def errors(self):
        errors = [geom.errors() for geom in self['geometries']]
        return [err for err in errors if err]

    def __getitem__(self, key):
        try:
            return self.get("geometries", ())[key]
        except (KeyError, TypeError, IndexError):
github jazzband / geojson / geojson / crs.py View on Github external
from geojson.base import GeoJSON


class CoordinateReferenceSystem(GeoJSON):
    """
    Represents a CRS.
    """

    def __init__(self, properties=None, **extra):
        super(CoordinateReferenceSystem, self).__init__(**extra)
        self["properties"] = properties or {}


class Named(CoordinateReferenceSystem):
    """
    Represents a named CRS.
    """

    def __init__(self, properties=None, **extra):
        super(Named, self).__init__(properties=properties, **extra)
github jazzband / geojson / geojson / geometry.py View on Github external
import sys
from decimal import Decimal
from numbers import Number

from geojson.base import GeoJSON


if sys.version_info[0] == 3:
    # Python 3.x has no long type
    _JSON_compliant_types = (float, int, Decimal)
else:
    _JSON_compliant_types = (float, int, Decimal, long)  # noqa


class Geometry(GeoJSON):
    """
    Represents an abstract base class for a WGS84 geometry.
    """

    def __init__(self, coordinates=None, validate=False, precision=6, **extra):
        """
        Initialises a Geometry object.

        :param coordinates: Coordinates of the Geometry object.
        :type coordinates: tuple or list of tuple
        :param validate: Raise exception if validation errors are present?
        :type validate: boolean
        :param precision: Number of decimal places for lat/lon coords.
        :type precision: integer
        """
        super(Geometry, self).__init__(**extra)