#!/usr/bin/env python3 """Render a walking route between two points on OSM tiles. Usage: route_image.py LAT1 LON1 LAT2 LON2 OUT.png [START_LABEL] [END_LABEL]""" import io, json, math, sys, urllib.request from PIL import Image, ImageDraw, ImageFont la1, lo1, la2, lo2 = map(float, sys.argv[1:5]); out = sys.argv[5] l1 = sys.argv[6] if len(sys.argv) > 6 else 'BAŞLANGIÇ' l2 = sys.argv[7] if len(sys.argv) > 7 else 'HEDEF' UA = {'User-Agent': 'hermes-maps/1.0'} get = lambda u: urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=20).read() r = json.loads(get(f'https://routing.openstreetmap.de/routed-foot/route/v1/foot/{lo1},{la1};{lo2},{la2}?overview=full&geometries=geojson'))['routes'][0] z = 17 def px(lon, lat): n = 2 ** z * 256; lr = math.radians(lat) return (lon + 180) / 360 * n, (1 - math.log(math.tan(lr) + 1 / math.cos(lr)) / math.pi) / 2 * n P = [px(*p) for p in r['geometry']['coordinates']] pad = 120 x0, x1 = min(p[0] for p in P) - pad, max(p[0] for p in P) + pad y0, y1 = min(p[1] for p in P) - pad, max(p[1] for p in P) + pad tx0, ty0 = int(x0 // 256), int(y0 // 256) img = Image.new('RGB', ((int(x1 // 256) - tx0 + 1) * 256, (int(y1 // 256) - ty0 + 1) * 256)) # OSM tile usage policy (https://operations.osmfoundation.org/policies/tiles/): keep requests low, # send a real User-Agent, cache tiles you reuse and do not bulk-download. For heavy use run your own tile server. for tx in range(tx0, int(x1 // 256) + 1): for ty in range(ty0, int(y1 // 256) + 1): img.paste(Image.open(io.BytesIO(get(f'https://tile.openstreetmap.org/{z}/{tx}/{ty}.png'))).convert('RGB'), ((tx - tx0) * 256, (ty - ty0) * 256)) d = ImageDraw.Draw(img) Q = [(x - tx0 * 256, y - ty0 * 256) for x, y in P] d.line(Q, fill=(30, 100, 255), width=8, joint='curve') FP = '/System/Library/Fonts/Supplemental/Arial Bold.ttf' try: F, S = ImageFont.truetype(FP, 22), ImageFont.truetype(FP, 16) except OSError: F = S = ImageFont.load_default() for (x, y), c, t in [(Q[0], (0, 150, 0), l1), (Q[-1], (210, 0, 0), l2)]: d.ellipse([x - 12, y - 12, x + 12, y + 12], fill=c, outline='white', width=3) d.text((x + 16, y - 12), t, font=F, fill=c, stroke_width=3, stroke_fill='white') img = img.crop((int(x0 - tx0 * 256), int(y0 - ty0 * 256), int(x1 - tx0 * 256), int(y1 - ty0 * 256))) d = ImageDraw.Draw(img) d.text((8, img.height - 24), f"© OpenStreetMap | yürüyüş ~{round(r['distance'])} m, ~{round(r['duration']/60)} dk", font=S, fill='black', stroke_width=2, stroke_fill='white') img.save(out); print(out, img.size, round(r['distance']), 'm')