1+ import pandas as pd
2+ import requests
3+ import json
4+ import csv
5+ import codecs
6+
7+ # 创建导出文件
8+ with open (r'..\document\village.csv' , 'wb+' )as fp :
9+ fp .write (codecs .BOM_UTF8 )
10+ f = open (r'..\document\village.csv' ,'w+' ,newline = '' , encoding = 'utf-8' )
11+ writer = csv .writer (f )
12+ writer .writerow (("小区名" , "坐标" , "步行距离-地点1" ,"通勤时间-地点1" , "步行距离-地点2" ,"通勤时间-地点2" ))
13+
14+ geourl = 'https://restapi.amap.com/v3/geocode/geo'
15+ puburl = 'https://restapi.amap.com/v3/direction/transit/integrated?origin={}&destination={}&key={}&time=9:00&city=上海'
16+
17+ # 读取文件
18+ csv_read = pd .read_csv ('../document/sh.csv' ,header = None )
19+ village_set = set (csv_read [2 ])
20+ village_list = list (village_set )
21+
22+ # 获取第一个坐标
23+ geourl = 'https://restapi.amap.com/v3/geocode/geo'
24+ # 地址前要加地区名,否则可能定位到其他城市
25+ params = {'key' :'在这里填入个人的Key值' ,
26+ 'address' : '上海市国金中心' }
27+ # 发送请求
28+ res = requests .get (geourl , params )
29+ jd = json .loads (res .text )
30+ # 返回值的具体格式可以在API文档中查看
31+ geopoint_1 = jd ['geocodes' ][0 ]['location' ]
32+
33+ # 获取第二个坐标
34+ params = {'key' :'在这里填入个人的Key值' ,
35+ 'address' : '上海市国正中心' }
36+ res = requests .get (geourl , params )
37+ jd = json .loads (res .text )
38+ geopoint_2 = jd ['geocodes' ][0 ]['location' ]
39+
40+ for adr in village_list :
41+ # 获取小区坐标
42+ params = {'key' :'在这里填入个人的Key值' ,
43+ 'address' : '上海市' + adr }
44+ res = requests .get (geourl , params )
45+ jd = json .loads (res .text )
46+ geopoint = jd ['geocodes' ][0 ]['location' ]
47+
48+ # 获取第一个位置的信息
49+ r = requests .get (puburl .format (geopoint_1 , geopoint , '在这里填入个人的Key值' ))
50+ r = r .text
51+ jsonData = json .loads (r )
52+ publength_1 = round (int (jsonData ['route' ]['transits' ][0 ]['walking_distance' ])/ 1000 , 2 )
53+ pubtime_1 = round (int (jsonData ['route' ]['transits' ][0 ]['duration' ])/ 60 )
54+
55+ # 获取第二个位置的信息
56+ r = requests .get (puburl .format (geopoint_2 , geopoint , '在这里填入个人的Key值' ))
57+ r = r .text
58+ jsonData = json .loads (r )
59+ publength_2 = round (int (jsonData ['route' ]['transits' ][0 ]['walking_distance' ])/ 1000 , 2 )
60+ pubtime_2 = round (int (jsonData ['route' ]['transits' ][0 ]['duration' ])/ 60 )
61+
62+ writer .writerow ((adr , geopoint , publength_1 , pubtime_1 , publength_2 , pubtime_2 ))
63+
64+ f .close ()
0 commit comments