gauthamnairy commited on
Commit
8a8c13b
·
verified ·
1 Parent(s): ac5007c

Update backend/main.py

Browse files
Files changed (1) hide show
  1. backend/main.py +76 -52
backend/main.py CHANGED
@@ -4,29 +4,33 @@ from pydantic import BaseModel
4
  import httpx
5
  import pyproj
6
  from typing import List, Dict, Optional, Any
 
 
 
 
7
 
8
- app = FastAPI(title="Ground Elevation API")
9
 
10
  # Configure CORS
11
  app.add_middleware(
12
  CORSMiddleware,
13
- allow_origins=["*"], # Allows all origins
14
  allow_credentials=True,
15
- allow_methods=["*"], # Allows all methods
16
- allow_headers=["*"], # Allows all headers
17
  )
18
 
19
  # Define request and response models
20
  class CoordinateRequest(BaseModel):
21
  latitude: float
22
  longitude: float
23
- crs: str = "EPSG:4326" # Default to WGS84
24
 
25
  class ElevationResponse(BaseModel):
26
  latitude: float
27
  longitude: float
28
  elevation: float
29
- wgs84_latitude: float # Add WGS84 coordinates
30
  wgs84_longitude: float
31
  original_crs: str
32
 
@@ -34,17 +38,52 @@ class CRSInfo(BaseModel):
34
  code: str
35
  name: str
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  # Route for fetching elevation data
38
  @app.post("/api/elevation", response_model=ElevationResponse)
39
  async def get_elevation(request: CoordinateRequest):
40
- """Get elevation for a given coordinate pair"""
41
  try:
42
- # Convert from source CRS to WGS84 (EPSG:4326) if necessary
43
  wgs84_coords = convert_to_wgs84(request.longitude, request.latitude, request.crs)
44
-
45
- # Query Open-Meteo for elevation data
46
  elevation = await query_open_meteo(wgs84_coords[1], wgs84_coords[0])
