由于需要将一系列经纬度坐标转换为地址,定位到具体某个街道或者道路,尝试调用百度地图的API,
发现正好有个全球逆地理编码的API可以调用:
在服务文档里看到只有location和ak为必须的请求参数:
可以发现服务文档里给的地址
http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=35.658651,139.745415&output=json&pois=1&ak=您的ak //GET请求
正是由location和ak组成的,所以对不同的经纬度这个地址相应的也有所不同
而返回参数里的street正是我们所转换成的具体到街道的地址:
附代码:
import requests
import json
import xlrd
import numpy as np
def find_street(location):
url = 'http://api.map.baidu.com/geocoder/v2'
ak = '你的ak'
real_url = url + '/?callback = renderReverse&location=' + location + '&output=json&pois=1&ak=' + ak
req = requests.get(real_url)
t = req.text
# t=t[29:-1]
#print(t)
data = json.loads(t)
street=data["result"]["addressComponent"]["street"] # 输出街道名称
return street
if __name__=='__main__':
path='lalo.xlsx'
xl = xlrd.open_workbook(path)
sheet = xl.sheets()[0] # 0表示读取第一个工作表sheet
data = []
for i in range(2,4): # ncols表示按列读取
data.append(sheet.col_values(i))
print(np.shape(data))
for i in range(1,np.shape(data)[1]):
print(i)
lat=data[1][i-1]
lng=data[0][i-1]
lat=str(lat)
lng=str(lng)
location=lat+','+lng
street=find_street(location)
print(street)#输出街道名称
运行结果:
期间遇到的主要问题是开始是用了服务文档给的地址
http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=35.658651,139.745415&output=json&pois=1&ak=您的ak //GET请求
然后req.text返回的并不是json格式,而是
renderReverse&&renderReverse({"status":0,"result":{"location":{"lng":139.7454149999999,"lat":35.658650898203038},"formatted_address":"東京都港区芝公園4-2-8, Minato, Tokyo, Japan","business":"","addressComponent":{"country":"Japan","country_code":26000,"country_code_iso":"JPN","country_code_iso2":"JP","province":"Tokyo","city":"Minato","city_level":1,"district":"","town":"","adcode":"0","street":"東京都港区芝公園4-2-8","street_number":"","direction":"附近","distance":"40"},"pois":[],"roads":[],"poiRegions":[],"sematic_description":"","cityCode":26041}})
解决方法我个人觉得有两个,一个是正则,但是我不太熟练,我用的是切片,把前面的renderReverse&&renderReverse(和后面的)切掉,
t = req.text
t=t[29:-1]
就变成json格式了