如何在WordPress中实现取货距离(英里)计价功能?
WordPress中基于取货距离的英里计价功能问题求助
我尝试在WordPress中实现基于取货距离的英里计价功能,但至今未成功。当前代码以公里为单位计算,不符合需求,同时不清楚功能失效的原因,以下是我编写的代码及修正方案:
1. 表单短代码(HTML部分)
function google_maps_distance_calculator_shortcode() { ob_start(); ?> <div class="distance-calculator-form"> <form id="distance-calculator-form"> <h2>计算距离与费用</h2> <label for="pickup">取货地点:</label> <input type="text" id="pickup" name="pickup" placeholder="输入取货地点"><br> <label for="destination">目的地:</label> <input type="text" id="destination" name="destination" placeholder="输入目的地"><br> <!-- 添加地图容器,原代码缺失此元素导致地图初始化失败 --> <div id="map" style="height: 300px; width: 100%; margin: 15px 0;"></div> <p>距离: <span id="distance">0 英里</span></p> <p>总费用: <span id="total-cost">$0.00</span></p> <button type="button" id="calculate-button">计算距离与费用</button> </form> </div> <?php return ob_get_clean(); } add_shortcode('google_maps_distance_calculator', 'google_maps_distance_calculator_shortcode');
2. Google Maps API计算距离的JavaScript代码
document.addEventListener('DOMContentLoaded', function() { let map; let directionsService; let directionsRenderer; function initMap() { directionsService = new google.maps.DirectionsService(); directionsRenderer = new google.maps.DirectionsRenderer(); // 检查地图容器是否存在,避免初始化报错 const mapElement = document.getElementById('map'); if (!mapElement) return; map = new google.maps.Map(mapElement, { center: { lat: 37.7749, lng: -122.4194 }, // 替换为更贴合需求的默认坐标 zoom: 10 }); directionsRenderer.setMap(map); } function calculateDistance() { const pickup = document.getElementById('pickup').value; const destination = document.getElementById('destination').value; if (!pickup || !destination) { alert('请输入取货地点和目的地'); return; } const request = { origin: pickup, destination: destination, travelMode: 'DRIVING' }; directionsService.route(request, function(result, status) { if (status === 'OK') { directionsRenderer.setDirections(result); // 将米转换为英里(1米=0.000621371英里) const distanceInMiles = (result.routes[0].legs[0].distance.value * 0.000621371).toFixed(2); const costPerMile = 3; // 自定义每英里计价,可按需修改 const totalCost = (distanceInMiles * costPerMile).toFixed(2); document.getElementById('distance').textContent = `${distanceInMiles} 英里`; document.getElementById('total-cost').textContent = `$${totalCost}`; } else { alert(`无法计算距离: ${status}`); } }); } const calculateBtn = document.getElementById('calculate-button'); if (calculateBtn) { calculateBtn.addEventListener('click', calculateDistance); } initMap(); });
3. 加载Google Maps脚本的PHP代码
function enqueue_google_maps_script() { // 替换YOUR_GOOGLE_MAPS_API_KEY为你的有效API密钥 wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places', null, null, true); } add_action('wp_enqueue_scripts', 'enqueue_google_maps_script');
4. 自定义样式代码
.distance-calculator-form { max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f9f9f9; border: 1px solid #ddd; border-radius: 8px; } .distance-calculator-form label { display: block; margin-bottom: 8px; font-weight: bold; } .distance-calculator-form input[type="text"] { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; } #calculate-button { background-color: #007cba; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; } #calculate-button:hover { background-color: #005f8d; } #distance, #total-cost { font-weight: bold; color: #2d3748; } #map { border-radius: 4px; border: 1px solid #ddd; }
问题排查与修正说明
- 缺失地图容器:原代码中
initMap函数尝试初始化id="map"的元素,但HTML中没有该容器,导致地图初始化失败,进而影响DirectionsService调用。已在表单中添加地图容器。 - 单位转换错误:原代码以公里计算,现已修改为直接将米转换为英里,并更新显示文本和计价逻辑。
- API密钥与权限:确保替换
YOUR_GOOGLE_MAPS_API_KEY为有效的Google Maps API密钥,且在Google Cloud控制台中启用了Directions API和Places API。 - 错误处理优化:添加了DOM元素存在性检查,避免因元素未加载导致的报错。
内容的提问来源于stack exchange,提问作者Masud Chowdhury
相关产品推荐
相关产品推荐

