File size: 924 Bytes
ac5007c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List

router = APIRouter()

class PolygonCoordinates(BaseModel):
    coordinates: List[List[float]]  # List of [longitude, latitude] pairs

@router.post("/api/calculate-area")
async def calculate_area(polygon: PolygonCoordinates):
    """Calculate the area of a polygon defined by a set of coordinates."""
    if len(polygon.coordinates) < 3:
        raise HTTPException(status_code=400, detail="At least three coordinates are required to form a polygon.")

    # Using the Shoelace formula to calculate the area
    area = 0.0
    n = len(polygon.coordinates)
    
    for i in range(n):
        x1, y1 = polygon.coordinates[i]
        x2, y2 = polygon.coordinates[(i + 1) % n]  # Wrap around to the first point
        area += x1 * y2 - x2 * y1
    
    area = abs(area) / 2.0
    return {"area": area}