Created
March 22, 2020 15:02
-
-
Save andrashann/3e20fdc55a37ff4960d3b430ecd724df 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
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"import requests\n", | |
"import time\n", | |
"\n", | |
"import geopandas as gpd\n", | |
"from shapely.geometry import Point, LineString" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 5, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"# Set your OpenRouteService API key in the environment before starting the notebook server.\n", | |
"\n", | |
"import os\n", | |
"\n", | |
"api_key = os.environ.get('API_KEY')" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"places = \"Velem, Bozsok, Torony, Sé, Olad, Szombathely, Nárai, Ják, Egyházasrádóc, Körmend, Halogy, Ivánc, Hegyhátszentmárton, Kondorfa, Szalafő, Őriszentpéter, Nagyrákos, Kerkáskápolna, Magyarföld, Magyarszombatfa, Gödörháza, Velemér, Szentgyörgyvölgy, Kógyár, Felsőszenterzsébet, Kerkafalva, Pusztaszentpéter, Felsőcsöde, Csöde, Pankasz, Kisrákos, Szaknyér, Hegyhátszentjakab, Vadása-tó, Zalalövő, Nagyfernekág, Salomvár, Zalacséb, Kávás, Ebergény, Zalaegerszeg, Babosdöbréte, Milejszeg, Pálfiszeg, Csonkahegyhát, Kislengyel, Vargaszeg, Vörösszeg, Győrfiszeg, Zalatárnok, Szentkozmadombja, Rádiháza, Söjtör, Tófej, Gutorfölde, Szentpéterfölde, Bázakerettye, Kistolmács, Borsfa, Valkonya, Obornak, Homokkomárom, Nagykanizsa, Miklósfa, Surd, Belezna, Őrtilos, Zákány, Somogybükkösd, Nemespátró, Ágneslak, Csurgónagymarton, Csurgó, Berzence, Somogyudvarhely, Vízvár, Babócsa, Komlósd, Drávaszentes, Barcs, Szulok, Kálmáncsa, Lad, Dióspuszta, Magyarlukafa, Somogyhárságy, Kishárságy, Visnyeszéplak, Szilvásszentmárton, Patca, Szenna, Kaposszerdahely, Kaposszentjakab, Kaposvár, Zselickislak, Simonfa, Gálosfa, Ibafa, Kán, Gorica, Hetvehely, Abaliget, Orfű, Kővágószőlős, Kővágótöttös, Cserkút, Bakonya, Pécs, Pécsbánya, Mánfa, Árpádtető, Zobákpuszta, Kisújbánya, Püspökszentlászló, Pécsvárad, Zengővárkony, Kisújbánya, Óbánya, Mecseknádasd, Apátvarasd, Ófalu, Bátaapáti, Mórágy, Kismórágy, Zsibrik, Mőcsény, Szálka, Grábóc, Szekszárd\"" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"129\n" | |
] | |
} | |
], | |
"source": [ | |
"places_split = places.split(', ')\n", | |
"print(len(places_split))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 4, | |
"metadata": { | |
"scrolled": true | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"129/129\r" | |
] | |
} | |
], | |
"source": [ | |
"results = []\n", | |
"\n", | |
"for i, p in enumerate(places_split):\n", | |
" r = requests.get(f'https://nominatim.openstreetmap.org/search/{p}, Hungary?format=json')\n", | |
" rdata = r.json()[0]\n", | |
" data = {'lat': float(rdata['lat']), 'lon': float(rdata['lon']), 'name': rdata['display_name'].split(',')[0],\n", | |
" 'geom': Point(float(rdata['lon']), float(rdata['lat']))}\n", | |
" results.append(data)\n", | |
" \n", | |
" time.sleep(1.1)\n", | |
" \n", | |
" print(f'{i+1}/{len(places_split)}', end='\\r')" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 8, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"places_gdf = gpd.GeoDataFrame(results, geometry='geom')" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 9, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"# save places points as a geojson\n", | |
"\n", | |
"places_gdf[['name', 'geom']].to_file(\"places.geojson\", driver='GeoJSON')" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 38, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"# get hiking directions between points\n", | |
"\n", | |
"path_points = [list(x) for x in list(zip(gdf.lon, gdf.lat))]\n", | |
"\n", | |
"# the api can take at most 50 points for routing,\n", | |
"# so we need to split the list in less-than-50-point,\n", | |
"# parts where the last point in a part is the first \n", | |
"# point of the next part\n", | |
"#\n", | |
"# note: this is a shoddy solution right now, but it works\n", | |
"\n", | |
"# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks\n", | |
"\n", | |
"def chunks(lst, n):\n", | |
" \"\"\"Yield successive n+1-sized chunks from lst with \n", | |
" the last element repeated as the first element of\n", | |
" the next chunk.\"\"\"\n", | |
" for i in range(0, len(lst), n):\n", | |
" if i == 0:\n", | |
" yield lst[i:i + n]\n", | |
" else:\n", | |
" yield lst[i-1:i + n]\n", | |
"\n", | |
"path_point_lists = list(chunks(path_points, 30))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 50, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"list_of_path_coordinates = []\n", | |
"\n", | |
"for pts in path_point_lists:\n", | |
" headers = {\n", | |
" 'Content-Type': 'application/json; charset=utf-8',\n", | |
" 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',\n", | |
" 'Authorization': api_key,\n", | |
" }\n", | |
"\n", | |
" data = f'{{\"coordinates\":{pts},\"instructions\":\"false\",\"preference\":\"recommended\"}}'\n", | |
"\n", | |
" path_response = requests.post('https://api.openrouteservice.org/v2/directions/foot-hiking/geojson', headers=headers, data=data)\n", | |
" \n", | |
" if path_response.ok:\n", | |
" list_of_path_coordinates.extend(path_response.json()['features'][0]['geometry']['coordinates'])\n", | |
" else:\n", | |
" print('There was an error.')\n", | |
" break\n", | |
" \n", | |
" time.sleep(2)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 54, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"hikepath_gdf = gpd.GeoDataFrame([{'geom': LineString(list_of_path_coordinates)}], geometry='geom')\n", | |
"hikepath_gdf.to_file(\"path.geojson\", driver='GeoJSON')" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.7.1" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment