You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Directions API仅获取驾车路线中的高速公路/主干道列表?

提取驾车路线中的高速公路/主干道列表

一、基于现有输出的过滤方案

你的当前输出里,高速公路/主干道通常带有明显标识:州际高速以I 开头、国道以US 开头、州级公路以XX-XXX格式命名、收费公路包含Tpke关键词。可以用正则匹配直接过滤这些条目:

import re

# 你的路线段列表
route_segments = ['2 Murray Street, New York, NY 10007, USA', '50 14th St, Jersey City, NJ 070310, USA', '5710 Newark - Jersey City Tpke, Kearny, NJ 07032, USA', 'US 46, 07058, , New Jersey, United States', '192 Waring Dr, Delaware Water Gap, PA 18327, USA', '4891 E County Line Rd, Mineral Ridge, OH 44440, USA', ', 44451, , Ohio, United States', '914&, 916 Rosamond Ave, Akron, OH 44307, USA', '1090 W Wilbeth Rd, Akron, OH 44314, USA', 'US 224, 44273, , Ohio, United States', 'I 71, 43334, , Ohio, United States', '3970 OH-229, Marengo, OH 43334, USA', '2390 OH-229, Ashley, OH 43003, USA']

# 匹配高速/主干道的正则规则
highway_regex = re.compile(r'(I \d+|US \d+|\w{2}-\d+|Tpke)', re.IGNORECASE)

# 过滤并去空值
filtered_highways = [seg for seg in route_segments if highway_regex.search(seg) and seg.strip()]

print(filtered_highways)

运行后得到的结果:

['5710 Newark - Jersey City Tpke, Kearny, NJ 07032, USA', 'US 46, 07058, , New Jersey, United States', 'US 224, 44273, , Ohio, United States', 'I 71, 43334, , Ohio, United States', '3970 OH-229, Marengo, OH 43334, USA', '2390 OH-229, Ashley, OH 43003, USA']

二、优化API请求,直接获取准确高速路信息

上面的过滤方法依赖现有途经点的字符串格式,可能存在遗漏或误判。更可靠的方式是直接解析Directions API返回的完整路线数据,提取驾车路段中的高速公路:

以Google Maps Directions API为例,调用时指定mode=driving,然后遍历响应中的routes[0].legs[0].steps,提取每个步骤里的高速路名称:

import requests
import re

api_key = '你的API密钥'
origin = "New York"
destination = "Ohio"
highway_regex = re.compile(r'(I \d+|US \d+|\w{2}-\d+|Tpke)', re.IGNORECASE)

# 发起API请求
response = requests.get(
    f'https://maps.googleapis.com/maps/api/directions/json',
    params={
        'origin': origin,
        'destination': destination,
        'mode': 'driving',
        'key': api_key
    }
).json()

highway_set = set()
if response['status'] == 'OK':
    # 遍历路线的每一段步骤
    for step in response['routes'][0]['legs'][0]['steps']:
        # 从步骤说明中提取高速路名称
        matches = highway_regex.findall(step['html_instructions'])
        for match in matches:
            highway_set.add(match.strip())

# 去重后输出
print(list(highway_set))

这种方法能直接从API的路线指令中提取高速路名称,结果更准确,还能自动去重重复路段。

内容的提问来源于stack exchange,提问作者Ekagra Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:50:25