|
import os |
|
import uuid |
|
import tempfile |
|
import staticmaps |
|
from PIL import Image |
|
|
|
|
|
TEMP_DIR = tempfile.mkdtemp(prefix="geocalc_") |
|
|
|
|
|
def generate_route_image_file(coords, start_lat, start_lon, end_lat, end_lon): |
|
"""Generate route image and save to temp file.""" |
|
context = staticmaps.Context() |
|
context.set_tile_provider(staticmaps.tile_provider_OSM) |
|
|
|
|
|
line = staticmaps.Line( |
|
[staticmaps.create_latlng(lat, lng) for lat, lng in coords], |
|
color=staticmaps.BLUE, |
|
width=4 |
|
) |
|
context.add_object(line) |
|
|
|
|
|
start_marker = staticmaps.Marker( |
|
staticmaps.create_latlng(start_lat, start_lon), |
|
color=staticmaps.GREEN, |
|
size=12 |
|
) |
|
context.add_object(start_marker) |
|
|
|
|
|
end_marker = staticmaps.Marker( |
|
staticmaps.create_latlng(end_lat, end_lon), |
|
color=staticmaps.RED, |
|
size=12 |
|
) |
|
context.add_object(end_marker) |
|
|
|
|
|
image = context.render_pillow(500, 375) |
|
|
|
|
|
filename = f"route_{uuid.uuid4().hex[:8]}.webp" |
|
filepath = os.path.join(TEMP_DIR, filename) |
|
|
|
image.save(filepath, format='WEBP', quality=85, optimize=True) |
|
return filepath |
|
|
|
|
|
def load_image_with_title(image_path, custom_title=None): |
|
"""Load image from path and optionally add custom title.""" |
|
image = Image.open(image_path) |
|
|
|
if custom_title: |
|
from PIL import ImageDraw, ImageFont |
|
draw = ImageDraw.Draw(image) |
|
|
|
|
|
try: |
|
font = ImageFont.truetype("Arial.ttf", 24) |
|
except: |
|
font = ImageFont.load_default() |
|
|
|
|
|
text_bbox = draw.textbbox((0, 0), custom_title, font=font) |
|
text_width = text_bbox[2] - text_bbox[0] |
|
x = (image.width - text_width) // 2 |
|
y = 10 |
|
|
|
|
|
padding = 5 |
|
draw.rectangle([x-padding, y-padding, x+text_width+padding, y+text_bbox[3]+padding], |
|
fill="white", outline="black") |
|
draw.text((x, y), custom_title, fill="black", font=font) |
|
|
|
return image |