请求优化Google Maps API里程计算功能:支持文本框输入城市对自动获取驾车英里数
请求优化Google Maps API里程计算功能:支持文本框输入城市对自动获取驾车英里数
Hey there! I've revamped your code to meet your exact need—now users can type in a city pair like Nashville, TN to Atlanta, GA directly into a text field, and the app will automatically parse the origin/destination, calculate the driving distance, and display the miles right away. Here's the cleaned-up, fully functional version:
Full Working Code
<!DOCTYPE html> <html> <head> <title>Route Miles Calculator</title> <script src="https://maps.googleapis.com/maps/api/js?key=MY API GOES HERE"></script> <style> body { font-family: sans-serif; padding: 20px; } .calculator-container { margin-bottom: 20px; } #route-input { padding: 8px; width: 350px; font-weight: bold; margin-right: 10px; } #calculate-btn { padding: 8px 16px; cursor: pointer; background: #2563eb; color: white; border: none; border-radius: 4px; } #calculate-btn:hover { background: #1d4ed8; } #distance-display { font-size: 1.1em; font-weight: bold; color: #1f2937; } </style> </head> <body> <div class="calculator-container"> <label>输入路线(格式:城市, 州 to 城市, 州):</label><br> <input type="text" id="route-input" placeholder="例如:Nashville, TN to Atlanta, GA"> <button id="calculate-btn">计算里程</button> </div> <div id="distance-display">等待输入路线...</div> <script> let directionsService; function initMap() { directionsService = new google.maps.DirectionsService(); // 绑定按钮点击事件 document.getElementById('calculate-btn').addEventListener('click', calculateRouteMiles); // 支持回车直接触发计算 document.getElementById('route-input').addEventListener('keypress', (e) => { if (e.key === 'Enter') calculateRouteMiles(); }); } // 核心计算函数:解析输入并请求API function calculateRouteMiles() { const inputText = document.getElementById('route-input').value.trim(); const displayElement = document.getElementById('distance-display'); // 分割输入的起点和终点(兼容大小写和多余空格) const routeSegments = inputText.split(/\s+to\s+/i); if (routeSegments.length !== 2) { displayElement.textContent = "❌ 请使用正确格式:比如 Nashville, TN to Atlanta, GA"; return; } const origin = routeSegments[0]; const destination = routeSegments[1]; displayElement.textContent = "🔄 正在计算里程..."; // 构造API请求参数 const apiRequest = { origin: origin, destination: destination, travelMode: 'DRIVING', unitSystem: google.maps.UnitSystem.IMPERIAL // 强制返回英里单位 }; // 调用Google Directions API directionsService.route(apiRequest, (result, status) => { if (status === 'OK') { // 提取里程字符串(如"473 mi") const miles = result.routes[0].legs[0].distance.text; displayElement.textContent = `✅ 总驾车里程:${miles}`; } else { // 针对不同错误场景给出友好提示 let errorMsg = "❌ 无法计算里程"; if (status === 'NOT_FOUND') errorMsg += ":地址无法识别,请检查输入"; else if (status === 'ZERO_RESULTS') errorMsg += ":两地之间无可行驾车路线"; displayElement.textContent = errorMsg; } }); } // 页面加载完成后初始化地图服务 window.onload = initMap; </script> </body> </html>
Key Updates I Made
- Flexible Input Handling: The app now parses any input with
to(case-insensitive, ignores extra spaces) to split origin and destination—so messy inputs likeChicago, IL TO Detroit, MIstill work perfectly. - Intuitive UI: Added a clear calculate button (plus Enter key support) for easy triggering, and updated the UI with loading states and emoji hints for quick visual feedback.
- Better Error Feedback: No more generic "Error" messages—users get specific hints for common issues like bad input format or unrecognizable addresses.
- Modular Code: Split logic into reusable functions to make it easier to tweak later (like adding walking/biking modes if you ever need it).
Quick Reminders
- Don't forget to replace
MY API GOES HEREwith your actual Google Maps API key (and make sure the Directions API is enabled for your key in the Google Cloud Console!). - The app is locked to imperial units, so results will always show miles—exactly what you wanted.
- Google Maps can handle more than just city-state pairs! Users can input full addresses, zip codes, or even landmarks as long as they're separated by
to.
If you want to tweak anything (like adding real-time calculation as users type, or supporting other travel modes), just say the word! 😊




