使用 Google Directions API 解決 TSP
在不下載 OR-Tools 的情況下,Google 也提供可解析實際位置的簡單 TSP 方法。如果有 Google Directions API 金鑰,您可以使用 Directions API 解析實際位置中的 TSP。在網址中提供位置,再傳回 JSON 格式的回應。您需要自己的免費 Directions API 金鑰進行開發,或企業金鑰用於商業用途。
舉例來說,您可以利用這個網址尋找南澳大利南州葡萄酒製造地區的簡短導覽,從阿德萊德開始。如果您想要透過瀏覽器試用這項功能,請將網址結尾的 API_KEY 換成您的金鑰。
https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=API_KEY
結果將是詳細的 JSON 回應,內容是關於解決方案的,且包含 Google 地圖路線:
{ "routes" : [ { "bounds" : { "northeast" : { "lat" : -33.8347115, "lng" : 140.8547058 }, "southwest" : { "lat" : -37.3511758, "lng" : 138.4951576 } }, "copyrights" : "Map data ©2014 Google", "legs" : [ { "distance" : { "text" : "139 km", "value" : 139119 }, "duration" : { "text" : "1 hour 51 mins", "value" : 6648 }, "end_address" : "Clare SA 5453, Australia", "end_location" : { "lat" : -33.8333395, "lng" : 138.6117283 }, "start_address" : "Adelaide SA, Australia", "start_location" : { "lat" : -34.9285894, "lng" : 138.5999429 }, "steps" : [ { "distance" : { "text" : "70 m", "value" : 70 }, "duration" : { "text" : "1 min", "value" : 6 }, "end_location" : { "lat" : -34.9285338, "lng" : 138.6007031 }, "html_instructions" : "Head \u003cb\u003eeast\u003c/b\u003e on \u003cb\u003eReconciliation Plaza\u003c/b\u003e toward \u003cb\u003eVictoria Square\u003c/b\u003e", ...