高德地图地址和经纬度的转换
1. 地址转经纬度
import requests
def addressToLocation(address):
"""
将地址转换为经纬度
:param address: 地址
:return: 经度和维度
"""
# 在高德地图开发者平台(https://lbs.amap.com/)申请的key,需要替换为自己的key
parameters = {
'key': '0610416f549978a9ce5017dab6195a5b',
'address': address,
}
base = 'http://restapi.amap.com/v3/geocode/geo?'
contest = requests.get(base,parameters).json()
location = contest['geocodes'][0]['location']
return location
if __name__ == '__main__':
print(addressToLocation("北京西站"))
运行结果
116.323294,39.893874
2. 经纬度转地址
非高德坐标转成高德坐标
import requests
def transform(location):
"""
坐标转换,将非高德坐标(GPS坐标、mapbar坐标、baidu坐标)转换为高德坐标
"""
parameters = {
'coordsys': 'gps',
'locations': location,
'key': '0610416f549978a9ce5017dab6195a5b'
}
base = 'http://restapi.amap.com/v3/assistant/coordinate/convert?'
response = requests.get(base, parameters)
answer = response.json()
return answer['locations']
if __name__ == '__main__':
location = '116.192386,39.533795' # 非高德坐标
print(transform(location))
运行结果
116.198459743924,39.535011664497
高德地图经纬度转地址
import requests
def locationToAddress(location):
"""
将经纬度转换为地址
所以选用的是逆地理编码的接口
:param location: 经纬度,格式为 经度+','+维度,例如:location='116.323294,39.893874'
:return:返回地址所在区,以及详细地址
"""
parameters = {
'location': location,
'key': '0610416f549978a9ce5017dab6195a5b'
}
base = 'http://restapi.amap.com/v3/geocode/regeo?'
response = requests.get(base, parameters)
answer = response.json() #.encode('gbk','replace')
return answer['regeocode']['addressComponent']['district'],answer['regeocode']['formatted_address']
if __name__ == '__main__':
location = '116.323294,39.893874'
print(locationToAddress(location))
运行结果
(‘丰台区’, ‘北京市丰台区太平桥街道北京西站’)