简单示例代码

This commit is contained in:
锦鲤 2025-03-07 00:24:33 +08:00
parent 806c5eda5e
commit c827566d03
4 changed files with 408 additions and 0 deletions

181
amap_route_planning.html Normal file
View File

@ -0,0 +1,181 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
<title>地点关键字 + 驾车路线规划</title> // 手动初始化定位版本
<style type="text/css">
html,
body,
#container {
width: 100%;
height: 100%;
}
#panel {
position: fixed;
background-color: white;
max-height: 90%;
overflow-y: auto;
top: 10px;
right: 10px;
width: 280px;
}
#panel .amap-call {
background-color: #009cf9;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
#panel .amap-lib-driving {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
overflow: hidden;
}
#input-container {
position: fixed;
top: 10px;
left: 10px;
background-color: white;
padding: 10px;
border-radius: 4px;
box-shadow: 0 2px 6px rgba(0,0,0,0.3);
z-index: 1000;
}
#input-container input {
margin-bottom: 10px;
padding: 5px;
width: 200px;
display: block; /* 每个输入框单独一行 */
}
#input-container button {
padding: 5px 10px;
background-color: #009cf9;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
width: 100%; /* 按钮宽度与输入框一致 */
}
</style>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id="container"></div>
<div id="input-container">
<input type="text" id="start-input" placeholder="输入起点">
<input type="text" id="end-input" placeholder="输入终点">
<button onclick="planRoute()">规划路线</button>
</div>
<div id="panel"></div>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: "安全秘钥",
};
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=高德KEY&plugin=AMap.Driving,AMap.AutoComplete,AMap.PlaceSearch"></script>
<script type="text/javascript">
//基本地图加载
var map = new AMap.Map("container", {
resizeEnable: true,
center: [114.202549, 22.66327], // 初始地图中心点(北京)
zoom: 15 //地图显示的缩放级别
});
//构造路线导航类
var driving = new AMap.Driving({
map: map,
panel: "panel"
});
// 存储起点和终点的城市信息
var startCity, endCity;
// 初始化起点和终点的自动补全
AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], function() {
var placeSearch = new AMap.PlaceSearch({
map: map
});
// 起点自动补全
var startAuto = new AMap.AutoComplete({
input: "start-input"
});
// 监听起点选择事件
startAuto.on("select", function(e) {
if (e.poi && e.poi.city) {
startCity = e.poi.city; // 获取起点的城市
console.log("获取到的起点城市信息:", startCity); // 输出城市信息
// 根据起点设置地图中心点
placeSearch.search(e.poi.name, function(status, result) {
if (status === 'complete' && result.poiList.pois.length > 0) {
var location = result.poiList.pois[0].location;
console.log("获取到的起点经纬度:", location); // 输出经纬度信息
map.setCenter([location.lng, location.lat]); // 设置地图中心点
} else {
console.error("获取起点经纬度失败,状态:", status, "结果:", result); // 输出错误信息
}
});
} else {
startCity = ''; // 如果未获取到城市信息,设置为空
console.warn("未获取到起点城市信息,使用默认城市"); // 输出警告信息
}
});
// 终点自动补全
var endAuto = new AMap.AutoComplete({
input: "end-input"
});
// 监听终点选择事件
endAuto.on("select", function(e) {
if (e.poi && e.poi.city) {
endCity = e.poi.city; // 获取终点的城市
console.log("获取到的终点城市信息:", endCity); // 输出城市信息
// 根据终点设置地图中心点
placeSearch.search(e.poi.name, function(status, result) {
if (status === 'complete' && result.poiList.pois.length > 0) {
var location = result.poiList.pois[0].location;
console.log("获取到的终点经纬度:", location); // 输出经纬度信息
map.setCenter([location.lng, location.lat]); // 设置地图中心点
} else {
console.error("获取终点经纬度失败,状态:", status, "结果:", result); // 输出错误信息
}
});
} else {
endCity = ''; // 如果未获取到城市信息,设置为空
console.warn("未获取到终点城市信息,使用默认城市"); // 输出警告信息
}
});
});
// 规划路线函数
function planRoute() {
var start = document.getElementById('start-input').value;
var end = document.getElementById('end-input').value;
if (!start || !end) {
alert('请输入起点和终点');
return;
}
// 根据起终点名称规划驾车导航路线
driving.search([
{keyword: start, city: startCity || '全国'}, // 使用起点的城市,如果未获取到则默认全国
{keyword: end, city: endCity || '全国'} // 使用终点的城市,如果未获取到则默认全国
], function(status, result) {
// result 即是对应的驾车导航信息,相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
if (status === 'complete') {
log.success('绘制驾车路线完成');
console.log(result); // 输出路线规划结果
} else {
log.error('获取驾车数据失败:' + result);
}
});
}
</script>
</body>
</html>

