之前在学习了简单的API调用后,查看了几个知名网站的API调用方法,发现Google的API调用还是相对比较简单的。下面就从API key的获取、googlemaps的安装,再到实际使用做一下说明。
 
1.基于Python的Google MAPS服务:
Google目前在Maps方面开放的API有好几个,可以根据不同的需求进行使用:
 
2.系统需求:
Python 2.7及以上;
Google MAP API key
 
1) 访问Google控制台并登陆;

2) 点击左上角的项目进行选择或者创建新项目:
这里我选择了之前创建过的项目,可以点击+号新建
 
3) 点击"启用API和服务"开启你需要的API;

这里选择跟地图相关的API:
 

点击启用。
显示此界面就说明启用成功。
 
4) 创建API key;
点击左侧边栏中的"凭据"进行创建:

5) 限制访问IP(可选)
点击后面的修改按钮可以对密钥进行IP等设置:

4.安装googlemaps:
C:\Users\DEV>pip install -U googlemaps
Collecting googlemaps
  Downloading googlemaps-2.5.1.tar.gz
Collecting requests<3.0,>=2.11.1 (from googlemaps)
  Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
    100% |████████████████████████████████| 92kB 112kB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 121kB/s
Collecting idna<2.7,>=2.5 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
    100% |████████████████████████████████| 61kB 123kB/s
Collecting certifi>=2017.4.17 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading certifi-2018.1.18-py2.py3-none-any.whl (151kB)
    100% |████████████████████████████████| 153kB 326kB/s
Collecting urllib3<1.23,>=1.21.1 (from requests<3.0,>=2.11.1->googlemaps)
  Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
    100% |████████████████████████████████| 133kB 216kB/s
Building wheels for collected packages: googlemaps
  Running setup.py bdist_wheel for googlemaps ... done
  Stored in directory: C:\Users\DEV\AppData\Local\pip\Cache\wheels\04\e8\d1\ae5577b5339873e6a5dd55141d56e507cf281b137ef0
9ba924
Successfully built googlemaps
Installing collected packages: chardet, idna, certifi, urllib3, requests, googlemaps
  Found existing installation: chardet 3.0.3
    Uninstalling chardet-3.0.3:
      Successfully uninstalled chardet-3.0.3
  Found existing installation: idna 2.5
    Uninstalling idna-2.5:
      Successfully uninstalled idna-2.5
  Found existing installation: requests 2.14.2
    Uninstalling requests-2.14.2:
      Successfully uninstalled requests-2.14.2
Successfully installed certifi-2018.1.18 chardet-3.0.4 googlemaps-2.5.1 idna-2.6 requests-2.18.4 urllib3-1.22
 
 
执行完上述操作后,我们就可以调用这些API来获取我们需要的数据了,先使用文档中的一个例子来调用试试:
import googlemaps
from datetime import datetime gmaps = googlemaps.Client(key='Add Your Key here') # Geocoding an address
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
print(geocode_result[0]['geometry']['location']) # Look up an address with reverse geocoding
reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))
print(reverse_geocode_result[0]['address_components'][1]['long_name'])
 
上述例子调用了geocode API,并分别打印各自的返回值。
geocode()即地理编码,根据地址以json格式返回经纬度。
reverse_geocode()即反向地理编码,根据经纬度返回具体地址。
 
实际调用后,在API首页便可以看到调用的具体情况。
下面针对directions API进行进一步研究。
 
Directions API
Directions API可以用来计算两地点之间的路线,并可设置路径点及出行模式(公交、驾车、骑行、步行等)
先来看一个简单的调用例子,并分析返回的json数据的具体内容。
import googlemaps
from datetime import datetime gmaps = googlemaps.Client(key='Add Your Key here')
# Request directions via public transit
now = datetime.now()
directions_result = gmaps.directions("Sydney Town Hall",
"Parramatta, NSW",
mode="transit",
departure_time=now)
print(directions_result)
例子中gmaps.directions()函数的形参分别为:
起始地点(Sydney Town Hall), 目标地点(Parramatta, NSW), 出行模式(公交), 出发时间(即刻触发)
然后再来看看根据这个请求返回的数据:
第一次看时有点发晕,这么多数据啊,怎么这么复杂,该怎么搞?其实像这样将数据格式化后再分析,就比较清楚了。
'legs'中为具体的路径信息,总体结构如下:
legs: [{
    'arrival_time': {},     # 到达时间
    'departure_time': {},     # 出发时间(这两个时间在调用时只能指定一个,另一个通过路线规划进行预估)
    'distance': {},     # 两个地点之间基于路线的距离
    'duration': {},     # 需要花费的时间
    'end_address': '',     # 目的地地址
    'end_location': {},     # 目的地经纬度
    'start_address': {},     # 出发地地址
    'start_location': {},     # 出发地经纬度
    'steps': {},     # 具体的规划路线
    'traffic_speed_entry': [],
    'via_waypoint': []
}]
 
