Python+Google Geocoding

时间:2023-03-10 01:08:02
Python+Google Geocoding

  本文主要介绍使用Python调用Google Geocoding API进行地址到地理坐标的转换。

  Google Geocoding参考https://developers.google.com/maps/documentation/geocoding/?hl=zh-CN

  Google Geocoding API 目前最新版为 Geocoding API (V3)

  要通过 HTTPS 访问 Geocoding API,请使用以下形式:

  HTTP://maps.googleapis.com/maps/geocode/out?parameters

  这里out参数指定请求返回的数据的格式,可以是json或者xml两者之一,本文使用json进行数据获取。本例子中取官方文档中的地址进行解析:

1600 Amphitheatre Parkway, Mountain View, CA,相应的json响应为:

{
"results" : [
{
"address_components" : [
{
"long_name" : "",
"short_name" : "",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "",
"short_name" : "",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4219998,
"lng" : -122.0839596
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4233487802915,
"lng" : -122.0826106197085
},
"southwest" : {
"lat" : 37.4206508197085,
"lng" : -122.0853085802915
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}

其中json数据中包含两个键results和status。

Demo源码:

 import urllib.request
import json,io,os,base64
#获得json数据
resquest = urllib.request.urlopen('http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false')
data = resquest.read().decode('utf-8')
jsonData = json.loads(data)
results = jsonData['results'] #从json文件中读取results的值(形式为列表)
address = results[0]['formatted_address']
lat_lng = results[0]['geometry']['location']
print(address,'的经纬度为',lat_lng)

results是一个只包含一个元素的元组,该元素(results[0])又是一个json格式的数据,包含4个键address_components、formatted_address、geometry和types。我们这里需要的地理坐标就在geometry中。