2016-04-21 137 views
5

路線只創建一個使用PlaceId一個途徑,如果我用經緯度或字符串PARAMS但我需要通過PlaceId創建它,但它不工作谷歌地圖API(JS)創建航點

例如:

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 
    } 
+0

你試過選中此相關[SO問題](http://stackoverflow.com/questions/33990153 /傳遞到位-ID定位到目的地功能於谷歌 - 地圖-API)?你的錯誤日誌是什麼? – abielita

+0

我試過但沒有結果。 placeId僅適用於原產地和目的地。我沒有找到結果 –

回答

4

只需要通過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 
} 

位置指定路標的位置,作爲一個經緯度,作爲 google.maps.Place對象或作爲可進行地理編碼的字符串。

Google Maps - Direction Services Documentation

Here's the JsFiddle

3

我得到張貼代碼JavaScript錯誤:Uncaught TypeError: google.maps.Place is not a constructor在這條線:

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

你需要指定location你做同樣的方式origindestination placeIds:

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

說明在documentation

Google.maps.Place對象規範

placeId |類型:字符串 地點的地點ID(例如業務或興趣點)。地點ID是Google地圖數據庫中某個地點的唯一標識符。請注意,placeId是識別地點的最準確的方式。如果可能,你應該指定placeId而不是placeQuery。可以從對Places API的任何請求中檢索地點ID,例如TextSearch。地點ID也可以從請求中檢索到Geocoding API。欲瞭解更多信息,請參閱overview of place IDs

proof of concept 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"></script> 
 
<div id="map_canvas"></div>