准备材料:
1、搭建python环境
2、注册高德api link
3、获取key link (注册后,才能打开该网站以及下述网站)
3、阅读api说明文档
获取城市经纬度链接: link
获取城市间的距离、火车时间等: link
使用高德地图API,根据城市名称获取其地理坐标(经纬度)。这一过程首先构建请求URL,然后发送HTTP请求,最后解析返回的JSON数据以提取所需信息。
import requests
CenterCity_name = ['上海市', "深圳市", "北京市", "广州市", "杭州市"]
BorderCity_name = ['巴彦淖尔市', '白山市', '百色市', '包头市', '保山市', '丹东市', '防城港市', '哈密市', '鹤岗市', '黑河市', '呼伦贝尔市', '鸡西市', '佳木斯市', '酒泉市','林芝市', '临沧市', '牡丹江市', '南宁市', '普洱市', '日喀则市', '山南市', '双鸭山市', '通化市', '乌兰察布市','伊春市']
city_location = []
border_city_location = []
#获取指定城市(如上海市)的经纬度
def get_city_location(city_name):
url = f'https://restapi.amap.com/v3/config/district?keywords={city_name}&subdistrict=2&key=<准备材料中获取的key>'
response = requests.get(url)
json_data = response.json()
if json_data['districts'] and len(json_data['districts']) > 0:
return json_data['districts'][0]['center']
else:
print(f"{city_name}信息列表为空")
return None
for city in CenterCity_name:
location = get_city_location(city)
if location:
city_location.append(location)
for city in BorderCity_name:
location = get_city_location(city)
if location:
border_city_location.append(location)
print("Center City Locations:", city_location)
print("Border City Locations:", border_city_location)
通过构建请求URL,从高德地图API获取边境城市到中心城市的交通数据,包括距离(米)、时间(秒)和费用(元)。
##### 获取BorderCity至CenterCity需要花费的时间、距离和金钱 #####
data = []
for center_city, center_loc in city_location.items():
for border_city, border_loc in border_city_location.items():
if center_loc and border_loc:
url = f'https://restapi.amap.com/v5/direction/transit/integrated?origin={border_loc}&destination={center_loc}&show_fields=cost&key=<准备材料中获取的key>'
response = requests.get(url)
json_data = response.json()
if json_data.get('route') and json_data['route'].get('transits'):
transits = json_data['route']['transits'][0]
distance = transits['distance'] #获取城市间的距离,单位:米
duration = int(transits['cost']['duration']) #获取城市间的时间,单位:秒
time = duration / 3600 #获取城市间的时间,单位:小时
tolls = transits['cost']['transit_fee'] #获取城市间的所需成本,单位:元
data.append([border_city, center_city, distance, time, tolls])
else:
print(f"{border_city} 转乘信息列表为空")
将获取的交通数据写入CSV文件中,方便后续分析和应用。
with open('city_data.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(["Border City", "Center City", "Distance (m)", "Time (h)", "Tolls (CNY)"])
writer.writerows(data)
打开city_data.csv表格,如下图所示
import requests
import csv
### 研究区城市 ###
CenterCity_name = ['上海市', "深圳市", "北京市", "广州市", "杭州市"]
BorderCity_name = ['巴彦淖尔市', '白山市', '百色市', '包头市', '保山市', '丹东市', '防城港市', '哈密市', '鹤岗市', '黑河市', '呼伦贝尔市', '鸡西市', '佳木斯市', '酒泉市','林芝市', '临沧市', '牡丹江市', '南宁市', '普洱市', '日喀则市', '山南市', '双鸭山市', '通化市', '乌兰察布市','伊春市']
##### 获取上述城市的地理坐标 #####
def get_city_location(city_name):
url = f'https://restapi.amap.com/v3/config/district?keywords={city_name}&subdistrict=2&key=03fe3cfb4dcfb788868fd9f352ee3726'
response = requests.get(url)
json_data = response.json()
if json_data['districts']:
return json_data['districts'][0]['center']
else:
print(f"{city_name}信息列表为空")
return None
city_location = {city: get_city_location(city) for city in CenterCity_name}
border_city_location = {city: get_city_location(city) for city in BorderCity_name}
##### 获取BorderCity至CenterCity需要花费的时间、距离和金钱 #####
data = []
for center_city, center_loc in city_location.items():
for border_city, border_loc in border_city_location.items():
if center_loc and border_loc:
url = f'https://restapi.amap.com/v5/direction/transit/integrated?origin={border_loc}&destination={center_loc}&show_fields=cost&key=<准备材料中获取的key>'
response = requests.get(url)
json_data = response.json()
if json_data.get('route') and json_data['route'].get('transits'):
transits = json_data['route']['transits'][0]
distance = transits['distance'] #获取城市间的距离,单位:米
duration = int(transits['cost']['duration']) #获取城市间的时间,单位:秒
time = duration / 3600 #获取城市间的时间,单位:小时
tolls = transits['cost']['transit_fee'] #获取城市间的所需成本,单位:元
data.append([border_city, center_city, distance, time, tolls])
else:
print(f"{border_city} 转乘信息列表为空")
##### 将数据写入CSV文件 #####
with open('city_data.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(["Border City", "Center City", "Distance (m)", "Time (h)", "Tolls (CNY)"])
writer.writerows(data)
print("数据已成功写入 city_data.csv 文件。")
通过上述方法,我成功获取了125条城市间的交通数据,并存储在CSV文件中。这些数据可以用于分析不同城市之间的交通连接性和便捷性,为城市交通规划提供数据支持,优化交通布局,结合社会经济数据,分析交通成本对经济发展的影响等。