#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : BaiduAPI.py
# @Author: whf
# @Date : 2020/3/10
import urllib.request, urllib.parse, urllib.error
import json
import hashlib
MyAK = ‘********‘
MySK = ‘********‘
#事先申请好百度开发者权限
lat = 0
lng = 0
dictjson = {} # 声明一个字典
def JingWei(address):
global lat, lng
# 产生sn码
queryStr = "/geocoding/v3/?address=" + address + ‘&output=json&ak=‘ + MyAK
encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;‘@()*[]")
rawStr = encodedStr + MySK
sn = (hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest())
# 生成url
url = urllib.parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;‘@()*[]")
#print(‘Retrieving‘, url)
# 从API读取数据
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print(data)
#print(‘Retrieved‘, len(data), ‘characters‘)
# 解析数据
try:
js = json.loads(data)
except:
js = None
if not js or ‘status‘ not in js or js[‘status‘] != 0:
print(‘======Failure====‘)
print(data)
#print(json.dumps(js, indent=4, ensure_ascii=False))
# 获取经纬度坐标和地址类型
lat = js["result"]["location"]["lat"]
lng = js["result"]["location"]["lng"]
#print(‘纬度‘, lat, ‘经度‘, lng)
level = js["result"]["level"]
#print(‘地址类型‘, level)
# 基于百度地图API下的经纬度信息来解析地理位置信息
def getlocation(lat, lng):
#print(lat, "ss", lng)
url = ‘/reverse_geocoding/v3/?ak=‘ + MyAK + ‘&output=json&coordtype=wgs84ll&location=‘ + str(lat) + ‘,‘ + str(lng)
encodedStr = urllib.parse.quote(url, safe="/:=&?#+!$,;‘@()*[]")
rawStr = encodedStr + MySK
sn = (hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest())
# 生成url
url = urllib.parse.quote("http://api.map.baidu.com" + url + "&sn=" + sn, safe="/:=&?#+!$,;‘@()*[]")
#print(‘Retrieving‘, url)
req = urllib.request.urlopen(url) # json格式的返回数据
res = req.read().decode("utf-8") # 将其他编码的字符串解码成unicode
#print(json.loads(res))
return json.loads(res)
def jsonFormat(lat, lng):
str = getlocation(lat, lng)
global dictjson
dictjson = {}
# get()获取json里面的数据
jsonResult = str.get(‘result‘)
address = jsonResult.get(‘addressComponent‘)
# 国家
country = address.get(‘country‘)
# 国家编号(0:中国)
country_code = address.get(‘country_code‘)
# 省
province = address.get(‘province‘)
# 城市
city = address.get(‘city‘)
# 城市等级
city_level = address.get(‘city_level‘)
# 县级
district = address.get(‘district‘)
# 区划代码
adcode = address.get(‘adcode‘)
# 街道
street = address.get(‘street‘)
# 街道编号
street_number = address.get(‘street_number‘)
# 把获取到的值,添加到字典里(添加)
# dictjson[‘country‘]=country
# dictjson[‘country_code‘] = country_code
dictjson[‘province‘] = province + city + district + street + street_number
dictjson[‘adcode‘] = adcode
# dictjson[‘city_level‘] = city_level
# dictjson[‘district‘]=district
return dictjson
if __name__ == "__main__":
with open("hubei","r",encoding=‘UTF-8‘) as f:###注意只需要修改这个上传文件即可,文件与代码放在同一目录下
hbaddress=f.readlines()
#print(hbaddress)
for i in hbaddress:
print(i)
JingWei(str(i))
jsonFormat(lat, lng)
print("行政区划代码" + dictjson.get(‘adcode‘))
百度-根据address调用百度api获取行政区域