-
Notifications
You must be signed in to change notification settings - Fork 1
/
osm_stitch.py
executable file
·67 lines (58 loc) · 2.16 KB
/
osm_stitch.py
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
#! /usr/bin/env python
import math
import httplib
import sys
import tempfile
from PIL import Image
if not len(sys.argv) > 6:
raise SystemExit("Usage: upper_lat upper_lon lower_lat lower_lon zoom output_file")
upper_lat = float(sys.argv[1])
upper_lon = float(sys.argv[2])
lower_lat = float(sys.argv[3])
lower_lon = float(sys.argv[4])
zoom = int(sys.argv[5])
output = sys.argv[6]
sub = ''
tmp_location = tempfile.gettempdir() + '/'
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
return (xtile, ytile)
def writetile(x, y, zoom):
global sub
if sub == 'a':
sub = 'b'
elif sub == 'b':
sub = 'c'
else:
sub = 'a'
file_name = str(x) + '_' + str(y) + '.png'
conn = httplib.HTTPConnection(sub + '.tile.openstreetmap.org')
print('Retrieving /' + str(zoom) + '/' + str(x) + '/' + str(y) + '.png')
conn.addheaders = [('User-agent', 'Mozilla/5.0')]
conn.request('GET', '/' + str(zoom) + '/' + str(x) + '/' + str(y) + '.png')
response = conn.getresponse()
if response.status == 200 and response.reason == 'OK':
print('/' + str(zoom) + '/' + str(x) + '/' + str(y) + '.png retrieved')
f = open(tmp_location + file_name, 'w')
f.write(response.read())
f.close()
else:
print('/' + str(zoom) + '/' + str(x) + '/' + str(y) + '.png failed')
print(str(response.status) + ' ' + response.reason)
conn.close()
return file_name
top_left = deg2num(upper_lat, upper_lon, zoom)
bottom_right = deg2num(lower_lat, lower_lon, zoom)
height = (bottom_right[1] - top_left[1]) * 256
width = (bottom_right[0] - top_left[0]) * 256
osm_map = Image.new("RGBA", (width, height))
for x in range(top_left[0], bottom_right[0]):
for y in range(top_left[1], bottom_right[1]):
foo = Image.open(tmp_location + writetile(x, y, zoom))
osm_map.paste(foo, (256 * (x - top_left[0]), 256 * (y - top_left[1])))
writetile(x, y, zoom)
print('Saving map to ' + output + '/map.png')
osm_map.save(output + '/map.png')