python调用高德地图实现根据地名获取经纬度

前提条件:

需要申请一个web服务类型的key(xxxxxxxxx为申请的key)

import requests
import pypinyin
import json
 
'''
获取地址坐标
'''

def pinyin(word):
    s = ''
    for i in pypinyin.pinyin(word, style=pypinyin.NORMAL):
        s += ''.join(i)
    return s

def get_city_location(name):
    url = "https://restapi.amap.com/v3/geocode/geo?address={}&output=json&key=xxxxxxxxxxxxxxxx".format(name)
    # print(url)
    res_text = requests.get(url).text
    # print(res_text)
    # print(json.loads(res_text).get('status'))
    # print(json.loads(res_text).get('geocodes')[0].get('city'))
    # print(json.loads(res_text).get('geocodes')[0].get('location'))
    # print(json.loads(res_text).get('geocodes')[0].get('location').split(',')[0])
    # print(json.loads(res_text).get('geocodes')[0].get('location').split(',')[1])

    retval = json.loads(res_text).get('status')

    city_list = []
    if retval == '1':
        city_name = json.loads(res_text).get('geocodes')[0].get('city')
        longitude = json.loads(res_text).get('geocodes')[0].get('location').split(',')[0]
        latitude = json.loads(res_text).get('geocodes')[0].get('location').split(',')[1]

        tmpl = {
            "key": pinyin(city_name),
            "latitude": float(latitude),
            "longitude": float(longitude),
            "name": city_name
        }

        city_list.append(tmpl)
        return json.dumps(city_list, ensure_ascii=False)
    
    return None


print(get_city_location("苏州"))

输出结果:

[{"key": "suzhoushi", "latitude": 31.298886, "longitude": 120.585315, "name": "苏州市"}]

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值