data science/python

Dijkstra Algorithm가 구현된 osmnx 라이브러리를 이용한 경로 검색

꼰대코더 2025. 2. 22. 22:07

앞선 칼럼에서 경로 검색에 쓰이는 Dijkstra Algorithm 을 Python 으로 구현해 보았다..

 

Dijkstra Algorithm (Google map 에서도 사용하는 경로 찾기)

Dijkstra Algorithm은 지도에서 가장 빠른 패스를 찾아주는 것 처럼 네트워크에서 두 지점간 가장 짧은 루트를 찾는데 쓰이는 알고리즘이다. 아래와 같은 분야에서 응용될 수 있다.GPS navigation systems fi

eldercoder.tistory.com

이번엔 OSMnx  라이브러리를 이용하여 직접 지도와 연결해서 경로 검색을 해 보도록 하자.

참고로 OSMnx  OpenStreetMap (오픈소스 지도 데이터)로 부터 데이터를 다운로드 받아 실 세계의 도로망과 그 외의 지리공간형태를 모델화, 투영, 가시화, 분석할 수 있는 Python 패키지 이다

 

패키지 다운로드

pip install osmnx
pip install mapclassify

한국에서는 국가 안보상 이유로 구글맵에서 도보 검색이 불가능 하다고 한다.

구글맵에서 경도 위도(혹은 대충의 주소)는 아래와 같이 지점을 클릭하여 마우스 메뉴로 취득할 수 있다.

서대문 독립공원  종각
 
# 맵 데이터를 로딩(정확히 한정된 지역을 지정해야 함 그렇지 않으면 방대한 데이터로 세션 아웃이 발생)
place = "Seoul, South Korea"
# network_type -> {"all", "all_public", "bike", "drive", "drive_service", "walk"}
# 도보를 선택
G = ox.graph_from_place(place, network_type="walk")

# # 지역명으로 검색하고자 하는 경우 -> 위도 경도 취득
# origin_point = ox.geocode("Bukchon Hanok Village, Seoul, South Korea")
# destination_point = ox.geocode("Namsan, Seoul, South Korea")
# 위도 경도를 직접 지정
origin_point = (37.57458439050526, 126.9560484944386)
destination_point =(37.57043876386802, 126.98323828460079)

# 가장 가까운 노드를 취득 (파라미터 순서는 경도 -> 위도)
origin_node = ox.distance.nearest_nodes(G, origin_point[1], origin_point[0])
destination_node = ox.distance.nearest_nodes(G, destination_point[1], destination_point[0])

# 가장 짧은 경로에 있는 노드들을 리턴 (k= 는 경로수)
routes_nodes = ox.k_shortest_paths(G, origin_node, destination_node, k=1, weight="length")

# get edges from from above multidigraph
gdf_nodes, gdf_edges = ox.graph_to_gdfs(G)

def generate_multindex(route_nodes):
    multiindex_list = []
    # append the index to list
    for u, v in zip(route_nodes[:-1], route_nodes[1:]):
        multiindex_list.append((u, v, 0))
    return multiindex_list

# generate multiindex based on generated shortest route
routes_index_list = []
for route_nodes in routes_nodes:
    multiindex_list = generate_multindex(route_nodes)
    routes_index_list.extend(multiindex_list)

# fetch edge details based on multi index list
shrt_gdf_edges = gdf_edges[gdf_edges.index.isin(routes_index_list)]
# plot the shortest route on map
shrt_gdf_edges.explore(color="red")

 

빨간색으로 도보 경로가 검색 되었다.