Home > Mobile >  How to make the polyline change with the draggable route
How to make the polyline change with the draggable route

Time:01-03

I am trying to create a polyline from the route. The route is draggable and it has waypoints. I am using the directions_changed event listener to draw the polyline so that whenever the route changes the polyline also changes. I am able to achieve all of this except then when I drag the route I get the new polyline but I also have the older polyline drawn on the route. Whenever the route is dragged I don't want the older polyline to appear along with the new polyline. enter image description here How can I achieve this?

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);
        var polyline = new google.maps.Polyline(
            {
              path:google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
              map : map
            }
          )
          if(polyline)
          {
            console.log(polyline)
            polyline.setMap(map)
          }
      }
    });
    displayRoute(
      "Perth, WA",
      "Sydney, NSW",
      directionsService,
      directionsRenderer
    );
  }
  
  function displayRoute(origin, destination, service, display) {
    service
      .route({
        origin: origin,
        destination: destination,
        waypoints: [
          { location: "Adelaide, SA" },
          { location: "Broken Hill, NSW" },
        ],
        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;

CodePudding user response:

If you want to hide the old polyline, keep a reference to it (outside the scope of the directions_changed listener) and remove it from the map with polyline.setMap(null); before creating the new polyline:

  if (polyline) {
    // if polyline already exists, remove it from the map.
    polyline.setMap(null)
  }
  polyline = new google.maps.Polyline({
    path: google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
    map: map
  })

screenshot of resulting map after dragging route

code snippet:

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"),
  });
  let polyline;
  directionsRenderer.addListener("directions_changed", () => {
    const directions = directionsRenderer.getDirections();

    if (directions) {
      computeTotalDistance(directions);
      if (polyline) {
        // if polyline already exists, remove it from the map.
        polyline.setMap(null)
      }
      polyline = new google.maps.Polyline({
        path: google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
        map: map
      })
      if (polyline) {
        console.log(polyline)
        polyline.setMap(map)
      }
    }
  });
  displayRoute(
    "Perth, WA",
    "Sydney, NSW",
    directionsService,
    directionsRenderer
  );
}

function displayRoute(origin, destination, service, display) {
  service
    .route({
      origin: origin,
      destination: destination,
      waypoints: [{
          location: "Adelaide, SA"
        },
        {
          location: "Broken Hill, NSW"
        },
      ],
      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;
/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */

#map {
  height: 90%;
}


/* 
 * Optional: Makes the sample page fill the window. 
 */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: "Roboto", "sans-serif";
  line-height: 30px;
  padding-left: 10px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Directions Service</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="total"></div>
  <div id="map"></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
     with https://www.npmjs.com/package/@googlemaps/js-api-loader.
    -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly" defer></script>
</body>

</html>

  • Related