Google Directions Api 优化问题

问题描述 投票:0回答:1

我正在使用带有一些航点的路线 API。问题是它没有优化,它符合我的数组的顺序,而不是最有效的顺序。 我不希望我的数组的顺序参与路径的一部分。 例如,api 总是会引导我到数组上的第一个对象,这是不对的,它应该引导我到最有效的。

const destinations = [
        { latitude: 40.962259, longitude: 24.506937,stopover: true }, 
        { latitude: 37.993381, longitude: 23.713517,stopover: true }, 
        { latitude: 40.936184, longitude: 24.401282,stopover: true }, 
        // Add more destinations
      ];
      
      const startingPoint = { latitude: 40.400304, longitude: 23.876982 };
    async function planRoute() {
        
      
        try {
          const response = await client.directions({
            params: {
              origin: `${startingPoint.latitude},${startingPoint.longitude}`,
              destination: `${40.397665},${23.884578}`,
              waypoints: destinations,
              optimizeWaypoints: true,
              key: apikey
            },
          });
      
          if (response) {
            // The optimized route is in response.data.routes[0]
            const route = response.data.routes[0];
            console.log('Optimized route:', route);
          }

我尝试更改数组上对象的顺序,它改变了我的方向路径,这是不对的。

javascript google-directions-api google-directory-api google-roads-api google-routes-api
1个回答
0
投票

您的代码存在多个问题

我不确定你是如何让它工作的,但首先,你的

waypoints
数组不是与 documentation 相关的格式。

航路点被指定为对象文字,其字段如下所示:

location
指定航路点的位置,作为
LatLng
,作为 放置对象或作为将进行地理编码的字符串。
stopover
是一个 布尔值,表示该航路点是路线上的一个停靠点, 这具有将路线分成两条路线的效果。

使用您的格式给我一个错误:

[
  { latitude: 40.962259, longitude: 24.506937,stopover: true }, 
  { latitude: 37.993381, longitude: 23.713517,stopover: true }, 
  { latitude: 40.936184, longitude: 24.401282,stopover: true }, 
]

所以我按照文档修复了它:

[
  { location: {lat: 40.962259, lng: 24.506937},stopover: true }, 
  { location: {lat: 37.993381, lng: 23.713517},stopover: true }, 
  { location: {lat: 40.936184, lng: 24.401282},stopover: true }, 
]

然后,代码就可以工作了。

然后传入

optimizeWaypoints
似乎工作正常并且按预期工作

这里有一个示例片段,您可以使用一些给定的位置作为示例自行验证:

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -24.345, lng: 134.46 }, // Australia.
  });
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer({
    draggable: true,
    map,
    panel: document.getElementById("panel"),
  });

  directionsRenderer.addListener("directions_changed", () => {
    const directions = directionsRenderer.getDirections();

    if (directions) {
      computeTotalDistance(directions);
    }
  });
  displayRoute(
        {lat:40.973614, lng: 24.593084},
    {lat: 40.397665, lng: 23.884578},
    directionsService,
    directionsRenderer,
  );
}

function displayRoute(origin, destination, service, display) {
  service
    .route({
      origin: origin,
      destination: destination,
      // Change this to true and the Total Distance 
      // becomes shorter
      optimizeWaypoints: false,
      waypoints:  [
        { location: {lat: 40.962259, lng: 24.506937},stopover: true }, 
        { location:{lat: 37.993381, lng: 23.713517},stopover: true }, 
        { location:{lat: 40.936184, lng: 24.401282},stopover: true }, 
      ],
      travelMode: google.maps.TravelMode.DRIVING,
      avoidTolls: true,
    })
    .then((result) => {
      display.setDirections(result);
    })
    .catch((e) => {
      alert("Could not display directions due to: " + e);
    });
}

function computeTotalDistance(result) {
  let total = 0;
  const myroute = result.routes[0];

  if (!myroute) {
    return;
  }

  for (let i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }

  total = total / 1000;
  document.getElementById("total").innerHTML = total + " km";
}

window.initMap = initMap;
/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#container {
  height: 100%;
  display: flex;
}

#sidebar {
  flex-basis: 15rem;
  flex-grow: 1;
  padding: 1rem;
  max-width: 30rem;
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
}

#map {
  flex-basis: 0;
  flex-grow: 4;
  height: 100%;
}
<!doctype html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Draggable Directions</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="container">
      <div id="map"></div>
      <div id="sidebar">
        <p>Total Distance: <span id="total"></span></p>
        <div id="panel"></div>
      </div>
    </div>

    <!-- 
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

如果您尝试将

optimizeWaypoints
更改为
true
,您会发现路径的总距离显着缩短。这表明
optimizeWaypoints
正在 按预期工作。切换航点顺序似乎不会影响它。

我希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.