Google Maps API(JS)在航点中使用PlaceId创建路线

问题描述 投票:6回答:2

路由只有在我使用LatLng或String参数时才会创建,但我需要通过PlaceId创建它,但它不起作用

例:

directionsService.route({
        origin: {'placeId': 'ChIJc1lGdwfP20YR3lGOMZD-GTM'},
        destination: {'placeId': 'ChIJdTGhqsbP20YR6DZ2QMPnJk0'},
        waypoints: [{stopover: true, location: new google.maps.Place('ChIJRVj1dgPP20YRBWB4A_sUx_Q')}],
        optimizeWaypoints: true,
        travelMode: google.maps.TravelMode.DRIVING
    }
javascript google-maps google-maps-api-3 direction
2个回答
5
投票

只需要传递google.maps.Place对象作为航点位置。例如:

directionsService.route({
    origin: { placeId: "ChIJc1lGdwfP20YR3lGOMZD-GTM" },
    destination: { placeId: "ChIJdTGhqsbP20YR6DZ2QMPnJk0" },
    waypoints: [{ stopover: true, location: { placeId: "ChIJRVj1dgPP20YRBWB4A_sUx_Q" } }],
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
}

location指定航点的位置,LatLng,google.maps.Place对象或将进行地理编码的String。

Google Maps - Direction Services Documentation

Here's the JsFiddle


4
投票

我发布了一个javascript错误,发布的代码:Uncaught TypeError: google.maps.Place is not a constructor在这一行:

waypoints: [{stopover: true, location: new google.maps.Place('ChIJRVj1dgPP20YRBWB4A_sUx_Q')}],

你需要像locationorigin placeIds一样指定destination

waypoints: [{
  stopover: true,
  location: {'placeId':"ChIJRVj1dgPP20YRBWB4A_sUx_Q"}
}],

documentation中的描述:

Google.maps.Place对象规范

placeId |类型:字符串地点的地点ID(例如商家或兴趣点)。地点ID是Google地图数据库中地点的唯一标识符。请注意,placeId是识别地点的最准确方式。如果可能,您应该指定placeId而不是placeQuery。可以从Places API的任何请求中检索地点ID,例如TextSearch。也可以从对Geocoding API的请求中检索地点ID。有关更多信息,请参阅overview of place IDs

proof of concept fiddle

screenshot of resulting map

代码段:

function initialize() {
  var map = new google.maps.Map(document.getElementById("map_canvas"));
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });
  directionsService.route({
    origin: {
      'placeId': 'ChIJc1lGdwfP20YR3lGOMZD-GTM'
    },
    destination: {
      'placeId': 'ChIJdTGhqsbP20YR6DZ2QMPnJk0'
    },
    waypoints: [{
      stopover: true,
      location: {
        'placeId': "ChIJRVj1dgPP20YRBWB4A_sUx_Q"
      }
    }],
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === 'OK') {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
© www.soinside.com 2019 - 2024. All rights reserved.