-
Notifications
You must be signed in to change notification settings - Fork 1
F4KRP-125 Get polyline from stops #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
eddywang4340
wants to merge
13
commits into
main
Choose a base branch
from
eddy/get-polyline-from-stops
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+142
−0
Open
Changes from 9 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
7bcdf7f
added migration for new field in routes
eddywang4340 18dc879
added migration for new field in routes
eddywang4340 7a07450
Merge branch 'eddy/get-polyline-from-stops' of github.com:uwblueprint…
eddywang4340 49fae09
fixed mypy complaining error
eddywang4340 38251ba
added route utils file
eddywang4340 93e219f
fixed migrations diverging
eddywang4340 db35979
fixed test typo
eddywang4340 11f3fd0
holy shit it worked
eddywang4340 eca355a
fixed lint issues
eddywang4340 c3537ed
removed test file
eddywang4340 2533ca8
Merge branch 'main' of https://github.com/uwblueprint/food4kids into …
ludavidca e208fde
Fixing Migrations
ludavidca ed832a0
Pulling in main should fix the mypy issues
ludavidca File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from fastapi import HTTPException | ||
| from google.api_core import exceptions as google_exceptions | ||
| from google.api_core.client_options import ClientOptions | ||
| from google.maps import routing_v2 | ||
|
|
||
| from app.config import settings | ||
|
|
||
| if TYPE_CHECKING: | ||
| from app.models.location import Location | ||
|
|
||
|
|
||
| async def fetch_route_polyline( | ||
| locations: list["Location"], | ||
| warehouse_lat: float, | ||
| warehouse_lon: float, | ||
| ends_at_warehouse: bool, | ||
| ) -> tuple[str, float]: | ||
| """Fetch encoded polyline from Google Maps Routes API. | ||
|
|
||
| Args: | ||
| locations: Ordered list of Location objects (route stops) | ||
| warehouse_lat: Warehouse latitude | ||
| warehouse_lon: Warehouse longitude | ||
| ends_at_warehouse: If True, route returns to warehouse | ||
|
|
||
| Returns: | ||
| Tuple with encoded polyline string and total distance in kilometers | ||
|
|
||
| Raises: | ||
| HTTPException: If API request fails | ||
| ValueError: If locations list is empty or API key not configured | ||
| """ | ||
| if not locations: | ||
| raise ValueError("Locations list cannot be empty") | ||
|
|
||
| if not settings.google_maps_api_key: | ||
| raise ValueError("Google Maps API key is not configured in settings") | ||
|
|
||
| # Build waypoints | ||
| origin = routing_v2.Waypoint( | ||
| location=routing_v2.Location( | ||
| lat_lng={"latitude": warehouse_lat, "longitude": warehouse_lon} | ||
| ) | ||
| ) | ||
|
|
||
| intermediates = [ | ||
| routing_v2.Waypoint( | ||
| location=routing_v2.Location( | ||
| lat_lng={"latitude": loc.latitude, "longitude": loc.longitude} | ||
| ) | ||
| ) | ||
| for loc in locations | ||
| ] | ||
|
|
||
| if ends_at_warehouse: | ||
| destination = origin | ||
| waypoints_to_use = intermediates | ||
| else: | ||
| if len(intermediates) > 1: | ||
| waypoints_to_use = intermediates[:-1] | ||
| destination = intermediates[-1] | ||
| else: | ||
| waypoints_to_use = None | ||
| destination = intermediates[0] | ||
|
|
||
| # Build request | ||
| request = routing_v2.ComputeRoutesRequest( | ||
| origin=origin, | ||
| destination=destination, | ||
| intermediates=waypoints_to_use, | ||
| travel_mode=routing_v2.RouteTravelMode.DRIVE, | ||
| routing_preference=routing_v2.RoutingPreference.TRAFFIC_AWARE, | ||
| ) | ||
|
|
||
| try: | ||
| # Create client with API key | ||
| options = ClientOptions(api_key=settings.google_maps_api_key) | ||
| client = routing_v2.RoutesAsyncClient(client_options=options) | ||
|
|
||
| response = await client.compute_routes( | ||
| request=request, | ||
| metadata=[ | ||
| ( | ||
| "x-goog-fieldmask", | ||
| "routes.polyline.encodedPolyline,routes.distanceMeters", | ||
| ) | ||
| ], | ||
| ) | ||
|
|
||
| if not response.routes: | ||
| raise HTTPException( | ||
| status_code=500, | ||
| detail="Google Maps API returned no routes", | ||
| ) | ||
|
|
||
| route = response.routes[0] | ||
| polyline = route.polyline.encoded_polyline | ||
| distance_km = route.distance_meters / 1000.0 | ||
|
|
||
| return polyline, distance_km | ||
|
|
||
| except google_exceptions.GoogleAPICallError as e: | ||
| raise HTTPException( | ||
| status_code=503, detail=f"Google Maps API error: {e!s}" | ||
| ) from e | ||
| except google_exceptions.RetryError as e: | ||
| raise HTTPException(status_code=504, detail="Request timed out") from e | ||
| except Exception as e: | ||
| raise HTTPException(status_code=500, detail=f"Unexpected error: {e!s}") from e |
28 changes: 28 additions & 0 deletions
28
backend/python/migrations/versions/eb010a6ed5ad_added_ends_at_warehouse_to_route_model.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| """added ends_at_warehouse to route model | ||
|
|
||
| Revision ID: eb010a6ed5ad | ||
| Revises: 7af7d4689b08 | ||
| Create Date: 2025-12-01 00:31:47.827096 | ||
|
|
||
| """ | ||
| from alembic import op | ||
| import sqlalchemy as sa | ||
|
|
||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = 'eb010a6ed5ad' | ||
| down_revision = 'b1c2d3e4f5a6' | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade(): | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.add_column('routes', sa.Column('ends_at_warehouse', sa.Boolean(), nullable=False, server_default='false')) | ||
| # ### end Alembic commands ### | ||
|
|
||
|
|
||
| def downgrade(): | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.drop_column('routes', 'ends_at_warehouse') | ||
| # ### end Alembic commands ### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| from uuid import uuid4 | ||
|
|
||
| import pytest | ||
|
|
||
| from app.models.location import Location | ||
| from app.utilities.routes_utils import fetch_route_polyline | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_fetch_route_polyline_with_return(): | ||
| """Test fetching polyline with return to warehouse.""" | ||
|
|
||
| # Create mock locations | ||
| loc1 = Location( | ||
| location_group_id=uuid4(), | ||
| contact_name="Test 1 Loc 1", | ||
| address="123 Test St", | ||
| phone_number="123-456-7890", | ||
| longitude=-80.50, | ||
| latitude=43.45, | ||
| halal=True, | ||
| dietary_restrictions="", | ||
| num_boxes=5, | ||
| notes="", | ||
| ) | ||
|
|
||
| loc2 = Location( | ||
| location_group_id=uuid4(), | ||
| contact_name="Test 1 Loc 2", | ||
| address="124 Test St", | ||
| phone_number="124-456-7890", | ||
| longitude=-80.51, | ||
| latitude=43.46, | ||
| halal=True, | ||
| dietary_restrictions="", | ||
| num_boxes=5, | ||
| notes="", | ||
| ) | ||
|
|
||
| polyline, distance_km = await fetch_route_polyline( | ||
| locations=[loc1, loc2], | ||
| warehouse_lat=43.40, | ||
| warehouse_lon=-80.46, | ||
| ends_at_warehouse=True, | ||
| ) | ||
|
|
||
| assert isinstance(polyline, str) | ||
| assert distance_km > 0.0 | ||
| assert len(polyline) > 0 | ||
| print(f"Encoded Polyline: {polyline}") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For context, these lines were added to fix this MyPy error:
Unexpected keyword argument "table" for "__init_subclass__" of "object"Mypy