import requests import sys import urllib.parse import json import subprocess import os def get_polygon(name): if not os.path.isfile(name + ".json"): url = "https://nominatim.openstreetmap.org/search.php?q={0}&polygon_geojson=1&format=jsonv2".format( urllib.parse.quote(name) ) r = requests.get(url) data = json.loads(r.text) if data is None: raise ValueError("Bogus results") osm_id = None for entry in data: if "boundary" in entry["category"] and entry["osm_type"] == "relation": osm_id = entry["osm_id"] break if not osm_id: raise ValueError("No id") url = "http://polygons.openstreetmap.fr/get_geojson.py?id={0}¶ms=0".format(osm_id) with open(name + ".json", "w") as file: file.write(requests.get(url).text) else: data = json.load(open(name + ".json")) info = subprocess.check_output( [ "mapshaper", "-i", "{0}.json".format(name), "-each", "console.log(this.centroidX, this.centroidY, this.area)"], shell=True, stderr=subprocess.STDOUT, ).decode("utf-8") lon, lat, area = list(map(float, info.split(" "))) if area is not None: info = subprocess.check_output( [ "mapshaper", "-i", "{0}.json".format(name), "-proj", "+proj=nsper", "+h=100000", "+lat_0={0}".format(lat), "+lon_0={0}".format(lon), "-simplify", "resolution=500x500", "-each", "console.log(\"HEIGHT:\" + this.height)", "-o", "{0}.svg".format(name), ], shell=True, stderr=subprocess.STDOUT, ).decode("utf-8") height = None for line in info.split("\n"): if "HEIGHT:" in line: height = float(line.split(":")[1].strip()) print("[\"{0}\", {1}, {2}],".format(name, area, height)) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: {0} list-of-cities".format(sys.argv[0])) else: city = None try: for city in open(sys.argv[1]).readlines(): try: get_polygon(city.strip()) except ValueError as e: print(city + " failed") print(e) except Exception as e: print(city + " failed") print(e)