1 import requests
2 import json
3
4
5 #传入地址,返回对应的经纬度信息
6 def getLocation(address,key):
7
8
9 url = 'https://restapi.amap.com/v3/geocode/geo?key=%s&address=%s'%(key,address)
10 res = requests.get(url)
11 try:
12 # 将 JSON 对象转换为 Python 字典
13 json_data = json.loads(res.text)
14 #取字典里的localtion的值,将键放到方括号里
15 location=json_data['geocodes'][0]['location']
16 except:
17 location=''
18 #print("没有location")
19 return location
20
21 #传入经纬度,返回
22 def getADaddress(location,key):
23 longitude=location.split(',')[0]
24 latitude=location.split(',')[1]
25 #url = 'https://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s'%(key,location)
26 url ='https://www.amap.com/service/regeo?longitude=%s&latitude=%s'%(longitude,latitude)
27 res = requests.get(url)
28 # 将 JSON 对象转换为 Python 字典
29 json_data = json.loads(res.text)
30 #取字典里的ADaddress的值,将键放到方括号里
31 """province=json_data['regeocode']['addressComponent']['province']
32 city=json_data['regeocode']['addressComponent']['city']
33 district=json_data['regeocode']['addressComponent']['district']
34 adcode=json_data['regeocode']['addressComponent']['adcode']
35 ADaddress=[province,city,district]
36 data=[adcode,ADaddress]"""
37 ADaddress=json_data['data']['desc'].split(',')[0]+json_data['data']['desc'].split(',')[1]+json_data['data']['desc'].split(',')[2]
38 adcode=json_data['data']['districtadcode']
39 data=(adcode,ADaddress)
40 return data
41
42
43 def getData(key,address):
44 location=getLocation(address,key)
45 try:
46 data=getADaddress(location,key)
47 except:
48 data=('','')
49 #print("location传入失败")
50 return data