Skip to content

Instantly share code, notes, and snippets.

@georgewhewell
Created February 17, 2020 20:34
Show Gist options
  • Save georgewhewell/e8667236bffabe5b472b36d338f4f71c to your computer and use it in GitHub Desktop.
Save georgewhewell/e8667236bffabe5b472b36d338f4f71c to your computer and use it in GitHub Desktop.
import math
from time import sleep
from urllib.request import Request, urlopen
from PIL import Image
ZOOM_SIZE = 16
TILE_SIZE = 256
TILE_URL = "https://a.tile.openstreetmap.org/{}/{}/{}.png"
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n
return (xtile, ytile)
def get_img(x, y):
request = Request(TILE_URL.format(ZOOM_SIZE, x, y))
request.add_header('User-Agent', 'Maptthing')
return urlopen(request)
def stitch(lat, lng):
xtile, ytile = deg2num(lat, lng, ZOOM_SIZE)
print(f"{xtile}, {ytile}")
stitched = Image.new('RGB', (TILE_SIZE * 3, TILE_SIZE * 3))
for i, x in enumerate(range(int(xtile-1), int(xtile+2))):
for j, y in enumerate(range(int(ytile-1), int(ytile+2))):
sleep(1)
img = Image.open(get_img(x, y))
print(f"saving at {x} at {i*TILE_SIZE}, {y} at {j*TILE_SIZE}")
stitched.paste(img, box=(i*TILE_SIZE, j*TILE_SIZE))
xoffset = xtile - (x - (TILE_SIZE * 2)) + (xtile % 1)
yoffset = ytile - (y - (TILE_SIZE * 2)) + (ytile % 1)
print(f"cropping: from {xoffset} {yoffset}")
box = (xoffset - TILE_SIZE / 2, yoffset - TILE_SIZE / 2, xoffset + TILE_SIZE / 2, yoffset + TILE_SIZE /2)
print(f"box: {box}")
cropped = stitched.crop(box)
cropped.save('out.png')
stitch(51.471539,-0.0931495)
@tmellan
Copy link

tmellan commented Feb 17, 2020

def stitch2(lat, lng):
    xtile, ytile = deg2num(lat, lng, ZOOM_SIZE)
    print(f"{xtile}, {ytile}")
    stitched = Image.new('RGB', (TILE_SIZE * 3, TILE_SIZE * 3))
    for i, x in enumerate(range(int(xtile-1), int(xtile+2))):
        for j, y in enumerate(range(int(ytile-1), int(ytile+2))):
            sleep(1)
            img = Image.open(get_img(x, y))
            print(f"saving at {x} at {i*TILE_SIZE}, {y} at {j*TILE_SIZE}")
            stitched.paste(img, box=(i*TILE_SIZE, j*TILE_SIZE))
    xoffset, yoffset = (xtile%1 - 0.5)*TILE_SIZE+TILE_SIZE*3/2, (ytile%1 - 0.5)*TILE_SIZE+TILE_SIZE*3/2
    print(f"cropping: from {xoffset} {yoffset}")
    box = (xoffset - TILE_SIZE / 2, yoffset - TILE_SIZE / 2, xoffset + TILE_SIZE / 2, yoffset + TILE_SIZE /2)
    print(f"box: {box}")
    cropped = stitched.crop(box)
#     cropped.save('out.png')
    return cropped

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment