使用python获取城市经纬度以及城市间的距离、火车时间、所需成本等


本案例研究选择了中国的五个中心城市(上海市、深圳市、北京市、广州市、杭州市)和25个边境城市(如巴彦淖尔市、白山市等)作为研究对象。通过调用高德地图API( https://lbs.amap.com/api )来获取城市的地理坐标及从边境城市到中心城市的交通数据,包括距离、时间和费用。

准备材料:
1、搭建python环境
2、注册高德api link
3、获取key link (注册后,才能打开该网站以及下述网站)
3、阅读api说明文档
获取城市经纬度链接: link
在这里插入图片描述

获取城市间的距离、火车时间等: link
在这里插入图片描述

1 获取城市地理坐标

使用高德地图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)

2 获取交通数据

通过构建请求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} 转乘信息列表为空")

3 数据存储

将获取的交通数据写入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表格,如下图所示
在这里插入图片描述

4 代码整合

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文件中。这些数据可以用于分析不同城市之间的交通连接性和便捷性,为城市交通规划提供数据支持,优化交通布局,结合社会经济数据,分析交通成本对经济发展的影响等。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 02:10:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 02:10:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 02:10:03       57 阅读
  4. Python语言-面向对象

    2024-07-14 02:10:03       68 阅读

热门阅读

  1. 代码随想录算法训练营第31天 | 第九章动态规划02

    2024-07-14 02:10:03       21 阅读
  2. ES6 Class 的继承(十一)

    2024-07-14 02:10:03       21 阅读
  3. springboot整合vue上传文件至oss

    2024-07-14 02:10:03       20 阅读
  4. 差点被这个Kafka的删除策略难住了

    2024-07-14 02:10:03       18 阅读
  5. Go语言map并发安全,互斥锁和读写锁谁更优?

    2024-07-14 02:10:03       22 阅读
  6. 调用 create_meshgrid 函数时出现了 TypeError

    2024-07-14 02:10:03       17 阅读
  7. 学院教学信息管理系统(c++)

    2024-07-14 02:10:03       16 阅读