簡體   English   中英

Google Maps API(JS)在航點中使用PlaceId創建路線

[英]Google Maps API (JS) Create a route using PlaceId in waypoints

路由只有在我使用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
    }

只需要將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地圖 - 指導服務文檔

這是JsFiddle

我發布的代碼出現javascript錯誤: Uncaught TypeError: google.maps.Place is not a constructor此行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的任何請求中檢索地點ID,例如TextSearch。 也可以從對Geocoding API的請求中檢索地點ID。 有關更多信息,請參閱地點ID概述

概念證明小提琴

結果地圖的屏幕截圖

代碼段:

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM