您的位置:首页 > 编程语言 > Python开发

Python下用Google Map查询地址的经纬度

2015-07-31 16:09 155 查看
环境:python3

坑:python2在开了goagent***后,运行查询程序会报错,"非法proxy",原理不明;

要点:urllib.parse.quote编码含中文地址的url,python才能正确解码处理

代码实现如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from urllib.request import urlopen
import json

def getGeoForAddress(address):
	# address = "上海市中山北一路121号"
	addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address
    #中文url需要转码才能识别
	addressUrlQuote = urllib.parse.quote(addressUrl, ':?=/')
	response = urlopen(addressUrlQuote).read().decode('utf-8')
	responseJson = json.loads(response)
    #type of response is string
	# print(type(response))
    #type of responseJson is dict
	# print(type(responseJson))
	lat = responseJson.get('results')[0]['geometry']['location']['lat']
	lng = responseJson.get('results')[0]['geometry']['location']['lng']
	print(address + '的经纬度是: %f, %f'  %(lat, lng))
	return [lat, lng]

if __name__ == '__main__':
    main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: