通过百度API获取城市经纬度(1)

时间:2021-03-28 10:53:15

百度API秘钥,具体请参照其他教程。

# 第一种,urllib把url转为urlencode,在读取网页,在json读取内容
from urllib import parse query = { 'key':'zSSQXXXXXXXXX', 'address':'广州', 'output':'json' } base = 'http://api.map.baidu.com/geocoder?' url = base + parse.urlencode(query)
In [17]:
url
Out[17]:
'http://api.map.baidu.com/geocoder?key=zSSQXXXXXXX&address=%E5%B9%BF%E5%B7%9E&output=json'
In [18]:
import urllib.request
uri = urllib.request.urlopen(url)
In [19]:
uri
Out[19]:
<http.client.HTTPResponse at 0x5d91cb0>
In [20]:
adds = uri.read().decode('utf-8')
In [21]:
adds
Out[21]:
'{\n    "status":"OK",\n    "result":{\n        "location":{\n            "lng":113.30765,\n            "lat":23.120049\n        },\n        "precise":0,\n        "confidence":12,\n        "level":"\\u57ce\\u5e02"\n    }\n}'
In [22]:
import json
data = json.loads(adds)
data
Out[22]:
{'result': {'confidence': 12,
  'level': '城市',
  'location': {'lat': 23.120049, 'lng': 113.30765},
  'precise': 0},
 'status': 'OK'}
In [23]:
lat = data['result']['location']['lat']
lng = data['result']['location']['lng']
In [28]:
print('lat:%s'%lat)
print('lng:%s'%lng)
lat:23.120049
lng:113.30765
In [29]:
data['result']
Out[29]:
{'confidence': 12,
 'level': '城市',
 'location': {'lat': 23.120049, 'lng': 113.30765},
 'precise': 0}
In [34]:
data['result']['location']
Out[34]:
{'lat': 23.120049, 'lng': 113.30765}
In [ ]:
# 第二种,利用requets模块
In [45]:
address = '广州'
url = 'http://api.map.baidu.com/geocoder?output=json&key=zSSQF0IkTliIBjcZlbNeNaDsWIHrCS0u&address=' + str(address)
In [46]:
res = requests.get(url)
data = res.json()
data
Out[46]:
{'result': {'confidence': 12,
  'level': '城市',
  'location': {'lat': 23.120049, 'lng': 113.30765},
  'precise': 0},
 'status': 'OK'}
In [49]:
lat = float(data['result']['location']['lat'])
lng = float(data['result']['location']['lng'])
In [50]:
print('lat:%s'%lat,'lng:%s'%lng)
lat:23.120049 lng:113.30765