varimax
varimax

Reputation: 121

Display multiple routes between two points on Google Maps

I want to display multiple routes between two locations on google maps. result contains 3 DirectionsRoutes. directionsRenderer1.setDirections(result) displays the first route. console prints routeindex1 = 0.

At line 15, console prints routeindex2 = 1. However, at line 16, directionsRenderer2.setDirections(result) displays the identical route on top of the first route. At Line 17, console prints routeindex2 = 0. How do I display the other route?

 function renderDirections(result,map) {
   directionsRenderer1 = new google.maps.DirectionsRenderer({
      routeIndex: 0,
      polylineOptions: {strokeColor: "green"}
    });
   directionsRenderer1.setMap(map);
   directionsRenderer1.setDirections(result);
   console.log("routeindex1 = ",directionsRenderer1.getRouteIndex());

   directionsRenderer2 = new google.maps.DirectionsRenderer({
      routeIndex: 1,
      polylineOptions: {strokeColor: "blue"}
    });
   directionsRenderer2.setMap(map);
   console.log("routeindex2 = ",directionsRenderer2.getRouteIndex()); //line 15
   directionsRenderer2.setDirections(result);  //line 16 
   console.log("routeindex2 = ",directionsRenderer2.getRouteIndex()); //line 17
 }

Upvotes: 0

Views: 2849

Answers (2)

geocodezip
geocodezip

Reputation: 161334

The DirectionsRenderer renders route 0 by default. Seem to do that regardless of an initially set value of the routeIndex. If you set the route index with the directions, it works.

var directionsRenderer1 = new google.maps.DirectionsRenderer({
  directions: result,
  routeIndex: 0,
  map: map,
  polylineOptions: {
    strokeColor: "green"
  }
});

var directionsRenderer2 = new google.maps.DirectionsRenderer({
  directions: result,
  routeIndex: 1,
  map: map,
  polylineOptions: {
    strokeColor: "blue"
  }
});

proof of concept fiddle

code snippet:

function renderDirections(result, map) {
  var directionsRenderer1 = new google.maps.DirectionsRenderer({
    directions: result,
    routeIndex: 0,
    map: map,
    polylineOptions: {
      strokeColor: "green"
    }
  });
  console.log("routeindex1 = ", directionsRenderer1.getRouteIndex());

  var directionsRenderer2 = new google.maps.DirectionsRenderer({
    directions: result,
    routeIndex: 1,
    map: map,
    polylineOptions: {
      strokeColor: "blue"
    }
  });
  console.log("routeindex2 = ", directionsRenderer2.getRouteIndex()); //line 17
}

function calculateAndDisplayRoute(origin, destination, directionsService, directionsDisplay, map) {
  directionsService.route({
    origin: origin,
    destination: destination,
    travelMode: google.maps.TravelMode.DRIVING,
    provideRouteAlternatives: true
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      renderDirections(response, map);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

function initialize() {
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();
  var 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
    });
  directionsDisplay.setMap(map);
  calculateAndDisplayRoute(new google.maps.LatLng(51.61793418642200, -0.13678550737318), new google.maps.LatLng(51.15788846699750, -0.16364536053269), directionsService, directionsDisplay, map);


}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Upvotes: 3

Sagar Sukode
Sagar Sukode

Reputation: 1371

func drawMutliplePath()
{
    let origin = "\(startLocation.coordinate.latitude),\(startLocation.coordinate.longitude)"
    let destination = "\(destinationLocation.coordinate.latitude),\(destinationLocation.coordinate.longitude)"
    print("origin: \(origin)")
    print("destination: \(destination)")
    let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=\(APIKEY)&alternatives=true"
    print("urlString: \(urlString)")
    let url = URL(string: urlString)
    URLSession.shared.dataTask(with: url!, completionHandler: {
        (data, response, error) in
        if(error != nil){
            print("error")
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
                let routes = json["routes"] as! NSArray
                self.mapView.clear()

                OperationQueue.main.addOperation({
                    var i = 1
                    for route in routes
                    {
                        let routeOverviewPolyline:NSDictionary = (route as! NSDictionary).value(forKey: "overview_polyline") as! NSDictionary
                        let points = routeOverviewPolyline.object(forKey: "points")
                        let path = GMSPath.init(fromEncodedPath: points! as! String)
                        let polyline = GMSPolyline.init(path: path)
                        polyline.strokeWidth = 3

                        if i == 1
                        {
                            polyline.strokeColor = UIColor.green
                        }else if i == 2
                        {
                            polyline.strokeColor = UIColor.blue
                        }else
                        {
                            polyline.strokeColor = UIColor.red
                        }

                        i = i+1
                        let bounds = GMSCoordinateBounds(path: path!)
                        self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0))

                        polyline.map = self.mapView

                    }
                    self.marker = GMSMarker(position: self.startLocation.coordinate)
                    self.marker.map = self.mapView
                    self.marker.icon = GMSMarker.markerImage(with: UIColor.green)
                    self.destinationMarker = GMSMarker(position: self.destinationLocation.coordinate)
                    self.destinationMarker.map = self.mapView
                    self.destinationMarker.icon = GMSMarker.markerImage(with: UIColor.red)
                })
            }catch let error as NSError{
                print("error:\(error)")
            }
        }
    }).resume()
}

Upvotes: 0

Related Questions