-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_map.py
More file actions
170 lines (144 loc) · 5.26 KB
/
generate_map.py
File metadata and controls
170 lines (144 loc) · 5.26 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8
# *****************************************************************************#
from __future__ import annotations
import argparse
from pathlib import Path
import geopandas as gpd
import osmnx as ox
from geopy.geocoders import Nominatim
from palette import Palette, load_colour_palettes
class Map:
def __init__(self, point: tuple[float, float], radius: int) -> None:
print("### Loading data from OpenStreetMap")
self.streets = ox.graph_from_point(
point,
dist=radius,
retain_all=True,
truncate_by_edge=True,
clean_periphery=False,
)
self.street_data = self.unpack_data()
if "geometry" not in self.street_data:
raise KeyError("geometries not found in street data!")
self.water = ox.geometries_from_point(
point,
tags={"water": "river"},
dist=radius,
)
def unpack_data(self) -> gpd.GeoDataFrame:
data = []
for _, _, _, ddata in self.streets.edges(keys=True, data=True):
data.append(ddata)
df = gpd.GeoDataFrame(data)
return df
def apply_colour_palette(self, palette_name: str, palette: Palette):
print(f"### Applying palette {palette_name} to data")
def _map_highway_type_to_colour(row: gpd.GeoSeries) -> str:
if isinstance(row.highway, str):
comparer = lambda way, ref: way in ref
else:
comparer = lambda way, ref: any(i in ref for i in way)
if comparer(row.highway, ["motorway"]):
return palette["base05"]
elif comparer(row.highway, ["trunk"]):
return palette["base05"]
elif comparer(
row.highway,
["primary", "secondary", "tertiary", "unclassified", "residential"],
):
return palette["base05"]
elif comparer(row.highway, ["path"]):
return palette["base03"]
else:
return palette["base02"]
def _map_highway_type_to_width(row: gpd.GeoSeries) -> int:
if isinstance(row.highway, str):
comparer = lambda way, ref: way in ref
else:
comparer = lambda way, ref: any(i in ref for i in way)
if comparer(row.highway, ["motorway", "trunk"]):
return 2
else:
return 1
self.street_data["colour"] = self.street_data.apply(
_map_highway_type_to_colour, axis=1
)
self.street_data["line_width"] = self.street_data.apply(
_map_highway_type_to_width, axis=1
)
@property
def streets_bbox(self) -> tuple[float, float, float, float]:
minx, miny, maxx, maxy = self.street_data.geometry.total_bounds
return (maxy, miny, maxx, minx)
def export_image(self, destination: Path, palette_name: str, palette: Palette):
self.apply_colour_palette(palette_name, palette)
print("### Generating image")
fig, ax = ox.plot_graph(
self.streets,
node_size=0,
figsize=(20, 20),
bgcolor=palette["base00"],
edge_color=self.street_data["colour"].to_list(),
edge_linewidth=1,
edge_alpha=1,
show=False,
save=False,
close=True,
)
ox.plot_footprints(
self.water,
color=palette["base01"],
bbox=self.streets_bbox,
ax=ax,
dpi=600,
save=True,
show=False,
close=True,
filepath=destination,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--place",
type=str,
help="The place to generate the map for",
default="Grenoble, France",
)
parser.add_argument(
"--radius", type=int, help="Radius around the point to generate", default=3000,
)
parser.add_argument(
"--palette_file",
type=Path,
help="Path to a json file containing colour palettes",
default=Path("base16_schemes.json"),
)
parser.add_argument(
"--palette_names",
type=str,
nargs="+",
help="Names of the palettes to load from the palette_file",
default=["onedark", "github", "grayscale", "shapeshifter"],
)
parser.add_argument(
"--export_dir",
type=Path,
help="Path to a directory in which to place the generated maps",
default=Path("export"),
)
args = parser.parse_args()
geolocator = Nominatim(user_agent="map_plotter")
location = geolocator.geocode(args.place)
place_metadata = geolocator.reverse(location.point)
map = Map((location.latitude, location.longitude), args.radius)
place_cleaned = args.place.replace(' ', '_').replace(',', '')
args.export_dir.mkdir(exist_ok=True)
palettes = load_colour_palettes(args.palette_file)
for palette_name in args.palette_names:
map.export_image(
destination=args.export_dir / f"{place_cleaned}_{palette_name}.png",
palette_name=palette_name,
palette=palettes[palette_name],
)