python_search

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

python第三方库的使用

利用python第三方库requests实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import requests
def geocodeG(address):
par = {
'address': address,
'key': '21860ea33f506e37966bb669a6e05ff6'
}
base = 'http://restapi.amap.com/v3/geocode/geo'
response = requests.get(base, params=par)
answer = response.json()
mp = answer['geocodes'][0]['location'].split(",")
return mp[0], mp[1]

res = geocodeG("浙江")
print(res)


结果
('120.152791', '30.267446')

HTTP协议的使用

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import http.client
import json
from urllib.parse import quote_plus

base = "/v3/geocode/geo"

def geocode(address):
path = "{}?address={}&key=21860ea33f506e37966bb669a6e05ff6".format(base, quote_plus(address))
connection = http.client.HTTPConnection("restapi.amap.com")
connection.request("GET", path)
rawreplay = connection.getresponse().read()
reply = json.loads(rawreplay.decode("utf-8"))
mp = reply['geocodes'][0]['location'].split(",")
return mp[0], mp[1]



rep = geocode('浙江')
print(rep)


结果
('120.152791', '30.267446')

原始的网络会话

利用基于传输层上socket实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import socket
from urllib.parse import quote_plus

request_text = """\
GET /v3/geocode/geo?address={}&key=21860ea33f506e37966bb669a6e05ff6 HTTP/1.1\r\n\
Host: restapi.amap.com:80\r\n\
User-Agent: Foundations of Python Network Programming example search4.py\r\n\
Connection: close\r\n\
\r\n\
"""


def geocode(address):
sock = socket.socket()
sock.connect(("restapi.amap.com", 80))
request = request_text.format(quote_plus(address))
sock.sendall(request.encode('ascii'))
raw_reply = b''
while True:
more = sock.recv(4096)
if not more:
break
raw_reply += more
print(raw_reply.decode('utf-8'))

if __name__ == '__main__':
geocode('浙江')

结果

HTTP/1.1 200 OK
Server: Tengine
Date: Thu, 06 Aug 2020 08:05:41 GMT
Content-Type: application/json;charset=UTF-8
Content-Length: 344
Connection: close
Vary: Accept-Encoding
gsid: 011026090152159670114194800019907006955
sc: 0.005
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,key,x-biz,x-info,platinfo,encr,enginever,gzipped,poiid

{"status":"1","info":"OK","infocode":"10000","count":"1","geocodes":[{"formatted_address":"浙江省","country":"中国","province":"浙江省","city":[],"district":[],"township":[],"neighborhood":{"name":[],"type":[]},"building":{"name":[],"type":[]},"adcode":"330000","street":[],"number":[],"location":"120.152791,30.267446","level":"省"}]}

地理/逆地理编码api开发文档

https://lbs.amap.com/api/webservice/guide/api/georegeo/