批量计算自驾通勤距离网页程序
近日给客户做了一个网页小工具,方便客户批量计算通勤距离
运行截图:
html代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>批量通勤距离计算</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } .container { max-width: 800px; margin: 0 auto; } textarea { width: 100%; height: 150px; padding: 10px; border: 1px solid #ccc; border-radius: 4px; margin-bottom: 20px; } button { padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #0056b3; } .result { margin-top: 20px; } .result table { width: 100%; border-collapse: collapse; margin-top: 10px; } .result th, .result td { border: 1px solid #ccc; padding: 10px; text-align: left; } </style> </head> <body> <div> <h1>批量通勤距离计算</h1> <textarea id="inputData" placeholder="每行输入一组起点和终点,用逗号分隔。例如: 北京市海淀区上地十街10号,北京市朝阳区三里屯路 上海市浦东新区陆家嘴,上海市徐家汇"></textarea> <button onclick="calculateDistance()">计算距离</button> <div> <h2>计算结果</h2> <table id="resultTable"> <thead> <tr> <th>起点</th> <th>终点</th> <th>距离(公里)</th> <th>预计时间(分钟)</th> </tr> </thead> <tbody> <!-- 结果将动态插入到这里 --> </tbody> </table> </div> </div> <script> // 计算距离 async function calculateDistance() { const inputData = document.getElementById('inputData').value; // 解析输入数据 const lines = inputData.split('\n').filter(line => line.trim() !== ''); const data = lines.map(line => { const [origin, destination] = line.split(',').map(item => item.trim()); return { origin, destination }; }); // 检查是否有有效数据 if (data.length === 0) { alert('请输入至少一组起点和终点!'); return; } // 清空结果表 const resultTbody = document.querySelector('#resultTable tbody'); resultTbody.innerHTML = ''; // 逐条处理数据 for (let i = 0; i < data.length; i++) { const item = data[i]; try { // 发送单条数据到后端 const response = await fetch('calculate_distance.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(item) }); // 解析响应 const result = await response.json(); // 显示结果 const row = document.createElement('tr'); row.innerHTML = ` <td>${result.origin}</td> <td>${result.destination}</td> <td>${result.distance || '-'}</td> <td>${result.duration || '-'}</td> `; resultTbody.appendChild(row); } catch (error) { console.error('请求失败:', error); alert('请求失败,请稍后重试。'); } } } </script> </body> </html>
php代码