首页 > 代码库 > 高德地图api实现地址和经纬度的转换(python)

高德地图api实现地址和经纬度的转换(python)

利用高德地图web服务api实现地理/逆地址编码

api使用具体方法请查看官方文档

文档网址:http://lbs.amap.com/api/webservice/guide/api/georegeo/

 

1.利用python第三方库requests实现

Requests库文档地址:http://www.python-requests.org/en/master/

 1 #!/usr/bin/env python3
 2 #-*- coding:utf-8 -*-
 3 ‘‘‘
 4 利用高德地图api实现地址和经纬度的转换
 5 ‘‘‘
 6 import requests
 7 
 8 def geocode(address):
 9         parameters = {address: address, key: cb649a25c1f81c1451adbeca73623251}
10         base = http://restapi.amap.com/v3/geocode/geo
11         response = requests.get(base, parameters)
12         answer = response.json()
13         print(address + "的经纬度:", answer[geocodes][0][location])
14 
15 if __name__==__main__:
16         #address = input("请输入地址:")
17         address = 北京市海淀区
18         geocode(address)

 

2.基于http协议利用标准库http.client实现

 1 #!/usr/bin/env python3
 2 #-*- coding:utf-8 -*-
 3 ‘‘‘
 4 利用高德地图api实现地址和经纬度的转换
 5 ‘‘‘
 6 
 7 
 8 import http.client
 9 import json
10 from urllib.parse import quote_plus
11 
12 base = /v3/geocode/geo
13 key  = cb649a25c1f81c1451adbeca73623251
14 
15 def geocode(address):
16         path = {}?address={}&key={}.format(base, quote_plus(address), key)
17         #print(path)
18         connection = http.client.HTTPConnection(restapi.amap.com,80)
19         connection.request(GET, path)
20         rawreply = connection.getresponse().read()
21         #print(rawreply)
22         reply = json.loads(rawreply.decode(utf-8))
23         print(address + 的经纬度:,reply[geocodes][0][location])
24 
25 if __name__==__main__:
26         #address = input("请输入你的地址:")
27         address = 北京市朝阳区
28         geocode(address)

 

3.利用基于传输层上socket实现

 1 #!/usr/bin/env python3
 2 #-*- coding:utf-8 -*-
 3 
 4 import socket
 5 from urllib.parse import quote_plus
 6 
 7 request_text = """ 8 GET /v3/geocode/geo?address={}&key=cb649a25c1f81c1451adbeca73623251 HTTP/1.1\r\n 9 Host: restapi.amap.com:80\r\n10 User-Agent: search4.py\r\n11 Connection: close\r\n12 \r\n13 """
14 
15 def geocode(address):
16         sock = socket.socket()
17         sock.connect((restapi.amap.com, 80))
18         request = request_text.format(quote_plus(address))
19         sock.sendall(request.encode(ascii))
20         raw_reply = b‘‘
21         while True:
22                 more = sock.recv(4096)
23                 if not more:
24                         break
25                 raw_reply += more
26         print(raw_reply.decode(utf-8))
27 
28 if __name__==__main__:
29         #address = input("请输入地址:")
30         address = 北京市朝阳区
31         geocode(address)

 

高德地图api实现地址和经纬度的转换(python)