def test_invalid_geometry_collection(self): geometries = geojson.GeometryCollection() geometries.geometries = [ geojson.Point(coordinates=[0]), geojson.Point(coordinates=[D('100.0'), D('0.0')]) ] self.assertFalse(geometries.is_valid())
def to_geojson(hexgrid, filename): """Write out the hexgrid assignment to geoJSON format. Args: hexgrid (Hexgrid): Hexgrid object that should have an assignment. So the `fit()` function should have been run. """ def to_polygon(code): gridcoords = hexgrid.assignment[code] hexagon = hexgrid.grid[gridcoords] properties = hexgrid.objects[code] # drop the centroid, that was something that I calculated. properties.pop('centroid', None) # also stick the code on because I want that code. properties['code'] = code polygon = geojson.Polygon(mapping(hexagon.to_poly())['coordinates'], properties=properties) return polygon polygons = [to_polygon(code) for code in hexgrid.assignment.keys()] bbox = [ hexgrid.extent['min_x'], hexgrid.extent['min_y'], hexgrid.extent['max_x'], hexgrid.extent['max_y'], ] collection = geojson.GeometryCollection(polygons, bbox=bbox) with open(filename, 'w') as f: geojson.dump(collection, f, sort_keys=True)
def generate_features(self): # Create target directory if don't exist target = os.path.join(output_folder, self.name) if not os.path.exists(target): os.mkdir(target) ## ROOMS fc = geojson.FeatureCollection([r.generate_room_feature(target) for r in self.rooms.values()]) with open(os.path.join(target, self.name + "_rooms.geojson"), 'w') as myout: geojson.dump(fc,myout) ## Room Geometry fc = geojson.GeometryCollection([c.to_geometry_feature() for c in self.rooms.values()]) with open(os.path.join(target, self.name + "_room_geometry.geojson"), 'w') as myout: geojson.dump(fc,myout) ## CONNECTIONS fc = geojson.FeatureCollection([c.to_feature() for c in self.connections]) with open(os.path.join(target, self.name + "_connections.geojson"), 'w') as myout: geojson.dump(fc,myout) ## THROWABLES fc = geojson.FeatureCollection([t.to_feature() for t in self.throwables]) with open(os.path.join(target, self.name + "_throwables.geojson"), 'w') as myout: geojson.dump(fc,myout) ## CREATURE SPAWNS fc = geojson.FeatureCollection([f for f in [s.to_feature() for s in self.spawns] if f]) ## some fail with open(os.path.join(target, self.name + "_spawns.geojson"), 'w') as myout: geojson.dump(fc,myout)
def test_valid_geometrycollection(self): point = geojson.Point((10, 20)) poly = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 57.322)]]) geom_collection = geojson.GeometryCollection(geometries=[point, poly]) self.assertTrue(geom_collection.is_valid)
def dir_tendency(data, filename='trip_line.geojson'): fn = os.path.join(os.getcwd(), filename) raw = data lines = [] vec_l = [] for index, row in raw.iterrows(): start_pt = (row['start station latitude'], row['start station longitude']) end_pt = (row['end station latitude'], row['end station longitude']) line = geojson.geometry.LineString([start_pt, end_pt]) lines.append(line) # print(line) trip_vec = (end_pt[0] - start_pt[0], end_pt[1] - start_pt[1]) len_trip_vec = np.sqrt(np.square(end_pt[0] - start_pt[0]) + np.square(end_pt[1] - start_pt[1])) # vec.append(trip_vec) # vec_l.append(len_trip_vec) pass geocal = geojson.GeometryCollection(lines) with open(fn, 'w') as fl: fl.write(str(geocal)) fl.close() pass # print(type(vec[0])) # raw['vec_X'] = pd.DataFrame() # raw['vec_l'] = pd.DataFrame(vec_l) return None
def as_geojson_geometry(geojson_dict): """ Return a mapping as a GeoJSON instance, converting Feature types to Geometry types. """ try: geoj = geojson.GeoJSON.to_instance(geojson_dict, strict=True) except (TypeError, KeyError, UnicodeEncodeError) as ex: raise ValueError( "geometry not recognized as valid GeoJSON ({}): {}".format( str(ex), geojson_dict)) # Shapely cannot handle GeoJSON Features or FeatureCollections if isinstance(geoj, geojson.Feature): geoj = geoj.geometry elif isinstance(geoj, geojson.FeatureCollection): features = [] for feature in geoj.features: try: features.append( geojson.GeoJSON.to_instance(feature, strict=True).geometry) except (TypeError, KeyError, UnicodeEncodeError) as ex: raise ValueError( "feature in FeatureCollection not recognized as valid ({}): {}" .format(str(ex), feature)) geoj = geojson.GeometryCollection(features) return geoj
def to_json(self, data, options=None): options = options or {} try: if type(data) == dict and 'objects' in data: data = data['objects'] if type(data) == list and data: # we may have a *Collection t = data[0].obj.__geo_interface__ if "type" in t: if t['type'] == "Feature": # data items are Feature Objects. features = [] for f in data: f_dict = f.obj.__geo_interface__ features.append(f_dict) s = geojson.FeatureCollection(features) elif t['type'] in ("Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection"): s = geojson.GeometryCollection(data.obj) else: return super(GeoJSONSerializer, self).to_json(data, options) return geojson.dumps(s) except Exception as e: # fallback to default serialization. return super(GeoJSONSerializer, self).to_json(data, options)
def unwrapFeature(geometry): if geometry.type == 'FeatureCollection': geometries = [n.geometry for n in geometry.features] return geojson.GeometryCollection(geometries) elif geometry.type == 'Feature': return geometry.geometry else: return geometry
def test_invalid_geometrycollection(self): point = geojson.Point((10, 20)) bad_poly = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (25.44, -17.91)]]) geom_collection = geojson.GeometryCollection( geometries=[point, bad_poly]) self.assertFalse(geom_collection.is_valid)
def generateImageAndPolygonFromRaster(raster, outfile_suffix, threshold_high, compute_area = False): with rasterio.open(raster, 'r') as src: print("reading " + raster) # read image into ndarray im = src.read() bounds = src.bounds im = np.transpose(im, [1,2,0]) im = im.squeeze() stress_thresh_shapes= list(shapes(np.uint8(im > threshold_high)))#, transform=src.transform)) stress_thresh_polys = [] for poly, value in stress_thresh_shapes: if(value == 1.0): print(len(poly['coordinates'])) poly['coordinates'] = [src.affine * xy for xy in poly['coordinates'][0]] stress_thresh_polys.append(Polygon(shell=poly['coordinates'])) area = 0 if (compute_area): print("computing area...\r") # compute polygon area def get_geom_area(geom): _geom_area = ops.transform( partial( pyproj.transform, pyproj.Proj(init='EPSG:4326'), pyproj.Proj( proj='aea', lat1=geom.bounds[1], lat2=geom.bounds[3])), geom) return(_geom_area.area) area = sum([get_geom_area(g) for g in stress_thresh_polys]) print(area) print("area: {}".format(area)) print('done.') with open(outfile_suffix + ".geojson", 'w') as gjf: geojson.dump(geojson.GeometryCollection(stress_thresh_polys), gjf) im = np.flip(im, 0) norm = Normalize(vmin=200, vmax=320, clip=False) # ARBITRARY VALUES im = Image.fromarray(np.uint8(plt.cm.viridis(norm(im)) * 255)) im.save(outfile_suffix + ".gif") with open(outfile_suffix + '.ref', 'w') as f: f.write("{}.gif,{},{},{},{},{}.geojson".format(basename(outfile_suffix), bounds.left, bounds.right, bounds.bottom, bounds.top, basename(outfile_suffix)))
def geojson(self): """ Property that returns a geojson.GeometryCollection object to the user Returns ------- geojson.GeometryCollection """ if geojson is not None: if self._geojson is None: self._geojson = geojson.GeometryCollection( [i.geojson for i in self.__collection] ) return self._geojson
def make_geo_coll(vehicle_id, limit): docs = get_vehicle_positions(vehicle_id, limit) coords = [] for d in docs: coords.append(tuple(d['location']['coordinates'])) gc = gj.GeometryCollection([gj.LineString(coords), gj.MultiPoint(coords)]) start = arrow.get(docs[0]['timestamp']).to('America/Chicago').isoformat() end = arrow.get(docs[-1]['timestamp']).to('America/Chicago').isoformat() fname = 'GC_{vid}@{start}<-->{end}.geojson'.format(vid=vehicle_id, start=start, end=end) with open(fname, 'w') as f: gj.dump(gc, f)
def test_geometrycollection(self): p1 = geojson.Point((-115.11, 37.11)) p2 = geojson.Point((-115.22, 37.22)) ln = geojson.LineString( [(-115.3, 37.3), (-115.4, 37.4), (-115.5, 37.5)]) g = geojson.MultiPolygon([ ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],), ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29)],)]) itr = coords(geojson.GeometryCollection([p1, p2, ln, g])) pairs = set(itr) self.assertEqual(pairs, set([ (-115.11, 37.11), (-115.22, 37.22), (-115.3, 37.3), (-115.4, 37.4), (-115.5, 37.5), (3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28), (23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29) ]))
def geometry_from_string(points): """Takes a string, returns a geometry object""" points = points.split(';') pnt_list = [tuple(map(float, reversed(point.split()[:2]))) for point in points] if len(pnt_list) == 1: geometry = geojson.GeometryCollection( [geojson.Point(pnt_list[0])]) elif is_polygon(pnt_list): # First and last point are same -> Polygon geometry = geojson.Polygon([pnt_list]) else: # First and last point not same -> LineString geometry = geojson.LineString(pnt_list) return geometry
def savegeojson(self): gc = geojson.GeometryCollection(self.geos[:10]) fc = geojson.FeatureCollection(self.geos[:]) # print 'gc: ', gc # print 'fc: ', fc # print 'len(gc): ', len(gc) # print 'len(fc): ', len(fc) tg = {} tg['type'] = 'Topology' tg['objects'] = {self.name:gc} fl = '../json/'+self.name+'.json' with open(fl, 'w') as outfile: #dump = geojson.dumps(gc) #rtg = (tg).replace('LineString','polyline') #json.dump(tg, outfile) json.dump(fc, outfile)
def as_geojson_geometry(geojson_dict): """ Return a mapping as a GeoJSON instance, converting Feature types to Geometry types. """ geoj = _parse_geojson_safe(geojson_dict) # Shapely cannot handle GeoJSON Features or FeatureCollections if isinstance(geoj, geojson.Feature): geoj = _parse_geojson_safe(geojson_dict["geometry"]) elif isinstance(geoj, geojson.FeatureCollection): features = [] for feature in geojson_dict.get("features", []): try: features.append(_parse_geojson_safe(feature["geometry"])) except (TypeError, KeyError, UnicodeEncodeError) as ex: raise ValueError( "feature in FeatureCollection not recognized as valid ({}): {}" .format(str(ex), feature)) geoj = geojson.GeometryCollection(features) return geoj
def test_geojson_geometry_collection(self): resource_ids = [ '81b24334a8fe31fbcf2c56de923c1523', # Polygon and Point '52691ff2fca1a0c6a73230fd7241131d' # MultiPolygon and Point ] for resource_id in resource_ids: geo_object = self.__to_geojson(id_request( locations_url, access_token, resource_id, {'geojson': 'true'})) geo_collection = geo_object.geometry self.assertTrue(geo_object.is_valid) self.assertIsInstance(geo_object, type(geojson.Feature())) self.assertIsInstance(geo_collection, type(geojson.GeometryCollection())) geo_types = [ type(geojson.Polygon()), type(geojson.MultiPolygon()), type(geojson.Point()) ] for geo in geo_collection.geometries: self.assertTrue(type(geo) in geo_types)
def _handle_wells_request(provider_id: str, well_names_str: str) -> flask.Response: LOGGER.debug(f"Handling well request: " f"provider_id={provider_id} " f"well_names_str={well_names_str} ") timer = PerfTimer() try: provider = self._id_to_provider_dict[provider_id] well_names_arr = well_names_str.split("~") # pylint: disable=bare-except except: LOGGER.error("Error decoding wells address") flask.abort(404) validate_geometry = True feature_arr = [] for wname in well_names_arr: well_path = provider.get_well_path(wname) coords = list( zip(well_path.x_arr, well_path.y_arr, well_path.z_arr)) # coords = coords[0::20] point = geojson.Point(coordinates=[coords[0][0], coords[0][1]], validate=validate_geometry) geocoll = geojson.GeometryCollection(geometries=[point]) feature = geojson.Feature(id=wname, geometry=geocoll, properties={"name": wname}) feature_arr.append(feature) featurecoll = geojson.FeatureCollection(features=feature_arr) response = flask.Response(geojson.dumps(featurecoll), mimetype="application/geo+json") LOGGER.debug(f"Request handled in: {timer.elapsed_s():.2f}s") return response
def get_geojson( self, well_names: List[str], surface_name: str, attribute: str = WellPickTableColumns.WELL, ) -> geojson.FeatureCollection: dframe = self.dframe.loc[ (self.dframe[WellPickTableColumns.WELL].isin(well_names)) & (self.dframe[WellPickTableColumns.HORIZON] == self.surface_name_mapper.get(surface_name, surface_name))] if dframe.empty: return {"type": "FeatureCollection", "features": []} validate_geometry = True feature_arr = [] for _, row in dframe.iterrows(): coords = [ row[WellPickTableColumns.X_UTME], row[WellPickTableColumns.Y_UTMN], ] # coords = coords[0::20] point = geojson.Point(coordinates=coords, validate=validate_geometry) geocoll = geojson.GeometryCollection(geometries=[point]) properties = { "name": row[WellPickTableColumns.WELL], "attribute": str(row[attribute]), } feature = geojson.Feature( id=row[WellPickTableColumns.WELL], geometry=geocoll, properties=properties, ) feature_arr.append(feature) featurecoll = geojson.FeatureCollection(features=feature_arr) return featurecoll
def test_geojson_geofield(self): self._publish_submit_geojson() dataid = self.xform.instances.all().order_by('id')[0].pk data_get = {"geo_field": 'location', "fields": 'today'} view = DataViewSet.as_view({'get': 'retrieve'}) request = self.factory.get('/', data=data_get, **self.extra) response = view(request, pk=self.xform.pk, dataid=dataid, format='geojson') self.assertEqual(response.status_code, 200) test_loc = geojson.Feature(geometry=geojson.GeometryCollection( [geojson.Point((36.787219, -1.294197))]), properties={ 'xform': self.xform.pk, 'id': dataid, u'today': '2015-01-15' }) if 'id' in test_loc: test_loc.pop('id') self.assertEqual(response.data, test_loc) view = DataViewSet.as_view({'get': 'list'}) request = self.factory.get('/', data=data_get, **self.extra) response = view(request, pk=self.xform.pk, format='geojson') self.assertEqual(response.status_code, 200) self.assertEquals(response.data['type'], 'FeatureCollection') self.assertEquals(len(response.data['features']), 4) self.assertEquals(response.data['features'][0]['type'], 'Feature') self.assertEquals( response.data['features'][0]['geometry']['geometries'][0]['type'], 'Point')
def test_geometry_collection(self): geometries = geojson.GeometryCollection() geometries.geometries = [ geojson.Point(coordinates=[ random.randint(-180, 180), random.randint(-90, 90) ]) for _ in xrange(10) ] self.assertTrue(geometries.is_valid()) multipolygon = geojson.MultiPolygon() multipolygon.coordinates = [[[[D('102.0'), D('2.0')], [D('103.0'), D('2.0')], [D('103.0'), D('3.0')], [D('102.0'), D('3.0')], [D('102.0'), D('2.0')]]], [[[D('100.0'), D('0.0')], [D('101.0'), D('0.0')], [D('101.0'), D('1.0')], [D('100.0'), D('1.0')], [D('100.0'), D('0.0')]], [[D('100.2'), D('0.2')], [D('100.8'), D('0.2')], [D('100.8'), D('0.8')], [D('100.2'), D('0.8')], [D('100.2'), D('0.2')]]]] geometries.geometries[4] = multipolygon multipolygon = geojson.MultiPolygon() multipolygon.coordinates = [[[[D('102.0'), D('2.0')], [D('103.0'), D('2.0')], [D('103.0'), D('3.0')], [D('102.0'), D('3.0')], [D('102.0'), D('2.0')]]]] geometries.geometries.append(multipolygon) self.assertTrue(geometries.is_valid()) self.assertEquals(len(geometries), 11) for idx, geometry in enumerate(geometries): self.assertDictEquals(geometry.to_dict(), geometries[idx].to_dict())
print "Altitude: " + str(alt_value) print "--- GPS ---" coord_pyexiv = (md['Exif.GPSInfo.GPSLatitude'].raw_value, md['Exif.GPSInfo.GPSLongitude'].raw_value, md['Exif.GPSInfo.GPSAltitude'].raw_value) # with pillow keys = get_exif(photo) coord_pillow = (keys.get('GPSInfo').get(2), keys.get('GPSInfo').get(4), keys.get('GPSInfo').get(6)) # prints print "\navec pyEXIF", coord_EXIF print "avec pyexiv2", coord_pyexiv print "avec pillow", coord_pillow # geojsonning li_pts.append(geojson.Point([lon_value, lat_value])) points = geojson.GeometryCollection(li_pts) with open('photo_maps.geojson', 'w') as out_geojson: geojson.dump(points, out_geojson) def main(): pass ################################################################################ ##### Stand alone execution ####### ################################### if __name__ == '__main__': main()
import json import sys import geojson data = json.load(sys.stdin) name = [] for name, name_data in data['Name'].items(): locations = [] for location in name_data['locations']: locations.append((float(location['latitude']), float(location['longitude']))) name.append(geojson.Feature(geometry=geojson.MultiPoint(locations), properties={'Name': name})) result = geojson.GeometryCollection(projects) geojson.dump(result, sys.stdout)
[[100.2, 0.2], [100.2, 0.8], [100.8, 0.8], [100.8, 0.2], [100.2, 0.2]], ], ] ) def test_MultiPolygon_valid(): roax.geo.MultiPolygon().validate(_multipolygon) def test_MultiPolygon_str_bin(): _test_str_bin(roax.geo.MultiPolygon(), _multipolygon) _geometrycollection = geojson.GeometryCollection( [geojson.Point([100.0, 0.0]), geojson.LineString([[101.0, 0.0], [102.0, 1.0]])] ) def test_GeometryCollection_valid(): roax.geo.GeometryCollection().validate(_geometrycollection) def test_GeometryCollection_str_bin(): _test_str_bin(roax.geo.GeometryCollection(), _geometrycollection) def test_Feature_valid(): roax.geo.Feature().validate( geojson.Feature( geometry=geojson.Point([102.0, 0.5]), properties={"prop0": "value0"}