def geo_row_to_geojson(row, _, __): """Convert a geopandas dataframe row to a geojson format object. Converts all datetimes to epoch seconds. geo_properties and precision inputs are ignored """ # Let pandas handle json serialization, except for the geojson object shapely_geo_object = row['geometry'] row_json = json.loads(row.drop('geometry').to_json(date_format='epoch', date_unit='s')) # Convert shapely object to a geojson object geometry = geojson.GeoJSON(shapely.geometry.mapping(shapely_geo_object)) return geojson.Feature(geometry=geometry, properties={key: row_json[key] for key in row_json.keys()})
async def test_geo_result(connection, universal_access_token, flowapi_url): query = flowclient.joined_spatial_aggregate( connection=connection(url=flowapi_url, token=universal_access_token), **{ "locations": flowclient.daily_location_spec( date="2016-01-01", aggregation_unit="admin3", method="last" ), "metric": flowclient.handset_spec( start_date="2016-01-01", end_date="2016-01-02", characteristic="brand", method="last", ), "method": "distr", }, ) try: result = await query.get_result(format="geojson") except TypeError: result = query.get_result(format="geojson") assert geojson.GeoJSON(result).is_valid
def _read_geometries( shape: Union[str, Path], crs: Optional[Union[str, int, dict]] = None ) -> Tuple[List[geojson.geometry.Geometry], rasterio.crs.CRS]: """ A decorator to perform a check to verify a geometry is valid. Returns the function with geom set to the shapely Shape object. """ try: if shape is None: raise ValueError except (KeyError, ValueError): logging.exception("No shape provided.") raise geom = list() geometry_types = list() try: with fiona.open(shape) as fio: logging.info("Vector read OK.") if crs: shape_crs = rasterio.crs.CRS.from_user_input(crs) else: shape_crs = rasterio.crs.CRS(fio.crs or 4326) for i, feat in enumerate(fio): g = geojson.GeoJSON(feat) geom.append(g["geometry"]) geometry_types.append(g["geometry"]["type"]) except fiona.errors.DriverError: logging.exception("Unable to read shape.") raise if len(geom): logging.info("Shapes found are {}.".format(", ".join( set(geometry_types)))) return geom, shape_crs else: raise RuntimeError("No geometries found.")
def test_GeoJSON(self): self.assertEqual(None, geojson.GeoJSON().__geo_interface__) self.assertEqual({"type": "GeoJSON"}, to_mapping(geojson.GeoJSON()))
def generate_areal_stats(self, areal_option, query_object, wbpm_calc): """Calculates several statistics for the Water Productivity calculated raster for a chosen dataset / name Args: areal_option (TYPE): Description query_object (TYPE): Description wbpm_calc (TYPE): Description Returns: TYPE: Description """ num_areas = 0 if areal_option == 'c': try: calculation_area = WaterProductivityCalc._COUNTRIES.filter( ee.Filter.eq('iso3', query_object)) num_areas = calculation_area.size().getInfo() geom = calculation_area.geometry() finally: error = Exception('no country') elif areal_option == 'w': try: calculation_area = WaterProductivityCalc._WSHEDS.filter( ee.Filter.eq('MAJ_NAME', query_object)) num_areas = calculation_area.size().getInfo() geom = calculation_area.geometry() finally: error = Exception('no watershed') elif areal_option == 'g': try: geojson_raw = {"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}}, "features": [{"type": "Feature", "properties": {"area": "user_defined"}, "geometry": {"type": "Polygon", "coordinates": [[[8.72, 12.28], [29.34, 0.92], [20.63, -6.24], [8.72, 12.28]]]} } ] } # from IPython import embed # embed() if isinstance(geojson.GeoJSON(query_object), geojson.GeoJSON): if query_object['type'] == 'FeatureCollection': data = geojson.FeatureCollection( query_object['features']) geom = data['features'][0]['geometry'] if len(geom) > 0: num_areas = 1 finally: error = Exception('User defined area seems empty') if num_areas > 0: means = wbpm_calc.reduceRegion( reducer=ee.Reducer.mean(), geometry=geom, scale=self.scale_calc, maxPixels=1e9 ) mean = means.getInfo() reducers_min_max_sum = ee.Reducer.minMax().combine( reducer2=ee.Reducer.sum(), sharedInputs=True ) # Use the combined reducer to get the min max and SD of the image. stats = wbpm_calc.reduceRegion( reducer=reducers_min_max_sum, bestEffort=True, geometry=geom, scale=self.scale_calc ) min_max_sum = stats.getInfo() statistics_for_chosen_area = {} statistics_for_chosen_area['response'] = {} statistics_for_chosen_area['response']['name'] = query_object if areal_option == 'c': statistics_for_chosen_area['response']['iso3'] = calculation_area.getInfo()[ 'features'][0]['properties']['iso3'] statistics_for_chosen_area['response']['gaul_code'] = calculation_area.getInfo()[ 'features'][0]['properties']['gaul_code'] elif areal_option == 'w': statistics_for_chosen_area['response']['wshed_code'] = int( calculation_area.getInfo()['features'][0]['properties']['MAJ_BAS']) statistics_for_chosen_area['response']['wapor_code'] = calculation_area.getInfo()[ 'features'][0]['properties']['WaPOR_bas'] statistics_for_chosen_area['response']['stats'] = {} statistics_for_chosen_area['response']['stats']['min'] = min_max_sum.pop( 'b1_min') statistics_for_chosen_area['response']['stats']['sum'] = min_max_sum.pop( 'b1_sum') statistics_for_chosen_area['response']['stats']['max'] = min_max_sum.pop( 'b1_max') statistics_for_chosen_area['response']['stats']['mean'] = mean.pop( 'b1') return statistics_for_chosen_area else: self.L1_logger.error("Error: %s named %s" % (error, query_object)) return error
#!/usr/bin/env python3 import geojson import json import sys from geojson_rewind import rewind with open(sys.argv[1]) as json_file: data = json.load(json_file) if 'crs' in data: del data['crs'] data = rewind(data) widget = geojson.GeoJSON(data) widget.is_valid widget.errors() print(widget)