而在'steps'中,又细分为几段详细的路线(每一段的信息都在列表的字典元素中),并在每一步中给出了'html_instructions'指示信息,内容非常全:
steps: [
        {
            'distance':     # 第一段路线数据
            'duration':
            'end_location':
            'html_instructions':
            'polyline':
            'start_location':
            'steps': [     # 第一段路线的详细路径
                    {
                        'distance': {},     # 
                        'duration':
                        'end_location':
                        'html_instructions':
                        'polyline':
                        'start_location':
                        'travel_mode':
                    },
                    {
                        'distance': {},
                        ... ...
                    },
                    ... ...
                ],
            'travel_mode': ''
        },
        {
            'distance':     # 第二段路线数据
            ... ...
        },
        ... ...
]
可以看到实际返回的数据还是挺复杂的,但是也是非常详细,想要的数据基本上都在里面了。
 
单纯的获取这些零散数据是没有什么实际意义的,如果我们能基于现有的数据,或者用爬取的数据与API相结合,就能进行数据分析,并进一步得到一些结论。
根据经纬度值,让我联想到可以利用已有的出租车数据集,使用经纬度获取出租车的位置,并进行分析。
几个可用的数据集:
下面的数据使用的是Microsoft的T-Drive trajectory data数据(该数据集是由很多个.txt文件组成的,我在使用前先转换成了csv格式的文件)。
 
根据经纬度,从API获取两个节点开车所需的时间及距离,并作出图表,查看开车时间及距离各自所占的比重。
由于API的调用限制,我们先取前2000条的记录进行分析:
import googlemaps
from datetime import datetime
import os
import csv
import pandas as pd
import matplotlib.pyplot as plt
import math # 将已知的多个txt文件中的内容放到一个CSV文件下
def txt2Csv(dataPath, csvname):
fileList = os.listdir(dataPath)
csvFile = open(dataPath + '\\' + csvname, 'w+')
writer = csv.writer(csvFile)
for fileName in fileList:
with open(dataPath + '\\' + fileName) as fileObj:
lines = fileObj.readlines()
for line in lines:
line = line.split(',')
line[-1] = line[-1][0:-1]
writer.writerow((line))
csvFile.close() # 根据经纬度获取两地之间的距离及花费的时间
def getDistanceDuration(key, path, csvName):
gmaps = googlemaps.Client(key=key)
df = pd.read_csv(path + '\\' + csvName)
df.columns = ['id', 'time', 'longitude', 'latitude']
durationList = []
distanceList = []
try:
for i in range(1, 1000):
now = datetime.now()
# 调取google API的directions:
directions_result = gmaps.directions((df.iloc[i, 3], df.iloc[i, 2]),
(df.iloc[i+1, 3], df.iloc[i+1, 2]),
mode="driving",
departure_time=now)
# 按照返回的格式,找出distance及duration,追加到列表中并返回
distanceList.append(directions_result[0]['legs'][0]['distance']['value'])
durationList.append(directions_result[0]['legs'][0]['duration']['value'])
except googlemaps.exceptions._RetriableRequest:
pass
return distanceList, durationList path = 'D:\\Learnning\\python\\scrape\\taxiData\\T-drive Taxi Trajectories\\release\\taxi_log_2008_by_id'
txt2Csv(path, 'geodata.csv') distanceList, durationList = getDistanceDuration('AIzaSyD8X6tJx6Ap5TVHlqwSso8iTwZfDWcFsOA', path, 'geodata.csv')
# 对返回数据的单位做转换, 并使用math.ceil对数据向上取整
distanceList = [math.ceil(dis/1000) for dis in distanceList]
durationList = [math.ceil(dis/60) for dis in durationList] totalDistance = 0
totalDuration = 0
# 计算总路程,并画出每段路程的距离在总路程中的占比:
for distance in distanceList:
totalDistance += distance
distancePropo = [distance/totalDistance for distance in distanceList]
plt.bar(distanceList, distancePropo)
plt.title("Distance interval")
plt.xlabel("Km")
plt.ylabel("Proportion")
plt.show() # 计算总时间,并画出每段路程花费的时间在总时间中的占比:
for duration in durationList:
totalDuration += duration
durationPropo = [duration/totalDuration for duration in durationList]
plt.bar(durationList, durationPropo)
plt.title("Time interval")
plt.xlabel("Min")
plt.ylabel("Proportion")
plt.show()
得出的图像:
 
按时间分布:
 

按行驶距离分布:

具体的使用文档可参考:
 
 

