百度地图路径规划API调用示例(python)

文章讲述了上海大学生在暑期回家时面临的交通拥堵问题,分析了交通压力的原因,并推荐使用百度地图的DirectionLiteAPI进行路线规划。同时,示例展示了如何使用Python进行数据采集并存储到POSTGRESQL数据库,以便进一步的数据分析和可视化,以找出最佳出行时间,如11:00-12:00,该时段交通相对通畅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随着暑期的到来,大学生们迫不及待地打包行李,准备回家与家人团聚。然而,对于在上海市上学的大学生来说,回家也意味着面临较为严峻的城市拥堵问题。

首先,大学生回家集中在放假的前几天和假期的最后几天。这导致高速公路、火车站和机场等交通枢纽出现车流高峰。大量的私家车、长途客车和高铁动车,以及航班的增加,使得交通压力剧增,交通拥堵问题愈发严重。其次,大学生回家的同时,上海市的旅游高峰期也开始了。许多游客选择来上海观光和旅游,增加了景点、购物区和餐饮区的人流量。这不仅给公共交通带来了压力,还导致周边道路的交通拥堵,给大学生回家的交通带来不便和延误。此外,上海市的居民和其他工作人员也在这个时候休假或者利用周末时间外出。市区道路和周边高速公路上的车流量急剧增加,常常造成交通堵塞和行驶缓慢,给大学生回家的路上带来更多的时间成本和疲劳。

因此,合理规划出行时间对于正准备回家的大学生来说至关重要,特别是需要乘坐火车或高铁的同学,合理规划时间避免错过班车或航班,减少不必要的损失。

百度地图开放平台提供了轻量级路线规划服务(DirectionLite API ),以HTTP/HTTPS形式提供了路线规划服务。相较于Direction API,DirectionLite API更注重服务的高性能和接口的轻便简洁,满足基础的路线规划需求,并不具备Direciton API中的驾车多路线/未来出行和公交跨城规划等高级功能。DirectionLite API支持驾车、骑行、步行、公交路线规划,支持中国大陆地区。

使用指南:在这里插入图片描述
        - 注册百度账号
        - 申请成为百度开发者
        - 获取密钥(AK)
        - 发送请求,使用服务

驾车路线规划的GET请求:

https://api.map.baidu.com/directionlite/v1/driving?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK

驾车规划请求参数:本次路线规划只需要以下三个参数,其它参数请查看服务文档

字段名称字段含义字段类型是否必须备注
ak开发者密钥,AK申请string
origin起点“double,double”起点经纬度,格式为:纬度,经度;小数点后不超过6位,40.056878,116.30815
destination终点“double,double”终点经纬度,格式为:纬度,经度;小数点后不超过6位,40.056878,116.30815

API返回的json请求如下:主要包括计算状态、origin-destination点位,以及路径(routes)下具体的分段(steps)。
在这里插入图片描述

每个分段都有对应的路段距离(distance)、路段耗时(duration)、分段的道路类型(road_type)和路段描述(instruction)等等:
在这里插入图片描述

我以我们校区到虹桥火车站为例,每隔10分钟采集一次数据,将结果存入PostgreSQL中。

import psycopg2
import pandas as pd
import json, time, re
from urllib import request
from sqlalchemy import create_engine
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

'''数据库操作'''
# 创建数据库
db_name = 'dailydata'
db_connection = {
    "host": "localhost",
    "port": "5432",
    "user": "postgres",
    "password": "your password",
}
conn = psycopg2.connect(**db_connection) # 连接数据库
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) #  设置自动提交事务
cursor = conn.cursor() #  创建游标
try:
    sql = "CREATE DATABASE {}".format(db_name) #  创建数据库
    cursor.execute(sql) #  执行sql语句
    print(f'{db_name}数据库创建完成')

except:
    print(f'{db_name}数据库已存在')

cursor.close() # 关闭游标
conn.close() # 关闭连接

# 创建postgis扩展模块
extension = "postgis"
db_connection = {
    "host": "localhost",
    "port": "5432",
    "user": "postgres",
    "password": "123",
    "dbname": db_name
}
conn = psycopg2.connect(**db_connection) # 连接数据库
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) #  设置自动提交事务
cursor = conn.cursor() #  创建游标
try:
    cursor.execute(f"CREATE EXTENSION {extension};")
    print(f'{extension}扩展模块创建完成')
except:
    print(f'{extension}扩展模块已存在')

cursor.close() # 关闭游标
conn.close() # 关闭连接


'''获取路线数据'''
url = "https://api.map.baidu.com/directionlite/v1/driving?origin={0}&destination={1}&ak={2}"  # 百度地图api
line = "31.167918,121.42531;31.200282,121.326533"  # 起点坐标;终点坐标
ak = "your key"  # 百度地图api密钥

# 循环运行
while True:
    _data = pd.DataFrame(columns=['date','distance','duration','instruction','steps_loc'])  # 创建空的DataFrame
    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  # 获取当前时间
    origin=line.split(';')[0]  # 起点坐标
    destination = line.split(';')[1]  # 终点坐标
    html = request.urlopen(url.format(origin, destination, ak)).read()  # 获取返回的信息
    response = json.loads(html)  # 将json格式转换为python对象
    if(response['message'] == 'ok'):  # 判断是否成功获取数据
        distance = response['result']['routes'][0]['distance']  # 总距离
        duration = response['result']['routes'][0]['duration']  # 总时间

        # 获取每一步的行驶指示
        instructions = ''
        for instruction in response['result']['routes'][0]['steps']:
            instructions1 = re.sub(r'<[^>]+>', '', instruction['instruction']) + '。'
            instructions += instructions1

        # 获取每一步的起始坐标
        steps_loc = ''
        for step_loc in response['result']['routes'][0]['steps']:
            start_location = step_loc['start_location']
            end_location = step_loc['end_location']
            start_location = str(start_location['lng']) + ',' + str(start_location['lat']) + ';'
            end_location = str(end_location['lng']) + ',' + str(end_location['lat']) + ';'
            step_loc1 = start_location + end_location
            steps_loc += step_loc1

        # 将数据写入DataFrame
        _data.loc[0] = [current_time, distance, duration, instructions, steps_loc]

        # 将数据写入数据库
        engine = create_engine("postgresql://postgres:123@localhost:5432/"+db_name)  # 连接数据库
        try:
            _data.to_sql('Lines_SHNU_to_HQRailwayStation', engine, index=False, if_exists='append')  # 第一个参数为表名称
            print(f'当前时间路线数据已入库:', current_time, distance, duration)
        except Exception as e:
            print(e)
        finally:
        	engine.dispose()  # 关闭数据库连接

    # 每隔10分钟获取一次数据
    time.sleep(600)

对6月24日晚8时到6月26日晚10时约450条导航数据进行可视化。
在这里插入图片描述
出行尽量避开早晚高峰期(早8时左右和下午5点左右),选择在11:00-12:00出行最“通畅”,大约需要41分钟。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值