Python基于百度地图API根据地址获取经纬度

根据一个中文的地址信息,获取该地址所对应的经纬度信息。(专业的说法是地理编码)。编程语言:Python3,百度地图API接口:http://lbsyun.baidu.com/index.php?title=webapi

获取地址的经纬度大致步骤如下:

访问API接口需要上传的信息:
Python基于百度地图API根据地址获取经纬度
代码如下:

# encoding:utf-8
import requests
import time

# 此处需要ak,ak申请地址:https://lbs.amap.com/dev/key/app
ak = "xxxxxxxxxxx"

headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/56.0.2924.87 Safari/537.36',
    'Referer': 'https://restapi.amap.com/'
}


# 地理信息解析
def amp_geocode(addr=None):
    url = "https://restapi.amap.com/v3/geocode/geo?parameters"
    params = {"key": ak,
              "address": addr}
    response = requests.get(url, params=params, headers=headers)
    if response.status_code == 200:
        try:
            loc_info = response.json()["geocodes"][0]["location"]
            lng = loc_info.split(",")[0]
            lat = loc_info.split(",")[1]
            print(loc_info)
            time.sleep(0.25)
            return (lng, lat)
        except Exception as e:
            print("Exception in amp_geocode",e)
            time.sleep(5)
            return None
    else:
        print("========>", response.status_code)
        time.sleep(5)
        return None

注意事项:

  1. 访问API的方式要对,POST、GET方式各有不同,参数要正确
  2. 网络访问,难免会出现错误,需要进行异常处理,try…except,此外如果出现短时间出现频繁的访问接口,可能百度的服务器会中断响应,因此如果出现异常时,先让程序休眠等待一下,即time.sleep(5)
  3. 对百度地图访问量很大的话,可以申请开发者个人认证,百度对认证过的用户,开放的接口访问额度大很多。
    Python基于百度地图API根据地址获取经纬度