如何在Python或R中使用Google Maps Directions API获取经过的邮政编码和地址。

0 投票
1 回答
1082 浏览
提问于 2025-04-18 17:44

最近,我在尝试使用Google地图的API来进行Python和R的编程。我已经在Python中实现了这个功能,它可以返回从A点到B点的路线列表。

from googlemaps import GoogleMaps

mapService = GoogleMaps()
directions = mapService.directions('Houston', 'Atlanta')
for step in directions['Directions']['Routes'][0]['Steps']:
    print step['descriptionHtml']

这个功能会返回一系列的转弯指示等等,但我想要在每一步的指示中提取出地理坐标。比如,运行之前的代码会返回:

Head <b>northeast</b> on <b>Bagby St</b> toward <b>Walker St</b>
Turn left onto <b>Walker St</b>
Merge onto <b>I-45 N</b> via the ramp on the left to <b>Dallas</b>
Take exit <b>48A</b> for <b>Interstate 10 E</b> toward <b>Beaumont</b>
Merge onto <b>I-10 E</b>
Keep left to stay on <b>I-10 E</b>
Keep left to stay on <b>I-10 E</b><div class="google_note">Entering Louisiana</div>
Keep left to continue on <b>I-12 E</b>, follow signs for <b>Hammond</b>
Take exit <b>85B-85C</b> on the left toward <b>I-59 N/<wbr/>I-10 E/<wbr/>Bay St Louis/<wbr/>Hattiesburg</b>
Take exit <b>85C</b> on the left to merge onto <b>I-10 E</b> toward <b>Bay St Louis</b><div class="google_note">Passing through Mississippi</div><div class="google_note">Entering Alabama</div>
Take exit <b>20</b> on the left to merge onto <b>I-65 N</b> toward <b>Montgomery</b>
Take exit <b>171</b> to merge onto <b>I-85 N</b> toward <b>Atlanta</b><div class="google_note">Entering Georgia</div>
Take exit <b>246</b> for <b>Fulton St/<wbr/>Central Ave</b> toward <b>Downtown</b>
Keep right at the fork, follow signs for <b>Fulton Street</b>
Turn right onto <b>Fulton St SW</b>
Turn left onto <b>Capitol Ave SE</b>

那么,我该如何在第一步、第二步等之后获取当前的地理位置呢?我打算在R中使用这些信息,所以如果在R中做这个更简单,那就更好了。

1 个回答

2

这个文档 - http://py-googlemaps.sourceforge.net/ - 告诉你怎么从方向步骤中获取数据。以你的例子为例:

>>> for step in directions['Directions']['Routes'][0]['Steps']:
...   print step['Point']['coordinates'][1], step['Point']['coordinates'][0] 
... 
29.760427 -95.369803
29.76079 -95.36947
29.761142 -95.370061
29.766886 -95.366375
29.767338 -95.361398
29.776341 -95.269098

需要注意的是,这个包还提到它使用了一个已经不再支持的谷歌地图API(v2)。我也很惊讶居然可以在没有API密钥的情况下使用,但也许我第十次尝试的时候就会失败或者出现其他问题...

如果你想在R语言中做这件事,可以安装ggmap这个包,然后使用route

r = route("Houston","Atlanta",output="all")

虽然结构有点复杂,但可能会有文档可以参考,不过你可以获取这个路线的坐标:

sapply(r$routes[[1]]$legs[[1]]$steps,function(s){c(s$start_location)})
    [,1]     [,2]      [,3]      [,4]      [,5]     [,6]     [,7]     
lat 29.76043 29.76079  29.76114  29.76689  29.76734 29.77634 30.08729 
lng -95.3698 -95.36947 -95.37006 -95.36638 -95.3614 -95.2691 -94.13588
    [,8]      [,9]      [,10]     [,11]     [,12]     [,13]     [,14]    
lat 30.41922  30.30775  30.30571  30.62566  32.36334  33.7326   33.73572 
lng -91.12063 -89.74687 -89.73971 -88.12116 -86.32169 -84.39195 -84.39144
    [,15]     [,16]    
lat 33.74191  33.74189 
lng -84.39116 -84.38779

完整的例子可以在help(route)中找到

撰写回答