1

I have a project that needs to have multi-colors for a route between two points. I have used Google maps API to get the code working. Here is the code I am working on.

HTML part:

<!DOCTYPE html>  
 <html>  
  <head>  
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
<meta charset="utf-8">  
<style type="text/css">  
  html { height: 100% }  
  body { height: 100%; margin: 0; padding: 0 }  
  #map-canvas { height: 100% }  
</style>  
<title>Waypoints in directions</title>  
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>          </head>  
<body>  
  <div id="map-canvas" style="float:left;width:70%;height:100%;"></div>  
  <div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">  
  <div style="margin:20px;border-width:2px;">  
    <div id="panel">  
    <b>Start: </b>  
  <input id="start" type="text" onchange="calcRoute();">  
  <br>  
  <b>End: </b>  
  <input id="end" type="text" onchange="calcRoute();">  
  </div>  
  <br>  
  <b>Waypoints:</b> <br>  
  <p><input type="button" value="waypoint" onclick="waypoint();" width="100px"   height="60px"></p>  
  </div>
  <div id="div"></div>
  <p><input type="button" value="submit" onclick="calcRoute();" width="100px" height="60px"></p>
  </div>  
</body>  
</html>  

JavaScript part:

function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
  strokeColor: "blue"
}
  });   
directionsDisplay1 = new google.maps.DirectionsRenderer({
 suppressMarkers: true,
   polylineOptions: {
     strokeColor: "green"
  }
     });
 directionsDisplay2 = new google.maps.DirectionsRenderer({
  suppressMarkers: true,
    polylineOptions: {
     strokeColor: "orange"
     }
   });
 directionsDisplay3 = new google.maps.DirectionsRenderer({
    suppressMarkers: true,
    polylineOptions: {
      strokeColor: "red"
}
  });

  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
   }
   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
   directionsDisplay.setMap(map);
   directionsDisplay1.setMap(map);
   directionsDisplay2.setMap(map);
   directionsDisplay3.setMap(map);

}
function calcRoute() {
  start = document.getElementById('start').value;
  end = document.getElementById('end').value;


  for (var i = 0; i < counter; i++) {
   checkpts[i] = document.getElementsByClassName('way')[i];
   waypoints.push({
   location:checkpts[i].value,
   stopover:true});
}
  var request = {
  origin: start,
  destination: end,
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
};
  directionsService.route(request, function(response, status,routes) {
   if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
  myRoute = response.routes[0];
  }
  for (var i=0; i<myRoute.legs[0].steps.length; i++) {

      pts[i]=myRoute.legs[0].steps[i].polyline.points;
      points[i]=String(pts[i]);
      waypts[i]=decode(points[i]);
      Points.push(waypts[i]);
  }
for (var i=0; i<myRoute.legs[0].steps.length; i++){
   for (var j=0; j<Points[i].length; j++){
    routepts.push(Points[i][j]);
  }
}

  var s=routepts.length;
  var k=(s/4);
 for(var i=1;i<=4;i++)
 {
      latlng[i-1] = new google.maps.LatLng(routepts[(parseInt(i*k)-1)][0],       routepts[(parseInt(i*k)-1)][1]);

 }
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'latLng': latlng[0]},function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
             address.push(results[1].formatted_address);
           }
          }
      });
   geocoder.geocode({'latLng': latlng[1]},function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
             address.push(results[1].formatted_address);
            }
      }
  });
   geocoder.geocode({'latLng': latlng[2]},function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
          address.push(results[1].formatted_address);
        }
      }
  });
  geocoder.geocode({'latLng': latlng[3]}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
          address.push(results[1].formatted_address);
        }
      }
  });
})
 var request1 = {
  origin: start,
  destination: String(address[1]),
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
  };

directionsService.route(request1, function(response, status,routes) {
   if (status == google.maps.DirectionsStatus.OK) {
     directionsDisplay1.setDirections(response);
    }
   })

 var request2 = {
  origin: String(address[1]),
  destination: String(address[2]),
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
  };

directionsService.route(request2, function(response, status,routes) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay2.setDirections(response);
}
  })

var request3 = {
  origin: String(address[2]),
  destination: end,
  waypoints: waypoints,
  optimizeWaypoints: true,
  travelMode: google.maps.TravelMode.DRIVING
  };

directionsService.route(request3, function(response, status,routes) {
if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay3.setDirections(response);
}
  })


}
function decode(instring) {
  var out=[];
  //instring = instring.replace(/\\\\/g, "\\");
  out = decodeLine(instring);
  return out;
}
function decodeLine(encoded) {
 var len = encoded.length;
 var index = 0;
 var array = [];
 var lat = 0;
 var lng = 0;

  while (index < len) {
   var b;
   var shift = 0;
var result = 0;
do {
  b = encoded.charCodeAt(index++) - 63;
  result |= (b & 0x1f) << shift;
  shift += 5;
} while (b >= 0x20);
var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;

shift = 0;
result = 0;
do {
  b = encoded.charCodeAt(index++) - 63;
  result |= (b & 0x1f) << shift;
  shift += 5;
} while (b >= 0x20);
var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;

array.push([lat * 1e-5, lng * 1e-5]);
  }

  return array;
}

function waypoint(){
  var d=document.getElementById("div");
  d.innerHTML+="<p><input type='text' placeholder='waypoint' class='way'>";
  counter++;

}
 google.maps.event.addDomListener(window, 'load', initialize);

While running the code, I got an error.

  1. On entering a location in start or end input boxes, a route is being plotted between the location entered and an unknown location in Spain.

I am new to Google Maps API.Please suggest something to help me out.
Thanks in advance.

user2809895
  • 331
  • 1
  • 3
  • 8
  • You have lots of undefined variables in the code you posted, it doesn't allow the issue to be reproduced. It looks to me like you will probably have an issue with the asynchronous behavior of the geocoder. Why are you using it? – geocodezip Oct 01 '13 at 12:55
  • I need to find the location for the latlong values obtained from points of direction service response and from there I am using Google Directions to plot 3 different routes with different colors on the existing route – user2809895 Oct 03 '13 at 06:48
  • Have you tried a debugger? – geocodezip Oct 07 '13 at 12:52
  • yeah.I think the problem is with decoding the string to latitudes and longitudes.The code I have used is not decoding correctly. – user2809895 Oct 08 '13 at 12:18
  • second error was due to decoding and it was solved. 1st error still exist.@geocodezip Do u have any suggestions to solve that? – user2809895 Oct 10 '13 at 16:47
  • It doesn't look like you have changed the code posted in your question. Do you have a jsfiddle that shows the problem? Or a link to a live map that does? – geocodezip Oct 10 '13 at 18:22
  • http://jsfiddle.net/qBam8/ this js fiddle show the error. – user2809895 Oct 10 '13 at 19:00
  • @geocodezip can u find the source of this error? – user2809895 Oct 11 '13 at 10:06
  • Yes. the close bracket of the directions request is in the wrong place (way to early). Don't have time right now to explain completely or put up an example. – geocodezip Oct 11 '13 at 13:48
  • can you just tell me where to close? – user2809895 Oct 11 '13 at 13:57
  • Unfortunately, not easily, your code is poorly indented and don't know how to explain it other than after all the processing of the data from the route (it is being processed even if the DirectionsService returns an error and there isn't a route). – geocodezip Oct 11 '13 at 14:06

0 Answers0