通过Google API获得位置的经纬度

时间:2022-10-18 19:24:34

通过Google API获得位置的经纬度

KEY需要在google获取。

import json
from urllib.parse import quote
from urllib.request import urlopen

KEY = 'AIzaSyA0P56jBuEQRbe2IUnzBfmnK_beo2aYln8'


def get_address(address, key):
    url = 'https://maps.googleapis.com/maps/api/geocode/json?' + 'address=' + address + '&key=' + key
    # 中文url需要转码才能识别
    # url = quote(url, ':?=/')
    print(url)
    response = urlopen(url).read().decode('utf-8')  # response is str
    response_json = json.loads(response)  # response_json is dict
    print(response_json)
    lat = response_json.get('results')[0]['geometry']['location']['lat']
    lng = response_json.get('results')[0]['geometry']['location']['lng']
    print(address + '的经纬度是: %f, %f' % (lat, lng))
    return lat, lng