Google Maps API的使用的更多相关文章

  1. Google Maps API V3 之绘图库 信息窗口

    Google官方教程: Google 地图 API V3 使用入门 Google 地图 API V3 针对移动设备进行开发 Google 地图 API V3 之事件 Google 地图 API V3 ...

  2. Google Maps API V3 之 图层

    Google官方教程: Google 地图 API V3 使用入门 Google 地图 API V3 针对移动设备进行开发 Google 地图 API V3 之事件 Google 地图 API V3 ...

  3. Google Maps API V3 之 路线服务

    Google官方教程: Google 地图 API V3 使用入门 Google 地图 API V3 针对移动设备进行开发 Google 地图 API V3 之事件 Google 地图 API V3 ...

  4. google maps api申请的问题

    现在已经改由统一的GOOGLE API控制台进行所有GOOGLE API的管理了. 方法是使用Google帐号登入 https://code.google.com/apis/console. 然后在所 ...

  5. Google maps API开发(一)(转)

    一.加载Google maps API <script type="text/javascript" src="http://ditu.google.com/map ...

  6. Google maps API开发(二)(转)

    这一篇主要实现怎么调用Google maps API中的地址解析核心类GClientGeocoder: 主要功能包括地址解析.反向解析.本地搜索.周边搜索等, 我这里主要有两个实例: 实例一.当你搜索 ...

  7. Google Maps API Web Services

    原文:Google Maps API Web Services 摘自:https://developers.google.com/maps/documentation/webservices/ Goo ...

  8. Google maps API开发

    原文:Google maps API开发 Google maps API开发(一) 最近做一个小东西用到google map,突击了一下,收获不小,把自己学习的一些小例子记录下来吧 一.加载Googl ...

  9. Google Maps API Key申请办法(最新)

    之前的Google Maps Api的API Key很容易申请,只需要按照一个简单的表单提交部署的网站地址即可,自动生成API Key并给出引用的路径. 但是最近在处理另外一个项目的时候发现之前的这种 ...

  10. 如何插入谷歌地图并获取javascript api 秘钥--Google Maps API error: MissingKeyMapError

    参考:https://blog.csdn.net/klsstt/article/details/51744866 Google Maps API error: MissingKeyMapError h ...

随机推荐

  1. 使用Git的hook实现代码的自动部署

    这个功能非常的好用,可以省去诸多麻烦!我自己也是摸索了好久,才完全掌握的.希望能对大家有所帮助! 1,首先在我的阿里云服务器上已经创建好了一个代码远程的管理仓库,/srv/cmp.git 2, 在服务 ...

  2. 老男孩Python全栈开发(92天全)视频教程 自学笔记16

    day16课程内容: 装饰器: def outer(): x=10 def inner(): print(x) return innerouter()() #inner 是局部变量,10闭包:如果在一 ...

  3. day5(字符编码、数据类型、列表基本操作)

    一.字符编码 计算器所认识的编码都是二进制编码 二进制与十进制转换 计算机最开始使用的编码是美国的 ASCll编码 计算机容量单位 字符编码 python2.x 默认编码使用的是ASCll pytho ...

  4. Python+Selenium基础篇之1-环境搭建

    Python + Selenium 自动化环境搭建过程 1. 所需组建 1.1 Selenium for python 1.2 Python 1.3 Notepad++ 作为刚初学者,这里不建议使用P ...

  5. java基础之继承(二)

    上篇我们介绍了java中的构造方法,了解了关键字this和super在继承中所起到的作用,this可以显式调用重载的构造方法,super可以显式的调用父类中的任意可见方法.了解方法重载和重写的区别,知 ...

  6. 转 Caffe学习系列(2):数据层及参数

    http://www.cnblogs.com/denny402/p/5070928.html 要运行caffe,需要先创建一个模型(model),如比较常用的Lenet,Alex等, 而一个模型由多个 ...

  7. python 循环语句 函数 模块

    python循环语句 while循环语法结构 当需要语句不断的重复执行时,可以使用while循环 while expression: while_suite 语句ehile_suite会被连续不断的循 ...

  8. Linux PCI/PCI-E设备配置空间读取与修改

    Linux PCI/PCI-E设备配置空间读取与修改 1 前言 PCI和PCI Express,是计算机常使用的一种高速总线.操作系统中的PCI/PCI-E设备驱动以及操作系统内核,都需要访问PCI及 ...

  9. python︱Anaconda安装、简介(安装报错问题解决、Jupyter Notebook)

    每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 安装完anaconda,就相当于安装了Pyth ...

  10. R语言︱XGBoost极端梯度上升以及forecastxgb(预测)+xgboost(回归)双案例解读

    XGBoost不仅仅可以用来做分类还可以做时间序列方面的预测,而且已经有人做的很好,可以见最后的案例. 应用一:XGBoost用来做预测 ------------------------------- ...