How to use the geojson.Feature 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 hotosm / tasking-manager / tests / server / unit / services / grid / test_grid_service.py View on Github external
def test_cant_create_aoi_with_non_multipolygon_type(self):
        # Arrange
        bad_geom = geojson.Polygon(
            [[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]]
        )
        bad_feature = geojson.Feature(geometry=bad_geom)
        # bad_feature_collection = geojson.FeatureCollection([bad_feature])

        # Act / Assert
        with self.assertRaises(InvalidGeoJson):
            # Only geometries of type MultiPolygon are valid
            GridService.merge_to_multi_polygon(
                geojson.dumps(bad_feature), dissolve=True
            )
github developmentseed / label-maker / test / unit / test_filter.py View on Github external
def test_has(self):
        """Test has filter function"""
        ff = create_filter(['has', 'a'])
        passing = Feature(geometry=line_geometry, properties=dict(a=1))
        failing = Feature(geometry=line_geometry, properties=dict(b=3))
        self.assertTrue(ff(passing))
        self.assertFalse(ff(failing))
github erdc / quest / dsl / services / coops_pyoos.py View on Github external
def _getFeature(self, stationID):
        offeringid = 'station-%s' % stationID
        variables_list = []
        station = self.COOPS.server.contents[offeringid]
        for op in station.observed_properties:
            variables = op.split("/")
            variables_list.append(variables[len(variables) - 1])

        properties = {
            'station_name': station.name,
            'station_description': station.description,
            'data_offered': variables_list,
            }

        feature = Feature(geometry=Point(station.bbox[:2]),
                          properties=properties, id=stationID)

        return feature
github geosolutions-it / evo-odas / airflow / plugins / S1Reader.py View on Github external
def get_footprint(self):
        GML_NS = "{http://www.opengis.net/gml}"
        gml_coordinates = ""
        for el in self.manifest_tree.iter(GML_NS + "coordinates"):
            gml_coordinates = el.text
        wkt_coordinates = gml_coordinates.replace(",", ";")
        wkt_coordinates = wkt_coordinates.replace(" ", ",")
        wkt_coordinates = wkt_coordinates.replace(";", " ")
        wkt_coordinates = wkt_coordinates + "," + wkt_coordinates.split(",")[0]
        s = "POLYGON ((" + wkt_coordinates + "))"
        log.info("stringa s = " + s)
        g1 = shapely.wkt.loads(s)
        g2 = geojson.Feature(geometry=g1, properties={})
        print type(g2.geometry)
        return g2.geometry
github aerispaha / swmmio / swmmio / utils / spatial.py View on Github external
for rec in records:

        coordinates = rec['coords']
        del rec['coords']  # delete the coords so they aren't in the properties
        if drop_na:
            rec = {k: v for k, v in rec.items() if v is not None}
        latlngs = coordinates

        if geomtype == 'linestring':
            geometry = LineString(latlngs)
        elif geomtype == 'point':
            geometry = Point(latlngs)
        elif geomtype == 'polygon':
            geometry = Polygon([latlngs])

        feature = Feature(geometry=geometry, properties=rec)
        features.append(feature)

    if filename is not None:
        with open(filename, 'wb') as f:
            f.write(json.dumps(FeatureCollection(features)))
        return filename

    else:
        return FeatureCollection(features)
github GeotrekCE / Geotrek-admin / django-geojson / djgeojson / serializers.py View on Github external
geomfield = geomfield.simplify(tolerance=simplify, preserve_topology=True)
        # Optional geometry reprojection
        srid = self.options.get('srid')
        if srid is not None and srid != geomfield.srid:
            geomfield.transform(srid)
        # Load Django geojson representation as dict
        geometry = simplejson.loads(geomfield.geojson)
        # Build properties from object fields
        properties = dict(self._current.iteritems())
        if self.selected_fields is not None:
            properties = {k:v for k,v in properties.items() if k in self.selected_fields}
        # Add extra-info for deserializing
        properties['model'] = smart_unicode(obj._meta)
        properties['pk'] = pk
        # Build pure geojson object
        feature = geojson.Feature(id=pk,
                                  properties=properties,
                                  geometry=geometry)
        self.objects.append(feature)
        self._current = None
