Guodong Rong
Guodong Rong

Reputation: 21

Google map Remove previous route and draw a new route

Currently I have encounter a problem. I used and changed sample API to draw route for two points. Point A is current location. Point B is one of the multiple markers' location. Those markers are created which I call nearby search function.

function showInfoWindow() {
    var marker = this;
    places.getDetails({
            placeId: marker.placeResult.place_id
        },
        function(place, status) {
            if (status !== google.maps.places.PlacesServiceStatus.OK) {
                return;
            }
            infoWindow.open(map, marker);
            buildIWContent(place);
        });
    var clickLat = marker.position.lat();
    var clickLon = marker.position.lng();
    var directionsDisplay = new google.maps.DirectionsRenderer({
        map: map
    });
    var directionsService = new google.maps.DirectionsService();
    showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}

function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
    var pointA = {
        lat: currentLat,
        lng: currentLon
    };
    var pointB = {
        lat: clickLat,
        lng: clickLon
    };


    directionsDisplay.setOptions({
        suppressMarkers: true
    });

    //directionsDisplay.setMap(map);
    //directionsDisplay.setDirections({ routes: [] });
    // Set destination, origin and travel mode.
    var request = {
        destination: pointB,
        origin: pointA,
        travelMode: google.maps.TravelMode.DRIVING
    };
    //directionsDisplay.setMap(null);
    // Pass the directions request to the directions service.  
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            // Display the route on the map.
            //directionsDisplay.set('directions', null);

            //directionsDisplay.setMap(map);
            //directionsDisplay.setDirections({ routes: [] });
            directionsDisplay.setDirections(response);

        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });

}

These codes could draw route for two points already. But the problem is when I click one marker call the showInfoWindow() it will draw one route, and click another one when it will call the showInfoWindow() again it will draw another route remaining the previous one route.I want to clear the previous one route. Tried all the methods online and could not find the reason.

Upvotes: 0

Views: 2627

Answers (1)

geocodezip
geocodezip

Reputation: 161404

If you only want one directions result displayed on the map at the time, only create and use one instance of the DirectionsRenderer, currently you create a new one for every result from the DirectionsService.

proof of concept fiddle

code snippet:

var geocoder;
var map;
var places;
var infoWindow = new google.maps.InfoWindow();
//Jersey City, NJ, USA
var currentLat = 40.7281575;
var currentLon = -74.0776417;
// global reference to the DirectionsRenderer
var directionsDisplay;

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  places = new google.maps.places.PlacesService(map);
  // initialize the global DirectionsRenderer
  directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });
  var marker1 = new google.maps.Marker({ /* New York, NY, USA */
    position: {
      lat: 40.7127837,
      lng: -74.0059413
    },
    placeResult: {
      place_id: "ChIJOwg_06VPwokRYv534QaPC8g"
    },
    map: map
  });
  google.maps.event.addListener(marker1, 'click', showInfoWindow);
  var marker2 = new google.maps.Marker({ /* Newark, NJ, USA */
    position: {
      lat: 40.735657,
      lng: -74.1723667
    },
    placeResult: {
      place_id: "ChIJHQ6aMnBTwokRc-T-3CrcvOE"
    },
    map: map
  });
  google.maps.event.addListener(marker2, 'click', showInfoWindow);
  var bounds = new google.maps.LatLngBounds();
  bounds.extend(marker1.getPosition());
  bounds.extend(marker2.getPosition());
  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);

function showInfoWindow() {
  var marker = this;
  places.getDetails({
      placeId: marker.placeResult.place_id
    },

    function(place, status) {
      if (status !== google.maps.places.PlacesServiceStatus.OK) {
        return;
      }
      infoWindow.open(map, marker);
      buildIWContent(place);
    });
  var clickLat = marker.position.lat();
  var clickLon = marker.position.lng();
  var directionsService = new google.maps.DirectionsService();
  showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}

function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
  var pointA = {
    lat: currentLat,
    lng: currentLon
  };
  var pointB = {
    lat: clickLat,
    lng: clickLon
  };


  directionsDisplay.setOptions({
    suppressMarkers: true
  });

  //directionsDisplay.setMap(map);
  //directionsDisplay.setDirections({ routes: [] });
  // Set destination, origin and travel mode.
  var request = {
    destination: pointB,
    origin: pointA,
    travelMode: google.maps.TravelMode.DRIVING
  };
  //directionsDisplay.setMap(null);
  // Pass the directions request to the directions service.  
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      // Display the route on the map.
      //directionsDisplay.set('directions', null);

      //directionsDisplay.setMap(map);
      //directionsDisplay.setDirections({ routes: [] });
      directionsDisplay.setDirections(response);

    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });

}
html,
body,
#map_canvas {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

Upvotes: 1

Related Questions