92
baidu_map.py Normal file
View File

@ -0,0 +1,92 @@
#!/usr/bin/env python
# -*-coding:utf-8 -*-
'''
# @Author :幸运锦鲤
# @Time : 2025-03-07 00:14:56
# @version : python3
# @Update time :
# @Description : 百度地图坐标转换示例代码
'''
import math
def bd09_to_gcj02(bd_lon, bd_lat):
"""
BD-09 坐标系转换为 GCJ-02 坐标系
:param bd_lon: BD-09 经度
:param bd_lat: BD-09 纬度
:return: GCJ-02 坐标 (lon, lat)
"""
x = bd_lon - 0.0065
y = bd_lat - 0.006
z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * math.pi)
theta = math.atan2(y, x) - 0.000003 * math.cos(x * math.pi)
gcj_lon = z * math.cos(theta)
gcj_lat = z * math.sin(theta)
return gcj_lon, gcj_lat
def gcj02_to_wgs84(gcj_lon, gcj_lat):
"""
GCJ-02 坐标系转换为 WGS-84 坐标系
:param gcj_lon: GCJ-02 经度
:param gcj_lat: GCJ-02 纬度
:return: WGS-84 坐标 (lon, lat)
"""
a = 6378245.0 # 克拉索夫斯基椭球参数长半轴
ee = 0.00669342162296594323 # 克拉索夫斯基椭球参数第一偏心率平方
PI = math.pi
# 转换公式
dLat = transform_lat(gcj_lon - 105.0, gcj_lat - 35.0)
dLon = transform_lon(gcj_lon - 105.0, gcj_lat - 35.0)
radLat = gcj_lat / 180.0 * PI
magic = math.sin(radLat)
magic = 1 - ee * magic * magic
sqrtMagic = math.sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI)
dLon = (dLon * 180.0) / (a / sqrtMagic * math.cos(radLat) * PI)
wgs_lon = gcj_lon - dLon
wgs_lat = gcj_lat - dLat
return wgs_lon, wgs_lat
def transform_lat(x, y):
"""
纬度转换公式
"""
ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
ret += (20.0 * math.sin(y * math.pi) + 40.0 * math.sin(y / 3.0 * math.pi)) * 2.0 / 3.0
ret += (160.0 * math.sin(y / 12.0 * math.pi) + 320 * math.sin(y * math.pi / 30.0)) * 2.0 / 3.0
return ret
def transform_lon(x, y):
"""
经度转换公式
"""
ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
ret += (20.0 * math.sin(6.0 * x * math.pi) + 20.0 * math.sin(2.0 * x * math.pi)) * 2.0 / 3.0
ret += (20.0 * math.sin(x * math.pi) + 40.0 * math.sin(x / 3.0 * math.pi)) * 2.0 / 3.0
ret += (150.0 * math.sin(x / 12.0 * math.pi) + 300.0 * math.sin(x / 30.0 * math.pi)) * 2.0 / 3.0
return ret
def bd09_to_wgs84(bd_lon, bd_lat):
"""
BD-09 坐标系转换为 WGS-84 坐标系
:param bd_lon: BD-09 经度
:param bd_lat: BD-09 纬度
:return: WGS-84 坐标 (lon, lat)
"""
# 先将 BD-09 转换为 GCJ-02
gcj_lon, gcj_lat = bd09_to_gcj02(bd_lon, bd_lat)
# 再将 GCJ-02 转换为 WGS-84
wgs_lon, wgs_lat = gcj02_to_wgs84(gcj_lon, gcj_lat)
return wgs_lon, wgs_lat
# 示例
bd_lon, bd_lat = 116.510484,39.896936 # 百度地图坐标
wgs_lon, wgs_lat = bd09_to_wgs84(bd_lon, bd_lat)
print(f"WGS-84 坐标: ({wgs_lon}, {wgs_lat})")

