Created
August 19, 2022 18:52
-
-
Save evandiewald/3d299e096a9526006b11c32ad4825ec8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def load_map(place: str, graph_only: bool = False) -> (nx.MultiDiGraph, dict): | |
""" | |
Load OSM trail data for a given region. Initially check if the graph has already been cached on disk, otherwise it will be downloaded. | |
Args: | |
place: The geocode of the region of interest, e.g. 'Shenandoah National Park, Virginia, USA' | |
graph_only: If true, return only the NetworkX graph, not the geojson. | |
Returns: The dataset as a NetworkX MultiGraph, the nodes geojson, the edges geojson | |
""" | |
filename = p.sub("", place).lower().replace(" ", "_") | |
graph_fp = f"static/graphs/{filename}.graphml" | |
edges_fp = f"static/edges/{filename}.geojson" | |
nodes_fp = f"static/nodes/{filename}.geojson" | |
try: | |
G = ox.load_graphml(graph_fp) | |
print("Graph loaded from disk") | |
except FileNotFoundError: | |
print("Downloading and caching graph from OSM") | |
# custom filter to only include walkable segments - see: https://support.alltrails.com/hc/en-us/articles/360019246411-OSM-Derivative-Database-Derivation-Methodology | |
cf = '["highway"~"path|track|footway|steps|bridleway|cycleway"]' | |
G = ox.graph_from_place(place, custom_filter=cf) | |
ox.save_graphml(G, graph_fp) | |
if graph_only: | |
return G | |
if os.path.isfile(edges_fp) is False or os.path.isfile(nodes_fp) is False: | |
# convert Graph to GeoDataFrames and save as GeoJSON | |
nodes, edges = ox.graph_to_gdfs(G) | |
edges = edges[["name", "geometry", "length"]] | |
edges["name"] = edges["name"].apply(lambda x: x[0] if type(x) is list else x) | |
edges.to_file(edges_fp) | |
nodes.to_file(nodes_fp) | |
with open(nodes_fp, "r") as f: | |
nodes = json.load(f) | |
with open(edges_fp, "r") as f: | |
edges = json.load(f) | |
for feat in edges["features"]: | |
# add custom tooltip property for Leaflet visualization | |
tooltip = f"{feat['properties']['name']}, {round(feat['properties']['length'] / 1609, 1)} mi" | |
feat["properties"]["tooltip"] = tooltip | |
return G, nodes, edges |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment