You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Software_Architecture/distance-judgement/mobile/gps_test.html

312 lines
11 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GPS连接测试</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background: #f0f0f0;
color: #333;
}
.container {
max-width: 600px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.status-box {
padding: 15px;
margin: 10px 0;
border-radius: 5px;
font-weight: bold;
}
.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.info {
background: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
.warning {
background: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
margin: 5px;
}
button:hover {
background: #0056b3;
}
button:disabled {
background: #6c757d;
cursor: not-allowed;
}
.log {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 5px;
padding: 10px;
height: 200px;
overflow-y: auto;
font-family: monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div class="container">
<h1>📍 GPS连接测试工具</h1>
<div class="status-box info">
<strong>当前状态:</strong>
<div id="status">初始化中...</div>
</div>
<div class="status-box" id="gpsBox">
<strong>GPS坐标</strong>
<div id="gpsCoords">等待获取...</div>
</div>
<div class="status-box" id="connectionBox">
<strong>服务器连接:</strong>
<div id="connectionStatus">未测试</div>
</div>
<div style="text-align: center; margin: 20px 0;">
<button onclick="requestGPS()">请求GPS权限</button>
<button onclick="testConnection()">测试服务器连接</button>
<button onclick="sendTestData()" id="sendBtn" disabled>发送测试数据</button>
<button onclick="clearLog()">清空日志</button>
</div>
<div class="warning">
<strong>⚠️ 重要提示:</strong><br>
• 现代浏览器在HTTP模式下可能限制GPS访问<br>
• 请确保允许浏览器访问位置信息<br>
• 在室外或窗边可获得更好的GPS信号<br>
• 首次访问需要用户授权位置权限
</div>
<h3>📋 操作日志</h3>
<div class="log" id="logArea"></div>
</div>
<script>
let currentPosition = null;
let serverConnected = false;
const serverHost = window.location.hostname;
const serverPort = window.location.port || 5000;
const serverProtocol = window.location.protocol;
const baseURL = `${serverProtocol}//${serverHost}:${serverPort}`;
function log(message, type = 'info') {
const logArea = document.getElementById('logArea');
const timestamp = new Date().toLocaleTimeString();
const entry = `[${timestamp}] ${message}\n`;
logArea.textContent += entry;
logArea.scrollTop = logArea.scrollHeight;
console.log(`[${type}] ${message}`);
}
function updateStatus(message, type = 'info') {
const statusDiv = document.getElementById('status');
statusDiv.textContent = message;
statusDiv.style.color = type === 'success' ? '#155724' :
type === 'error' ? '#721c24' : '#0c5460';
}
function updateGPSBox(message, type = 'info') {
const gpsBox = document.getElementById('gpsBox');
document.getElementById('gpsCoords').textContent = message;
gpsBox.className = `status-box ${type}`;
}
function updateConnectionBox(message, type = 'info') {
const connBox = document.getElementById('connectionBox');
document.getElementById('connectionStatus').textContent = message;
connBox.className = `status-box ${type}`;
}
function requestGPS() {
log('开始请求GPS权限...');
updateStatus('正在请求GPS权限...');
if (!('geolocation' in navigator)) {
log('❌ 设备不支持GPS定位', 'error');
updateGPSBox('设备不支持GPS', 'error');
return;
}
const options = {
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 10000
};
navigator.geolocation.getCurrentPosition(
(position) => {
currentPosition = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
timestamp: Date.now()
};
const gpsText = `${position.coords.latitude.toFixed(6)}, ${position.coords.longitude.toFixed(6)}`;
const accuracyText = `精度: ${position.coords.accuracy.toFixed(0)}m`;
log(`✅ GPS获取成功: ${gpsText} (${accuracyText})`, 'success');
updateGPSBox(`${gpsText}\n${accuracyText}`, 'success');
updateStatus('GPS权限获取成功', 'success');
document.getElementById('sendBtn').disabled = !serverConnected;
},
(error) => {
let errorMsg = '';
switch (error.code) {
case error.PERMISSION_DENIED:
errorMsg = '用户拒绝了位置访问请求';
break;
case error.POSITION_UNAVAILABLE:
errorMsg = '位置信息不可用';
break;
case error.TIMEOUT:
errorMsg = '位置获取超时';
break;
default:
errorMsg = '未知位置错误';
break;
}
log(`❌ GPS获取失败: ${errorMsg}`, 'error');
updateGPSBox(`获取失败: ${errorMsg}`, 'error');
updateStatus('GPS权限获取失败', 'error');
if (error.code === error.PERMISSION_DENIED) {
log('💡 请在浏览器中允许位置访问权限', 'info');
}
},
options
);
}
async function testConnection() {
log('开始测试服务器连接...');
updateStatus('正在测试服务器连接...');
try {
const testData = {
device_id: 'test_device_' + Date.now(),
test: true
};
const response = await fetch(`${baseURL}/mobile/ping`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(testData)
});
if (response.ok) {
const data = await response.json();
log(`✅ 服务器连接成功: ${baseURL}`, 'success');
updateConnectionBox(`连接成功: ${baseURL}`, 'success');
updateStatus('服务器连接正常', 'success');
serverConnected = true;
document.getElementById('sendBtn').disabled = !currentPosition;
} else {
throw new Error(`HTTP ${response.status}`);
}
} catch (error) {
log(`❌ 服务器连接失败: ${error.message}`, 'error');
updateConnectionBox(`连接失败: ${error.message}`, 'error');
updateStatus('服务器连接失败', 'error');
serverConnected = false;
}
}
async function sendTestData() {
if (!currentPosition || !serverConnected) {
log('❌ 请先获取GPS并测试服务器连接', 'error');
return;
}
log('发送测试数据到服务器...');
updateStatus('正在发送测试数据...');
try {
const testData = {
device_id: 'gps_test_' + Date.now(),
device_name: 'GPS测试设备',
timestamp: Date.now(),
gps: currentPosition,
battery: 100,
test_mode: true
};
const response = await fetch(`${baseURL}/mobile/upload`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(testData)
});
if (response.ok) {
log('✅ 测试数据发送成功', 'success');
updateStatus('测试数据发送成功', 'success');
} else {
throw new Error(`HTTP ${response.status}`);
}
} catch (error) {
log(`❌ 测试数据发送失败: ${error.message}`, 'error');
updateStatus('测试数据发送失败', 'error');
}
}
function clearLog() {
document.getElementById('logArea').textContent = '';
}
// 页面加载时自动初始化
window.onload = function () {
log('GPS连接测试工具已加载');
log(`服务器地址: ${baseURL}`);
log(`协议: ${serverProtocol.replace(':', '')}, 主机: ${serverHost}, 端口: ${serverPort}`);
updateStatus('就绪 - 点击按钮开始测试');
};
</script>
</body>
</html>