# generated with chatgpt
import googlemaps
import math
from random import uniform
def generate_random_coordinates(lat, lon, max_distance_km):
"""Generate a random point within a circular area defined by max_distance_km."""
# Random angle
theta = uniform(0, 2 * math.pi)
# Random radius, weighted by area
r = max_distance_km * math.sqrt(uniform(0, 1))
# Convert polar to cartesian
dx = r * math.cos(theta)
dy = r * math.sin(theta)
# Earth's radius in kilometers
earth_radius = 6371
# New latitude in degrees
new_lat = lat + (dy / earth_radius) * (180 / math.pi)
# New longitude in degrees, taking into account the latitude compression
new_lon = lon + (dx / earth_radius) * (180 / math.pi) / math.cos(lat * math.pi/180)
return new_lat, new_lon
def create_route_link(start_location, distance_km, api_key):
gmaps = googlemaps.Client(key=api_key)
initial_location = gmaps.geocode(start_location)[0]['geometry']['location']
lat, lon = initial_location['lat'], initial_location['lng']
# Determine the number of segments; aiming to use about 10 waypoints
num_segments = 10
segment_length = (distance_km / 2) / num_segments # Half the route outwards
waypoints = []
current_lat, current_lon = lat, lon
# Generate waypoints
for _ in range(num_segments):
new_lat, new_lon = generate_random_coordinates(current_lat, current_lon, segment_length)
waypoints.append((new_lat, new_lon))
current_lat, current_lon = new_lat, new_lon
# Generate the return route directly without additional waypoints to avoid the limit
directions_result = gmaps.directions((lat, lon),
(lat, lon),
mode="walking",
waypoints=[(lat, lon) for lat, lon in waypoints],
optimize_waypoints=True)
# Construct Google Maps link for the route
start = f"{lat},{lon}"
waypoints_param = '|'.join(f"{lat},{lon}" for lat, lon in waypoints)
return f"https://www.google.com/maps/dir/?api=1&origin={start}&destination={start}&waypoints={waypoints_param}&travelmode=walking"
### Solara code - not AI generated
import os
import solara
import solara.lab
GOOGLE_MAPS_API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY", "AIzaSyBC-Cj54Xh4mM1E83WBof8ngLnJBUmzpb8")
assert GOOGLE_MAPS_API_KEY, "Please set a key"
start_location = solara.reactive("Groningen, Netherlands")
desired_distance_km = solara.reactive(10.0)
@solara.lab.task
async def generate_route(key):
return create_route_link(start_location.value, desired_distance_km.value, key)
@solara.component
def TrailGeneratorApp(key=GOOGLE_MAPS_API_KEY):
solara.InputText("Start location", start_location)
solara.InputFloat("Desired distance (km)", desired_distance_km)
solara.Button("Generate route", on_click=lambda: generate_route(key), icon_name="mdi-google-maps", color="primary")
solara.ProgressLinear(generate_route.pending)
if generate_route.error:
solara.Error(repr(generate_route.exception))
if generate_route.value:
solara.Button(label="View route", href=generate_route.value, target="_blank", icon_name="mdi-walk",
outlined=True, color="primary")
page = TrailGeneratorApp()