if (directionsRenderer != null) {directionsRenderer.setMap(null);directionsRenderer = null;}
if (waypts.length <= 23) {directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});var directionsService = new google.maps.DirectionsService;directionsRenderer.setMap(map);calculateAndDisplayRoute(directionsService, directionsRenderer, Startlong, Startlat, Endlong, Endlat, waypts);//AnimateFinalRoute(pathCoords4Animation);Startlong = Endlong;Startlat = Endlat;}else {// alert(waypts.length);var splitroute = Math.floor(waypts.length / 20);//quotient//alert(splitroute);var splitrouteReminder = (waypts.length % 20);// alert(splitrouteReminder);var m = 0;var CntWaypnt = 0;for (CntWaypnt = 0; CntWaypnt < splitroute; CntWaypnt++)//Quotient times{var SplittedWaypts1to20s = waypts.slice(m, m + 20);var Startlats = waypts[m].location.lat;var Endlats = waypts[m + 20].location.lat;var Startlongs = waypts[m].location.lng;var Endlongs = waypts[m + 20].location.lng;directionsRenderer = new google.maps.DirectionsRenderer({suppressMarkers: true});var directionsService = new google.maps.DirectionsService;directionsRenderer.setMap(map);calculateAndDisplayRoute(directionsService, directionsRenderer, Startlongs, Startlats, Endlongs, Endlats, SplittedWaypts1to20s);
function calculateAndDisplayRoute(directionsService, directionsRenderer, startLonRoute, StartLatRoute, EndLonRoute, EndLatRoute, waypts) {// Instantiate an info window to hold step text.var stepDisplay = new google.maps.InfoWindow;directionsService.route({origin: { lat: StartLatRoute, lng: startLonRoute }, // Haight.destination: { lat: EndLatRoute, lng: EndLonRoute }, // Ocean Beach.waypoints: waypts,optimizeWaypoints: false,travelMode: 'DRIVING'}, function (response, status) {if (status == 'OK') {directionsRenderer.setDirections(response);//////////////////////////////////var steps = [];polyline = new google.maps.Polyline({path: [],strokeColor: '#FF0000',strokeWeight: 3});poly2 = new google.maps.Polyline({path: [],strokeColor: '#FF0000',strokeWeight: 3});//Animationvar bounds = new google.maps.LatLngBounds();var route = response.routes[0];startLocation = new Object();endLocation = new Object();// For each route, display summary information.var path = response.routes[0].overview_path;var legs = response.routes[0].legs;for (i = 0; i < legs.length; i++) {if (i === 0) {startLocation.latlng = legs[i].start_location;startLocation.address = legs[i].start_address;// marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green");}endLocation.latlng = legs[i].end_location;endLocation.address = legs[i].end_address;var steps = legs[i].steps;for (j = 0; j < steps.length; j++) {var nextSegment = steps[j].path;for (k = 0; k < nextSegment.length; k++) {polyline.getPath().push(nextSegment[k]);bounds.extend(nextSegment[k]);}}}polyline.setMap(map);map.fitBounds(bounds);map.setZoom(18);startAnimation();} else {window.alert('Directions request failed due to ' + status);}});}