如何绑定quote-btn并通过Google Maps Directions Service获取起点终点英里数?
问题
我有两个id分别为origin和destination的HTML输入字段,已集成Google Places API实现地址预测功能且运行正常。现在我希望获取起点和终点地址,为表单的quote-btn按钮添加点击监听器,在不显示地图的前提下获取英里数。目前我的代码没有抛出异常,但不知道如何完成quote-btn的绑定。
我的表单如下:
<form method="post" action="#"> <div class="row"> <div class="col-md-12 col-lg-12"> <div class="border-bottom mb-4 w-100 d-sm-flex"> <h3 class="text-secondary pb-3">To Your Destination</h3> </div> </div> <div class="col-md-12 col-lg-12"> <div class="border-bottom mb-4 w-100 d-sm-flex" id="miles"> </div> </div> <div class="col-md-6 col-lg-6"> <div class="form-group"> <label>Enter pickup location</label> <input type="text" id="origin" class="form-control border border-primary" name="origin" autocomplete> </div> </div> <div class="col-md-6 col-lg-6"> <div class="form-group"> <label>Enter dropoff location</label> <input type="text" id="destination" class="form-control border border-primary" name="destination" autocomplete> </div> </div> <div class="col-md-12 col-lg-12"> <div class="form-group"> <label>Select Date and Time</label> <input type="text" class="form-control date-time" name="travel_date_time"> </div> </div> <div class="col-md-4 col-lg-3"> <div class="form-group mt-5"> <button type="button" id="qoute-btn" class="btn btn-primary w-100">Quote Now</button> </div> </div> </div> </form>
我的JavaScript代码如下:
function initMap() { // Initialize the autocomplete objects for origin and destination input fields const options = { componentRestrictions: {country: 'uk'} }; const originAutocomplete = new google.maps.places.Autocomplete(document.getElementById('origin'), options); const destinationAutocomplete = new google.maps.places.Autocomplete(document.getElementById('destination'), options); // Set the fields to return place details when a user selects a suggestion originAutocomplete.setFields(['place_id', 'formatted_address', 'geometry']); destinationAutocomplete.setFields(['place_id', 'formatted_address', 'geometry']); // Initialize the directions service const directionsService = new google.maps.DirectionsService(); // Initialize the directions renderer // const directionsRenderer = new google.maps.DirectionsRenderer(); // Set the directions renderer options // directionsRenderer.setOptions({suppressMarkers: true}); // Add a one-time listener to the "directions_changed" event google.maps.event.addListenerOnce(directionsRenderer, 'directions_changed', function () { // Get the origin and destination values const originValue = document.getElementById('origin').value; const destinationValue = document.getElementById('destination').value; // Check if the origin and destination values are not null if (originValue && destinationValue) { // Create the request object for the DirectionsService const request = { origin: originValue, destination: destinationValue, travelMode: 'DRIVING' }; // Call the DirectionsService to calculate the route directionsService.route(request, function (response, status) { if (status) { // Get the distance in miles from the response object const distanceInMiles = response.routes[0].legs[0].distance.text; console.log(`The distance from ${originValue} to ${destinationValue} is ${distanceInMiles}.`); } else { console.log(`Error: ${status}`); } }); } }); }
解决方案
只需移除不需要的directionsRenderer相关代码,直接给按钮绑定点击事件,在点击时调用Google Directions API计算距离。以下是修改后的完整代码:
function initMap() { // 初始化地址自动补全 const options = { componentRestrictions: {country: 'uk'} }; const originAutocomplete = new google.maps.places.Autocomplete(document.getElementById('origin'), options); const destinationAutocomplete = new google.maps.places.Autocomplete(document.getElementById('destination'), options); // 设置返回的地点字段 originAutocomplete.setFields(['place_id', 'formatted_address', 'geometry']); destinationAutocomplete.setFields(['place_id', 'formatted_address', 'geometry']); // 初始化路线服务 const directionsService = new google.maps.DirectionsService(); // 获取按钮元素(注意按钮ID是qoute-btn,拼写为q开头) const quoteBtn = document.getElementById('qoute-btn'); // 获取显示距离的容器 const milesContainer = document.getElementById('miles'); // 绑定按钮点击事件 quoteBtn.addEventListener('click', function() { const originValue = document.getElementById('origin').value.trim(); const destinationValue = document.getElementById('destination').value.trim(); // 验证输入是否为空 if (!originValue || !destinationValue) { milesContainer.textContent = '请填写起点和终点地址'; return; } // 构造路线请求参数,指定英制单位返回英里 const request = { origin: originValue, destination: destinationValue, travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERIAL }; // 调用路线服务计算距离 directionsService.route(request, function(response, status) { if (status === google.maps.DirectionsStatus.OK) { // 提取距离信息并展示 const distance = response.routes[0].legs[0].distance; milesContainer.textContent = `距离: ${distance.text}`; console.log(`距离: ${distance.text}`); } else { milesContainer.textContent = `获取距离失败: ${status}`; console.error(`路线请求错误: ${status}`); } }); }); }
核心修改说明:
- 删除所有
directionsRenderer相关代码(本来已注释,直接清理即可) - 获取按钮元素,绑定
click事件监听器 - 增加输入校验,避免空地址发起无效请求
- 在请求中指定英制单位,确保返回英里数
- 将计算结果展示到页面的
#miles容器,同时保留控制台日志便于调试 - 处理API请求失败的场景,给出明确的错误提示
内容的提问来源于stack exchange,提问作者Qasim Ali
相关产品推荐
相关产品推荐

