如何获得带有目的地地址的路线(Google 地图 API)

How to have a direction with a destination address (Google maps API)

我想用 Google 地图 API 做一个方向,但它没有地址。我尝试像那样使用地理编码服务,但它不知道 'route'(Direction Services)。

我的方法:

      var geocoder = new google.maps.Geocoder();
           geocoder.geocode({'address': this.nomBar}, function(results, status) {
             this.directionsService.route({
               origin: this.currentLocation,
               destination: results[0].geometry.location,
               travelMode: 'DRIVING'
             }, (response, status) => {
               if (status === 'OK') {
                 that.directionsDisplay.setDirections(response);
               } else {
                 window.alert('Directions request failed due to ' + status);
               }
             });
           });

您不需要使用地理编码器来获取起点和终点的路线。 Google 的 documentation 状态:

origin (required) specifies the start location from which to calculate directions. This value may be specified as a String (for example, "Chicago, IL"), as a LatLng value or as a google.maps.Place object. If you use a google.maps.Place object, you can specify a place ID, a query string or a LatLng location.

destination (required) specifies the end location to which to calculate directions. The options are the same as for the origin field described above.

example 使用地址:

directionsService.route({
  origin: start, // e.g. "chicago, il"
  destination: end, // e.g. "st louis, mo"
  travelMode: 'DRIVING'
}, function(response, status) {
  if (status === 'OK') {
    directionsRenderer.setDirections(response);
  } else {
    window.alert('Directions request failed due to ' + status);
  }
});

而另一个 example 使用坐标:

directionsService.route({
  origin: {lat: 37.77, lng: -122.447},
  destination: {lat: 37.768, lng: -122.511},
  travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
  if (status == 'OK') {
    directionsRenderer.setDirections(response);
  } else {
    window.alert('Directions request failed due to ' + status);
  }
});

希望对您有所帮助!