使用PlaceId在路标中创建路线的Google地图API(JS)

7

只有使用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
    }
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对象或将被地理编码的字符串。

Google Maps - 方向服务文档

这里是JsFiddle


4

我在使用发布的代码时遇到了一个javascript错误:Uncaught TypeError: google.maps.Place is not a constructor,出错行为:

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

您需要像使用origindestination placeIds一样指定location:

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

文档中的说明:

Google.maps.Place 对象规范

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

验证概念的fiddle

生成地图的截图

代码片段:

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接