47
-
48
  return ElevationResponse(
49
  latitude=request.latitude,
50
  longitude=request.longitude,
@@ -56,11 +95,34 @@ async def get_elevation(request: CoordinateRequest):
56
  except Exception as e:
57
  raise HTTPException(status_code=500, detail=str(e))
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  # Route for fetching CRS list
60
  @app.get("/api/crs-list", response_model=List[CRSInfo])
61
  async def get_crs_list():
62
- """Get a list of supported coordinate reference systems"""
63
- # List of common CRS systems
64
  crs_list = [
65
  {"code": "EPSG:4326", "name": "WGS 84"},
66
  {"code": "EPSG:3857", "name": "Web Mercator"},
@@ -73,47 +135,9 @@ async def get_crs_list():
73
  ]
74
  return crs_list
75
 
76
- # Convert coordinates from source CRS to WGS84
77
- def convert_to_wgs84(x, y, source_crs):
78
- """Convert coordinates from source CRS to WGS84"""
79
- # If already WGS84, return as is
80
- if source_crs == "EPSG:4326":
81
- return (x, y)
82
-
83
- try:
84
- # Create transformation
85
- transformer = pyproj.Transformer.from_crs(source_crs, "EPSG:4326", always_xy=True)
86
- # Transform coordinates
87
- lon, lat = transformer.transform(x, y)
88
- return (lon, lat)
89
- except Exception as e:
90
- raise Exception(f"Coordinate transformation error: {str(e)}")
91
-
92
- # Query elevation from Open-Meteo API
93
- async def query_open_meteo(lat, lon):
94
- """Query Open-Meteo for elevation data"""
95
- url = f"https://api.open-meteo.com/v1/elevation?latitude={lat}&longitude={lon}"
96
-
97
- async with httpx.AsyncClient() as client:
98
- try:
99
- response = await client.get(url)
100
- response.raise_for_status()
101
- data = response.json()
102
-
103
- # Extract elevation from response
104
- if "elevation" in data and isinstance(data["elevation"], list) and len(data["elevation"]) > 0:
105
- return float(data["elevation"][0])
106
- else:
107
- raise Exception("No elevation data found in API response")
108
- except httpx.HTTPStatusError as e:
109
- raise Exception(f"Elevation API error: {str(e)}")
110
- except Exception as e:
111
- raise Exception(f"Error querying elevation: {str(e)}")
112
-
113
- # Add additional health check endpoint
114
  @app.get("/api/health")
115
  async def health_check():
116
- """Health check endpoint"""
117
  return {"status": "ok"}
118
 
119
  if __name__ == "__main__":
 
4
  import httpx
5
  import pyproj
6
  from typing import List, Dict, Optional, Any
7
+ from distance import calculate_distance
8
+ from area import calculate_area
9
+ from coordinate_converter import convert_coordinates
10
+ from terrain import extract_terrain_data
11
 
12
+ app = FastAPI(title="GIS Tools API")
13
 
14
  # Configure CORS
15
  app.add_middleware(
16
  CORSMiddleware,
17
+ allow_origins=["*"],
18
  allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
  )
22
 
23
  # Define request and response models
24
  class CoordinateRequest(BaseModel):
25
  latitude: float
26
  longitude: float
27
+ crs: str = "EPSG:4326"
28
 
29
  class ElevationResponse(BaseModel):
30
  latitude: float
31
  longitude: float
32
  elevation: float
33
+ wgs84_latitude: float
34
  wgs84_longitude: float
35
  original_crs: str
36
 
 
38
  code: str
39
  name: str
40
 
41
+ class DistanceRequest(BaseModel):
42
+ point1: CoordinateRequest
43
+ point2: CoordinateRequest
44
+
45
+ class AreaRequest(BaseModel):
46
+ coordinates: List[CoordinateRequest]
47
+
48
+ class TerrainRequest(BaseModel):
49
+ latitude: float
50
+ longitude: float
51
+ crs: str = "EPSG:4326"
52
+
53
+ # Helper: Convert to WGS84
54
+ def convert_to_wgs84(lon, lat, source_crs):
55
+ if source_crs == "EPSG:4326":
56
+ return (lon, lat)
57
+ try:
58
+ transformer = pyproj.Transformer.from_crs(source_crs, "EPSG:4326", always_xy=True)
59
+ lon, lat = transformer.transform(lon, lat)
60
+ return (lon, lat)
61
+ except Exception as e:
62
+ raise Exception(f"Coordinate transformation error: {str(e)}")
63
+
64
+ # Helper: Query Open-Meteo
65
+ async def query_open_meteo(lat, lon):
66
+ url = f"https://api.open-meteo.com/v1/elevation?latitude={lat}&longitude={lon}"
67
+ async with httpx.AsyncClient() as client:
68
+ try:
69
+ response = await client.get(url)
70
+ response.raise_for_status()
71
+ data = response.json()
72
+ if "elevation" in data and isinstance(data["elevation"], list) and len(data["elevation"]) > 0:
73
+ return float(data["elevation"][0])
74
+ else:
75
+ raise Exception("No elevation data found in API response")
76
+ except httpx.HTTPStatusError as e:
77
+ raise Exception(f"Elevation API error: {str(e)}")
78
+ except Exception as e:
79
+ raise Exception(f"Error querying elevation: {str(e)}")
80
+
81
  # Route for fetching elevation data
82
  @app.post("/api/elevation", response_model=ElevationResponse)
83
  async def get_elevation(request: CoordinateRequest):
 
84
  try:
 
85
  wgs84_coords = convert_to_wgs84(request.longitude, request.latitude, request.crs)
 
 
86
  elevation = await query_open_meteo(wgs84_coords[1], wgs84_coords[0])
 
87
  return ElevationResponse(
88
  latitude=request.latitude,
89
  longitude=request.longitude,
 
95
  except Exception as e:
96
  raise HTTPException(status_code=500, detail=str(e))
97
 
98
+ # Route for calculating distance
99
+ @app.post("/api/distance")
100
+ async def calculate_distance_route(request: DistanceRequest):
101
+ # Extract coordinates and CRS
102
+ p1 = (request.point1.longitude, request.point1.latitude, request.point1.crs)
103
+ p2 = (request.point2.longitude, request.point2.latitude, request.point2.crs)
104
+ return {"distance": calculate_distance(p1, p2)}
105
+
106
+ # Route for calculating area
107
+ @app.post("/api/area")
108
+ async def calculate_area_route(request: AreaRequest):
109
+ # Convert CoordinateRequest list to list of (lon, lat, crs)
110
+ coords = [(c.longitude, c.latitude, c.crs) for c in request.coordinates]
111
+ return {"area": calculate_area(coords)}
112
+
113
+ # Route for converting coordinates
114
+ @app.post("/api/coordinate-converter")
115
+ async def coordinate_converter_route(request: CoordinateRequest):
116
+ return convert_coordinates(request.longitude, request.latitude, request.crs)
117
+
118
+ # Route for extracting terrain data
119
+ @app.post("/api/terrain")
120
+ async def terrain_data_route(request: TerrainRequest):
121
+ return await extract_terrain_data(request.latitude, request.longitude, request.crs)
122
+
123
  # Route for fetching CRS list
124
  @app.get("/api/crs-list", response_model=List[CRSInfo])
125
  async def get_crs_list():
 
 
126
  crs_list = [
127
  {"code": "EPSG:4326", "name": "WGS 84"},
128
  {"code": "EPSG:3857", "name": "Web Mercator"},
 
135
  ]
136
  return crs_list
137
 
138
+ # Health check endpoint
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  @app.get("/api/health")
140
  async def health_check():
 
141
  return {"status": "ok"}
142
 
143
  if __name__ == "__main__":