diff --git a/geoapi/src/api_functions.py b/geoapi/src/api_functions.py index 3fb0422..fe6070f 100644 --- a/geoapi/src/api_functions.py +++ b/geoapi/src/api_functions.py @@ -1,3 +1,5 @@ +import json + from src import db_tools @@ -10,6 +12,17 @@ def get_region_stats(region: str) -> dict: def get_nearby_fields(x: float, y: float, distance: int) -> dict: - for row in db_tools.get_nearby_fields_db(x, y, distance): - print(row) - print(type(row)) \ No newline at end of file + query_result = db_tools.get_nearby_fields_db(x, y, distance) + GeoJSON = create_GeoJSON(query_result) + return GeoJSON + + +def create_GeoJSON(query_result) -> dict: + features = [] + for row in query_result: + geometry = json.loads(row[5]) + properties = {"crop": row[1], "productivity_estimation": row[2], "region_code": row[4], "area_ha": row[3]} + feature = {"type": "Feature", "id": row[0], "geometry": geometry, "properties": properties} + features.append(feature) + GeoJSON = {"type": "FeatureCollection", "features": features} + return GeoJSON diff --git a/geoapi/src/db_tools.py b/geoapi/src/db_tools.py index a1f279a..1ecce26 100644 --- a/geoapi/src/db_tools.py +++ b/geoapi/src/db_tools.py @@ -48,12 +48,8 @@ def get_weighted_average_yield_per_hectare_db(region: str) -> float: def get_nearby_fields_db(x: float, y: float, distance: int): with engine.connect() as conn: - # # initialize the Metadata Object - # meta = MetaData() - # # create a table schema - # france = Table('france', meta, schema='france', autoload_with=engine) sql = text(f""" - Select * + Select id, crop, productivity, area_ha, region, ST_AsGeoJSON(fr.wkb_geometry) FROM {os.getenv('DB_SCHEMA_NAME')}.{os.getenv('DB_TABLE_NAME')} as fr WHERE ST_DWithin(fr.wkb_geometry::geography, (ST_SetSRID(ST_MakePoint({x}, {y}), 4326))::geography, {distance}); """) diff --git a/queries.sql b/queries.sql index 3c62f3f..9719270 100644 --- a/queries.sql +++ b/queries.sql @@ -27,6 +27,6 @@ SELECT Find_SRID('france', 'france', 'wkb_geometry'); --4326 ---task 1 -Select * +Select id, crop, productivity, area_ha, region, ST_AsGeoJSON(fr.wkb_geometry) FROM france.france as fr -WHERE ST_DWithin(fr.wkb_geometry::geography, (ST_SetSRID(ST_MakePoint(1.3373403, 49.9948281), 4326))::geography, 500); \ No newline at end of file +WHERE ST_DWithin(fr.wkb_geometry::geography, (ST_SetSRID(ST_MakeP1.3373403, 49.9948281oint(), 4326))::geography, 500);