How to use the geojson.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 / tests / test_base.py View on Github external
def test_errors(self):
        class Fake(geojson.GeoJSON):
            pass

        with self.assertRaises(NotImplementedError):
            Fake().errors()
github jazzband / geojson / tests / test_base.py View on Github external
self.assertTrue("type" in geojson_obj.properties)

        json_str = ('{"type": "Feature",'
                    ' "geometry": null,'
                    ' "id": 1,'
                    ' "properties": {"type": null}}')
        geojson_obj = geojson.loads(json_str)
        self.assertTrue(isinstance(geojson_obj, geojson.GeoJSON))
        self.assertTrue("type" in geojson_obj.properties)

        json_str = ('{"type": "Feature",'
                    ' "geometry": null,'
                    ' "id": 1,'
                    ' "properties": {"type": "meow"}}')
        geojson_obj = geojson.loads(json_str)
        self.assertTrue(isinstance(geojson_obj, geojson.GeoJSON))
        self.assertTrue("type" in geojson_obj.properties)
github girder / girder / plugins / geospatial / server / geospatial.py View on Github external
def _getGeometry(self, geometry):
        try:
            GeoJSON.to_instance(geometry, strict=True)

            if geometry['type'] != 'Point':
                raise ValueError

            return geometry
        except (TypeError, ValueError):
            raise RestException("Invalid GeoJSON passed as 'geometry' parameter.")
github jazzband / geojson / geojson / mapping.py View on Github external
def to_mapping(obj):

    mapping = getattr(obj, GEO_INTERFACE_MARKER, None)

    if mapping is not None:
        return mapping

    if is_mapping(obj):
        return obj

    if isinstance(obj, geojson.GeoJSON):
        return dict(obj)

    return json.loads(json.dumps(obj))
github pbugnion / gmaps / gmaps / geojson_layer.py View on Github external
def _validate_geojson(geojson_document):
    try:
        geojson_instance = geojson.loads(json.dumps(geojson_document))
    except ValueError as e:
        raise InvalidGeoJson(e.message)
    if not isinstance(geojson_instance, geojson.GeoJSON):
        # Sometimes GeoJSON.to_instance fails silently and just returns
        # the original type, rather than validation errors.
        # Try with, e.g. an empty dictionary.
        raise InvalidGeoJson('Could not convert document to GeoJSON.')
    if not geojson_instance.is_valid:
        raise InvalidGeoJson(", ".join(geojson_instance.errors()))
    if geojson_document["type"] != "FeatureCollection":
        raise InvalidGeoJson(
            "Only FeatureCollection GeoJSON is currently supported")
github geoadmin / mf-chsdi3 / chsdi / lib / validation.py View on Github external
def linestring(self, value):
        import geojson
        if value is None:
            raise exc.HTTPBadRequest("Missing parameter geom")
        try:
            geom = geojson.loads(value, object_hook=geojson.GeoJSON.to_instance)
        except:
            raise exc.HTTPBadRequest("Error loading geometry in JSON string")
        try:
            shape = asShape(geom)
        except:
            raise exc.HTTPBadRequest("Error converting JSON to Shape")
        try:
            shape.is_valid
        except:
            raise exc.HTTPBadRequest("Invalid Linestring syntax")

        self._linestring = shape
github hotosm / tasking-manager / server / services / grid / grid_service.py View on Github external
def _to_shapely_geometries(input: str) -> list:
        """
        Parses the input geojson and returns a list of geojson.Feature objects with their geometries adapted to shapely geometries
        :param input: string of geojson
        :return: list of geojson.Feature objects with their geometries adapted to shapely geometries
        """
        collection = geojson.loads(input, object_hook=geojson.GeoJSON.to_instance)

        if not hasattr(collection, "features") or len(collection.features) < 1:
            raise InvalidGeoJson("Geojson does not contain any features")

        shapely_features = list(
            (filter(lambda x: x is not None, map(GridService._adapt_feature_geometry, collection.features))))

        return shapely_features
