Google 地图 API - 检索 2 个坐标之间的道路距离

Google Maps API - Retrieve the road distance between 2 coordinates

希望能在这里找到已经使用此方法的人,并能给我一个如何完成它的示例。

预期结果 - 在一个简单的 HTML 页面中,我想要使用 Google 地图 API 自动完成的 2 个输入字段(位置 API?) 一个输入是起点,另一个输入是终点,它会给我这两个地方的坐标,用这两个坐标我想计算这两个地方之间的道路距离(以公里为单位)并显示屏幕上的结果。

我做了一些研究,我在这里想出了这个代码,用于自动完成输入的地方名称: example of autocomplete input

   google.maps.event.addDomListener(window,'load',initialize);
function initialize(){
    var autocomplete =new google.maps.places.Autocomplete(document.getElementById('txtautocomplete'));
    google.maps.events.addListener(autocomplete, 'plac_changed', function (){
        var places= autocomplete.getplace();
        var location= "<b>Location:</b>"+places.formatted_address+"<br/>";
        location += "<b>Latitude:</b>"+places.geometry.location.lat+"<br/>";
        location += "<b>Longitude:</b>"+places.geometry.location.lng    
    });
}

为了计算两点之间的道路距离,我在某处关于方向 API 的文档中看到了这一点...我保留了代码:

var startcoords=new google.maps.LatLng(latitude,longitude);
var fromcoords=new google.maps.LatLng(latitude,longitude);


let directionsService = new google.maps.DirectionsService();
  let directionsRenderer = new google.maps.DirectionsRenderer();
  directionsRenderer.setMap(map); // Existing map object displays directions
  // Create route from existing points used for markers
  const route = {
      origin: startcoords,
      destination: fromcoords,
      travelMode: google.maps.TravelMode.DRIVING
  }

  directionsService.route(route,
    function(response, status) { // anonymous function to capture directions
      if (status !== 'OK') {
        window.alert('Directions request failed due to ' + status);
        return;
      } else {
        directionsRenderer.setDirections(response); // Add route to the map
        var directionsData = response.routes[0].legs[0]; // Get data about the mapped route
        if (!directionsData) {
          window.alert('Directions request failed');
          return;
        }
        else {
          document.getElementById('msg').innerHTML += " Driving distance is " + directionsData.distance.text + " (" + directionsData.duration.text + ").";
        }
      }
    });

很抱歉,我对 javascript 很陌生,我已经被困在这里几天了..

首先,不建议在 Directions API 请求中使用 latlng 坐标,因为它可能会影响起点和目的地的定位精度。因此,我建议改用 formatted_address。

由于您想将 Places API 与 2 个输入字段(开始位置输入字段和结束位置输入字段)一起使用,因此您需要创建 Places API 的两个实例。例如:

var startAutocomplete = new google.maps.places.Autocomplete(startInput);
var endAutocomplete = new google.maps.places.Autocomplete(endInput);

您需要从 getPlace() 方法中获取值。在这种情况下,我将 formatted_address 值存储在 startValueendValue 变量中,稍后您将传递给路线服务。开始和结束位置的 formatted_address 值足以分别用作 origindestination

 var startValue, endValue; 

 startAutocomplete.addListener("place_changed", function() {
     startValue = startAutocomplete.getPlace().formatted_address;
 });

 endAutocomplete.addListener("place_changed", function() {
     endValue = endAutocomplete.getPlace().formatted_address;
 });

对于 DirectionsService,您可以像这样使用从 getPlace() 方法获得的值:

directionsService.route({
   origin: startValue,
   destination: endValue,
   travelMode: "DRIVING"
}

您可以查看我制作的示例 here on codesandbox.io 以更好地了解如何在 JavaScript 上执行此操作。作为奖励,我还添加了 alternativeRoutes 功能,它将显示最快和最短路线。

注意:您需要在示例中使用自己的 API 键才能工作。