欢迎访问宙启技术站
智能推送

Python中geocodergoogle()库的高级应用:在地图上绘制多个地址的路径

发布时间:2023-12-24 06:56:12

在Python中,如果需要在地图上绘制多个地址之间的路径,可以使用geocodergoogle库来实现。geocodergoogle是一个用于地理编码和逆地理编码的Python库,它使用Google提供的地理编码API来获取地理位置信息。

下面是一个使用geocodergoogle库在地图上绘制多个地址的路径的示例代码:

import geocoder
import folium
from geopy import distance

# 定义起点和终点地址
start_address = "北京市海淀区"
end_address = "北京市朝阳区"

# 定义中间的多个地址
waypoints = ["北京市西城区", "北京市东城区"]

# 通过地理编码获取起点和终点的经纬度
start_geo = geocoder.google(start_address).latlng
end_geo = geocoder.google(end_address).latlng

# 通过地理编码获取中间地址的经纬度
waypoints_geo = []
for waypoint in waypoints:
    waypoint_geo = geocoder.google(waypoint).latlng
    waypoints_geo.append(waypoint_geo)

# 创建地图对象
map_obj = folium.Map(location=start_geo, zoom_start=12)

# 添加起点和终点的标记
folium.Marker(start_geo, popup="起点").add_to(map_obj)
folium.Marker(end_geo, popup="终点").add_to(map_obj)

# 添加中间地址的标记
for waypoint_geo in waypoints_geo:
    folium.Marker(waypoint_geo, popup="中间地址").add_to(map_obj)

# 绘制路径
waypoints = [start_address] + waypoints + [end_address]
route = folium.PolyLine(locations=[geocoder.google(waypoint).latlng for waypoint in waypoints],
                       color="red", weight=2, opacity=1).add_to(map_obj)

# 计算经过的总距离
total_distance = 0
for i in range(len(waypoints) - 1):
    total_distance += distance.distance(geocoder.google(waypoints[i]).latlng,
                                        geocoder.google(waypoints[i + 1]).latlng).km

print("总距离为:", total_distance, "千米")

# 保存地图
map_obj.save("map.html")

这段代码首先引入了geocoder、folium和geopy的distance模块。然后,定义了起点地址、终点地址和中间的若干个地址。接着,使用geocoder.google函数通过地理编码获取起点和终点的经纬度,并将它们添加到地图对象map_obj中。然后,遍历中间地址列表,使用geocoder.google函数获取每个中间地址的经纬度,并将它们添加到地图对象map_obj中。接着,使用folium.PolyLine方法绘制路径,并将路径添加到地图对象map_obj中。最后,计算经过的总距离,并将地图保存为map.html文件。

使用这个示例代码,你可以通过修改起点、终点和中间地址的值来绘制不同的地址之间的路径,并计算经过的总距离。