Skip to content

Instantly share code, notes, and snippets.

@cad0p
Last active July 8, 2021 10:51
Show Gist options
  • Save cad0p/463c805d93f48351d824e46cb8c98af6 to your computer and use it in GitHub Desktop.
Save cad0p/463c805d93f48351d824e46cb8c98af6 to your computer and use it in GitHub Desktop.
import json
import matplotlib.pyplot as plt
def plot_polygon(coord):
xs, ys = zip(*coord) # create lists of x and y values
plt.figure()
plt.plot(xs, ys)
plt.show()
def get_poly_coord(ways):
def save_way():
for point in way:
coord.append([
point['lon'], point['lat']
])
return i
def check_swap(last_checked=-1):
point_i = 0 if last_checked == -1 else -1
for j, w_j in enumerate(ways_index_to_check):
if ways[w_j][point_i] == way[point_i]:
# we just need to swap the current one and save
# (usually occurs when this is the first way)
way.reverse()
return save_way()
elif ways[w_j][point_i] == ways[w_i][point_i]:
# in this case it is the next one that needs to be swapped,
# so we need to check this way again
ways[w_i].reverse()
return save_way()
coord = []
ways_index_to_check = [i for i in range(len(ways))]
way_i = 0
while len(ways_index_to_check) > 0:
way = ways[ways_index_to_check[way_i]]
del ways_index_to_check[way_i] # does not need to be checked anymore
for i, w_i in enumerate(ways_index_to_check):
if ways[w_i][0] == way[-1]:
# then we have found the next way!
way_i = save_way()
break
elif ways[w_i][-1] == way[-1]:
# check which way is the one to swap
way_i = check_swap(last_checked=-1)
else:
pass
save_way()
# for i, way in enumerate(ways):
# # this does not check for swaps/reordering
# for point in way:
# coord.append([
# point['lon'], point['lat']
# ])
return coord
if __name__ == '__main__':
with open("overpass_result_rapallo.json", "r") as json_overpass:
data = json.load(json_overpass)
# this data has one node (the city center),
# and many ways (the border of the municipality).
# This is the query to retrieve this data:
# place = "Rapallo"
# overpass_query = f"""
# [out:json];
# area['admin_level'='2']['name'='Italia'];
# rel['admin_level'='8']['name'=\"{place}\"](area);
# out geom;
# """
members = data['elements'][0]['members']
if members[0]['type'] == 'node':
# the node is the city center (roughly), and it is
# different from the boundaries of the municipality
node_index = 0
else:
# last position
node_index = -1
poly_coord = get_poly_coord(
[members[i]['geometry'] for i in range(
1+node_index, len(members)+node_index
)]
)
plot_polygon(poly_coord)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment