LoginSignup
5
2

More than 1 year has passed since last update.

pythonでOSMnxを使って、地図上に最短経路を表示する方法

Posted at

はじめに

pythonでOSMnxを使って、福岡の博多駅から西鉄天神駅までの最短経路(徒歩)を表示します。世界中の道路情報を取得できるっぽいので、単純にすごいの一言。
一部調査したときに、pythonの3.9からOSMnxで使えないモジュールが出てきているみたい…。
一応、Windowsでコマンドライン実行もやってみたが、pip等での違いはない。

環境

  • コマンドライン実行

    • Windows10(64bit)
    • python 3.9.13
  • Docker on Jupyter

    • Windows10(64bit)
    • Docker Desktop
      • python 3.9.13
      • Jupyter NoteBook 6.4.11

pip実行

pip install osmnx
pip install scikit-learn
pip install folium

※scikit-learn は osmnxの一部モジュールでエラーが出るため必要

プログラム

# 福岡の博多区と中央区を指定
query = ["Hakataku,Fukuoka,Japan", "Chuo-ku,Fukuoka,Japan"]
# 博多区と中央区の道路データ(歩き用)を取得する(driveとかにすると、車になる)
G = ox.graph_from_place(query, network_type="walk")

# 博多駅の座標
hakatasta_loc = (33.58993304570779, 130.42074178084746)
# 天神駅の座標
tenjinsta_loc = (33.59164188388589, 130.39887879641677)

# 各駅のノードを取得
hakatasta_node = ox.nearest_nodes(G, hakatasta_loc[1], hakatasta_loc[0])
tenjinsta_node = ox.nearest_nodes(G, tenjinsta_loc[1], tenjinsta_loc[0])

# 最短経路を取得
shortest_route = ox.shortest_path(G, hakatasta_node, tenjinsta_node)
# 最短経路を地図にプロット
map = ox.plot_route_folium(G, shortest_route)

# 地図に各駅のマーカーを追加
folium.Marker(location=hakatasta_loc, tooltip="博多駅").add_to(map)
folium.Marker(location=tenjinsta_loc, tooltip="天神駅").add_to(map)

# 表示
map
# HTML保存
# map.save("map.html")

こんな感じ(出力したHTMLのスクリーンキャプチャ)

image.png

さいごに

田舎の方の舗装されていない道とか、情報公開してほしくない国とか都市とかありそうだけど、制限どうなっているんだろう…

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2