File size: 2,313 Bytes
c2e4a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1a5d57
c2e4a2f
 
b1a5d57
c2e4a2f
 
b1a5d57
c2e4a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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)
    
    # Create route line
    line = staticmaps.Line(
        [staticmaps.create_latlng(lat, lng) for lat, lng in coords],
        color=staticmaps.BLUE,
        width=4
    )
    context.add_object(line)
    
    # Add start marker (green)
    start_marker = staticmaps.Marker(
        staticmaps.create_latlng(start_lat, start_lon),
        color=staticmaps.GREEN,
        size=12
    )
    context.add_object(start_marker)
    
    # Add end marker (red)
    end_marker = staticmaps.Marker(
        staticmaps.create_latlng(end_lat, end_lon),
        color=staticmaps.RED,
        size=12
    )
    context.add_object(end_marker)
    
    # Generate image and save to temp file
    image = context.render_pillow(500, 375)
    
    # Create unique temp file path
    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 to use a nice font, fallback to default
        try:
            font = ImageFont.truetype("Arial.ttf", 24)
        except:
            font = ImageFont.load_default()
        
        # Add title at top center
        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
        
        # Add background rectangle for better readability
        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