github indrz / indrz / indrz / routing / views.py View on Github external
route_info = calc_distance_walktime(route_segments)

    # empty list to hold each segment for our GeoJSON output
    route_result = []

    # loop over each segment in the result route segments
    # create the list of our new GeoJSON
    for segment in route_segments:
        seg_length = segment[4]  # length of segment
        layer_level = segment[6]  # floor number
        seg_type = segment[7]
        seg_node_id = segment[2]
        seq_sequence = segment[0]
        geojs = segment[8]  # geojson coordinates
        geojs_geom = loads(geojs)  # load string to geom
        geojs_feat = Feature(geometry=geojs_geom,
                             properties={'floor': layer_level,
                                         'segment_length': seg_length,
                                         'network_type': seg_type,
                                         'seg_node_id': seg_node_id,
                                         'sequence': seq_sequence}
                             )
        route_result.append(geojs_feat)

    # using the geojson module to create our GeoJSON Feature Collection
    geojs_fc = FeatureCollection(route_result)
    geojs_fc.update(route_info)
    return geojs_fc
github mapbox / robosat / robosat / tools / merge.py View on Github external
if merged.is_valid:
            # Orient exterior ring of the polygon in counter-clockwise direction.
            if isinstance(merged, shapely.geometry.polygon.Polygon):
                merged = shapely.geometry.polygon.orient(merged, sign=1.0)
            elif isinstance(merged, shapely.geometry.multipolygon.MultiPolygon):
                merged = [shapely.geometry.polygon.orient(geom, sign=1.0) for geom in merged.geoms]
                merged = shapely.geometry.MultiPolygon(merged)
            else:
                print("Warning: merged feature is neither Polygon nor MultiPoylgon, skipping", file=sys.stderr)
                continue

            # equal-area projection; round to full m^2, we're not that precise anyway
            area = int(round(project(merged, "epsg:4326", "esri:54009").area))

            feature = geojson.Feature(geometry=shapely.geometry.mapping(merged), properties={"area": area})
            features.append(feature)
        else:
            print("Warning: merged feature is not valid, skipping", file=sys.stderr)

    collection = geojson.FeatureCollection(features)

    with open(args.out, "w") as fp:
        geojson.dump(collection, fp)
github mharnold / spiderosm / spiderosm / shp2geojson.py View on Github external
reader = shapefile.Reader(inFilename)
    fields = reader.fields[1:]
    fieldNames = [field[0] for field in fields]
    #print 'fieldNames', fieldNames
    features = []
    skipped_no_points = 0
    for (sr, ss) in itertools.izip(reader.iterRecords(), reader.iterShapes()):
        if len(ss.points) == 0: 
            skipped_no_points += 1
            continue  
        atr = dict(zip(fieldNames, sr))
        geom = ss.__geo_interface__
        if not clip_rect or geofeatures.coordinates_intersect_rect_q(geom['coordinates'],clip_rect):
            #print 'DEB geom:', geom
            #features.append(dict(type='Feature', geometry=geom, properties=atr)) 
            features.append(geojson.Feature(geometry=geom, properties=atr)) 

    # log messages
    if skipped_no_points > 0:
        log.warning("Skipped %d shapes in %s because they have no geometry.", skipped_no_points, inFilename)

    # write the geojson file
    geofeatures.write_geojson(features, outFileName, srs=srs)
github mvexel / remapatron / service / get.py View on Github external
def GET(self,osmid):
        conn = psycopg2.connect(connstr)
        cur = conn.cursor()
        if osmid:                                                            
            cur.execute("SELECT ST_AsGeoJSON(geom_way), osmid_way, ST_AsGeoJSON(geom), osmid FROM mr_currentchallenge WHERE osmid_way = %(osmid)s",
                        {'osmid': osmid})
            
        else:
            cur.execute("SELECT ST_AsGeoJSON(geom_way), osmid_way, ST_AsGeoJSON(geom), osmid FROM mr_currentchallenge WHERE fixflag < 3 ORDER BY RANDOM() LIMIT 1")
        recs = cur.fetchall()
        print recs[0]
        (way,wayid,point,nodeid) = recs[0]
        if point is not None:
            out = geojson.FeatureCollection([geojson.Feature(geometry=geojson.loads(way),properties={"id": wayid}),geojson.Feature(geometry=geojson.loads(point),properties={"id": nodeid})])
        else:
            out = geojson.FeatureCollection([geojson.Feature(geometry=geojson.loads(way),properties={"id": wayid})])
        return geojson.dumps(out)