[Python] 纯文本查看 复制代码
import sys
import json
import requests
from math import radians, cos, sin, sqrt, atan2
from PyQt5 import QtWidgets
class MapApp(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.init_ui()
self.load_config()
def init_ui(self):
self.setWindowTitle("百度地图多点路径计算")
self.api_key_label = QtWidgets.QLabel("API密钥:")
self.api_key_input = QtWidgets.QLineEdit(self)
self.origin_label = QtWidgets.QLabel("起点 (地点|经度,纬度):")
self.origin_input = QtWidgets.QLineEdit(self)
self.destination_label = QtWidgets.QLabel("终点 (每行一个地点|经度,纬度):")
self.destination_input = QtWidgets.QTextEdit(self)
self.calculate_button = QtWidgets.QPushButton("计算路径", self)
self.calculate_button.clicked.connect(self.calculate_routes)
self.save_button = QtWidgets.QPushButton("保存配置", self)
self.save_button.clicked.connect(self.save_config)
# 调试信息文本框
self.debug_text = QtWidgets.QTextEdit(self)
self.debug_text.setReadOnly(True)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.api_key_label)
layout.addWidget(self.api_key_input)
layout.addWidget(self.origin_label)
layout.addWidget(self.origin_input)
layout.addWidget(self.destination_label)
layout.addWidget(self.destination_input)
layout.addWidget(self.calculate_button)
layout.addWidget(self.save_button)
layout.addWidget(self.debug_text) # 将调试文本框添加到布局中
self.setLayout(layout)
def load_config(self):
try:
with open('config.json', 'r') as file:
config = json.load(file)
self.api_key_input.setText(config.get("api_key", ""))
self.origin_input.setText(config.get("origin", ""))
self.destination_input.setPlainText(config.get("destination", ""))
except FileNotFoundError:
self.debug_text.append("未找到配置文件,加载默认值。")
def save_config(self):
config = {
"api_key": self.api_key_input.text(),
"origin": self.origin_input.text(),
"destination": self.destination_input.toPlainText(),
}
with open('config.json', 'w') as file:
json.dump(config, file)
self.debug_text.append("配置已保存。")
def parse_location(self, location_str):
"""解析'地点|经度,纬度'格式并返回名称、经度和纬度"""
try:
name, coords = location_str.split('|')
lng, lat = coords.split(',')
return name, float(lat), float(lng)
except ValueError:
self.debug_text.append(f"解析错误: 无效的格式 '{location_str}'")
return None, None, None
def calculate_straight_distance(self, lat1, lon1, lat2, lon2):
"""计算两个经纬度之间的直线距离(单位:公里)"""
R = 6371.0 # 地球半径,单位为公里
dlat = radians(lat2 - lat1)
dlon = radians(lon2 - lon1)
a = sin(dlat / 2)**2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
return round(distance, 2)
def format_duration(self, duration_seconds):
"""格式化导航时间,当时间小于1小时时显示分钟,否则显示小时"""
duration_hours = duration_seconds / 3600
if duration_hours < 1:
duration_minutes = round(duration_seconds / 60)
return f"{duration_minutes} 分钟"
else:
return f"{round(duration_hours, 2)} 小时"
def calculate_routes(self):
api_key = self.api_key_input.text()
origin_str = self.origin_input.text()
destinations_str = self.destination_input.toPlainText().strip().splitlines()
origin_name, origin_lat, origin_lng = self.parse_location(origin_str)
if not origin_name or not origin_lat or not origin_lng:
self.debug_text.append("起点格式错误")
return
# 清空调试文本框内容
self.debug_text.clear()
self.debug_text.append("开始计算路径...\n")
results = []
for destination_str in destinations_str:
dest_name, dest_lat, dest_lng = self.parse_location(destination_str)
if not dest_name or not dest_lat or not dest_lng:
self.debug_text.append(f"终点格式错误: {destination_str}")
continue
# 计算直线距离
straight_distance = self.calculate_straight_distance(origin_lat, origin_lng, dest_lat, dest_lng)
# 输出请求参数到调试文本框
#self.debug_text.append(f"\n计算路径 - 起点: {origin_name}({origin_lat},{origin_lng}) 到 终点: {dest_name}({dest_lat},{dest_lng})")
url = f"https://api.map.baidu.com/directionlite/v1/driving?origin={origin_lat},{origin_lng}&destination={dest_lat},{dest_lng}&ak={api_key}&coord_type=gcj02"
try:
response = requests.get(url)
data = response.json()
if data.get('status') == 0:
route = data['result']['routes'][0]
nav_distance_km = round(route['distance'] / 1000, 2) # 导航距离转换为公里
duration_formatted = self.format_duration(route['duration']) # 格式化时间
# 格式化输出结果
result_text = f"{origin_name} - {dest_name}: 直线距离 {straight_distance} 公里, 导航距离 {nav_distance_km} 公里, 耗时 {duration_formatted}"
results.append(result_text)
#self.debug_text.append(f"结果: {result_text}")
else:
error_msg = f"错误计算路径到 {dest_name}: {data.get('msg')}"
results.append(error_msg)
self.debug_text.append(error_msg)
except Exception as e:
self.debug_text.append(f"异常: {str(e)}")
# 显示所有结果
self.debug_text.append("\n".join(results))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MapApp()
window.resize(800, 600)
window.show()
sys.exit(app.exec_())