57
crc16_test.py Normal file
View File

@ -0,0 +1,57 @@
#!/usr/bin/env python
# -*-coding:utf-8 -*-
'''
# @Author :幸运锦鲤
# @Time : 2025-03-07 00:22:47
# @version : python3
# @Update time :
# @Description : crc16校验码计算示例代码
'''
def crc16(data: str) -> str:
# 将输入字符串按空格分割,并将每个部分转换为字节
byte_list = [int(byte, 16) for byte in data.split()]
# 计算CRC16校验码
crc = 0xFFFF
for b in byte_list:
cur_byte = 0xFF & b
for _ in range(0, 8):
if (crc & 0x0001) ^ (cur_byte & 0x0001):
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
cur_byte >>= 1
# 将CRC16校验码转换为大端序高位在前
crc = ((crc & 0xFF) << 8) | (crc >> 8)
# 将CRC16校验码转换为两位十六进制字符串
crc_high = (crc >> 8) & 0xFF
crc_low = crc & 0xFF
crc_str = f"{crc_high:02X}{crc_low:02X}"
# 返回原始数据加上CRC16校验码的字符串无空格
return f"{data.replace(' ', '')}{crc_str}"
# 示例用法
input_data = "01 03 00 00 00 01"
result = crc16(input_data)
print(result) # 输出: "010300000001840A"
input_data = "07 04 00 00 00 02"
result = crc16(input_data)
print(result)
input_data = "05 06 00 00 00 01"
result = crc16(input_data)
print(result)
spaced_hex_str = ' '.join(result[i:i+2] for i in range(0, len(result), 2))
print("result:",spaced_hex_str)

78
ups_info.py Normal file
View File

@ -0,0 +1,78 @@
#!/usr/bin/env python
# -*-coding:utf-8 -*-
'''
# @Author :幸运锦鲤
# @Time : 2025-02-02 16:09:53
# @version : python3
# @Update time :
# @Description : UPS信息获取用于后期处理示例代码
'''
from pynut2 import nut2 as PyNUT
import json
class UPSInfo:
def __init__(self, nut_server='127.0.0.1', nut_port=3493, ups_name='my_ups_name'):
"""初始化UPSInfo实例"""
self.nut_server = nut_server
self.nut_port = nut_port
self.ups_name = ups_name
def build_nested_dict(self, d, keys, value):
"""辅助函数,用于递归构建嵌套字典"""
if len(keys) == 1:
d[keys[0]] = value
else:
if keys[0] not in d:
d[keys[0]] = {}
self.build_nested_dict(d[keys[0]], keys[1:], value)
def get_ups_data(self):
"""获取UPS数据并返回JSON格式"""
try:
client = PyNUT.PyNUTClient(host=self.nut_server, port=self.nut_port)
ups_vars = client.list_vars(self.ups_name)
# 组织数据为字典形式
ups_data = {}
for key, value in ups_vars.items():
parts = key.split(':')
self.build_nested_dict(ups_data, parts, value)
# 返回JSON格式字符串
return json.dumps(ups_data, indent=4)
except Exception as e:
# 返回错误信息的JSON
error_response = {
"error": "Failed to retrieve UPS data",
"details": str(e)
}
return json.dumps(error_response, indent=4)
def get_ups_data_as_dict(self):
"""获取UPS数据并返回字典格式"""
try:
client = PyNUT.PyNUTClient(host=self.nut_server, port=self.nut_port)
ups_vars = client.list_vars(self.ups_name)
# 组织数据为字典形式
ups_data = {}
for key, value in ups_vars.items():
parts = key.split(':')
self.build_nested_dict(ups_data, parts, value)
# 返回字典
return ups_data
except Exception as e:
# 返回错误信息的字典
return {
"error": "Failed to retrieve UPS data",
"details": str(e)
}
if __name__ == '__main__':
# 示例调用,方便测试
ups_info = UPSInfo(nut_server="192.168.100.100", nut_port=3493, ups_name="ups")
print(ups_info.get_ups_data())