github geoadmin / mf-chsdi3 / chsdi / lib / validation / profile.py View on Github external
def linestring(self, value):
        if value is None:
            raise HTTPBadRequest("Missing parameter geom")
        try:
            geom = geojson.loads(value, object_hook=geojson.GeoJSON.to_instance)
        except:
            raise HTTPBadRequest("Error loading geometry in JSON string")
        try:
            shape = asShape(geom)
        except:
            raise HTTPBadRequest("Error converting JSON to Shape")
        try:
            shape.is_valid
        except:
            raise HTTPBadRequest("Invalid Linestring syntax")

        self._linestring = shape
github hotosm / tasking-manager / osmtm / scripts / initializedb.py View on Github external
Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)

    # then, load the Alembic configuration and generate the
    # version table, "stamping" it with the most recent rev:
    from alembic.config import Config
    from alembic import command
    alembic_cfg = Config("alembic.ini")
    url = settings['sqlalchemy.url']
    alembic_cfg.set_section_option("alembic", "sqlalchemy.url", url)
    command.stamp(alembic_cfg, "head")

    with transaction.manager:
        geometry = '{"type":"Polygon","coordinates":[[[85.31038284301758,27.70731518595052],[85.31089782714842,27.698120147680104],[85.3242015838623,27.69842412827061],[85.323429107666,27.70731518595052],[85.31038284301758,27.70731518595052]]]}'  # noqa
        geometry = geojson.loads(geometry,
                                 object_hook=geojson.GeoJSON.to_instance)
        geometry = shapely.geometry.asShape(geometry)
        geometry = shape.from_shape(geometry, 4326)

        area = Area(
            geometry
        )
        DBSession.add(area)

        license1 = License()
        license1.name = 'NextView'
        license1.description = "This data is licensed for use by the US Government (USG) under the NextView (NV) license and copyrighted by Digital Globe or GeoEye. The NV license allows the USG to share the imagery and Literal Imagery Derived Products (LIDP) with entities outside the USG when that entity is working directly with the USG, for the USG, or in a manner that is directly beneficial to the USG. The party receiving the data can only use the imagery or LIDP for the original purpose or only as otherwise agreed to by the USG. The party receiving the data cannot share the imagery or LIDP with a third party without express permission from the USG. At no time should this imagery or LIDP be used for other than USG-related purposes and must not be used for commercial gain. The copyright information should be maintained at all times. Your acceptance of these license terms is implied by your use."  # noqa
        license1.plain_text = "In other words, you may only use NextView imagery linked from this site for digitizing OpenStreetMap data for humanitarian purposes."  # noqa
        DBSession.add(license1)

        license2 = License()
        license2.name = 'Astrium/UNOSAT'
github geoadmin / mf-chsdi3 / chsdi / esrigeojsonencoder.py View on Github external
def default(self, obj):
        geom_type = None
        if hasattr(obj, '__geo_interface__'):
            geom_type = dict(obj.__geo_interface__)['type']

        if isinstance(obj, (decimal.Decimal, datetime.date, datetime.datetime)):
            return str(obj)

        if isinstance(obj, GeoInterface):
            self.srs = obj.geometry_column().type.srid
            obj = obj.__geo_interface__

        if isinstance(obj, (geojson.GeoJSON)):
            ret = dict(obj)
            if 'coordinates' in ret:
                coordinates = ret['coordinates']

            if isinstance(obj, (geojson.Feature, geojson.feature.Feature)) or geom_type == 'Feature':
                ret = dict(obj)
                geometry = self.default(obj.geometry)
                ret = dict(obj)
                ret['geometry'] = geometry
                esriType = 'esriGeometryPoint'
                if 'rings' in geometry:
                    esriType = 'esriGeometryPolygon'
                if 'paths' in geometry:
                    esriType = 'esriGeometryPolyline'
                ret['geometryType'] = esriType