Adrian.I
Adrian.I

Reputation: 180

Click event to multiple google maps routes

I need to add multiple custom routes to a map and redirect to specific pages when a user clicks on the routes. So far i was able to do that when the user click on the waypoints or custom labels, but not on the route itself. At first i tried to build the routes by drawing a polyline between each coordinate and could attached a click event to to the route, but couldn't draw more than one route on the same map. With the current method of drawing i can draw multiple routes but i can't attach a click event to it. Any help is highly appreciated.

  google.maps.event.addListener(directionsRenderer,'click', function (evt) {
  console.log('ev', evt);
  infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
  infowindow.setPosition(evt.latLng);
  infowindow.open(map);
})

This is the initial try when i attached click event to routes but couldn't draw multiples routes: fiddle

This is the latest try where i can draw multiple routes but without click events: fiddle

code snippet:

function busMaps() {
  var directionsService = new google.maps.DirectionsService;
  // var places = new google.maps.places.PlacesService(map);
  var infowindow = new google.maps.InfoWindow();


  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: 51.846437,
      lng: -1.210338
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    styles: [{
      stylers: [{
        saturation: -100
      }]
    }]


  });

  var myCoords = {
    route1: [
      new google.maps.LatLng(52.068903, -1.260588),
      new google.maps.LatLng(52.027057, -1.149292),
      new google.maps.LatLng(51.996436, -1.162611),
      new google.maps.LatLng(51.997970, -1.209802),
      new google.maps.LatLng(51.994775, -1.251997),
      new google.maps.LatLng(52.017494, -1.309684),
      new google.maps.LatLng(51.981498, -1.321367),
      new google.maps.LatLng(51.954807, -1.318343),
      new google.maps.LatLng(51.924264, -1.324991),
      new google.maps.LatLng(51.854053, -1.317165),
      new google.maps.LatLng(51.816201, -1.279594)

    ],
    route2: [
      new google.maps.LatLng(51.904426, -1.059206),
      new google.maps.LatLng(51.896698, -1.150888),
      new google.maps.LatLng(51.872638, -1.185954),
      new google.maps.LatLng(51.846437, -1.210338),
      new google.maps.LatLng(51.824472, -1.239081),
      new google.maps.LatLng(51.796790, -1.182005),
      new google.maps.LatLng(51.793961, -1.175405),
      new google.maps.LatLng(51.757714, -1.221619),
      new google.maps.LatLng(51.760187, -1.224629),
      new google.maps.LatLng(51.748485, -1.245116),
      new google.maps.LatLng(51.767480, -1.259988),
      new google.maps.LatLng(51.769385, -1.262244),
      new google.maps.LatLng(51.773602, -1.259178),
      new google.maps.LatLng(51.769385, -1.262244)
    ],
    route3: [
      new google.maps.LatLng(51.770860, -0.942120),
      new google.maps.LatLng(51.757360, -0.975366),
      new google.maps.LatLng(51.772137, -0.995936),
      new google.maps.LatLng(51.779836, -1.011279),
      new google.maps.LatLng(51.771619, -1.068480),
      new google.maps.LatLng(51.747970, -1.129057),
      new google.maps.LatLng(51.761746, -1.181807),
      new google.maps.LatLng(51.757714, -1.221619),
      new google.maps.LatLng(51.760187, -1.224629),
      new google.maps.LatLng(51.748485, -1.245116),
      new google.maps.LatLng(51.767480, -1.259988),
      new google.maps.LatLng(51.769385, -1.262244),
      new google.maps.LatLng(51.773602, -1.259178),
      new google.maps.LatLng(51.769363, -1.262420),
    ],
    route4: [
      new google.maps.LatLng(51.424203, -0.976910),
      new google.maps.LatLng(51.424088, -0.930640),
      new google.maps.LatLng(51.453720, -0.905135),
      new google.maps.LatLng(51.537599, -0.903588),
      new google.maps.LatLng(51.605565, -0.960766),
      new google.maps.LatLng(51.576115, -0.989035),
      new google.maps.LatLng(51.560421, -0.951550),
      new google.maps.LatLng(51.676793, -0.964094),
      new google.maps.LatLng(51.757714, -1.221619),
      new google.maps.LatLng(51.760187, -1.224629),
      new google.maps.LatLng(51.767480, -1.259988),
      new google.maps.LatLng(51.769385, -1.262244),
      new google.maps.LatLng(51.773602, -1.259178),
      new google.maps.LatLng(51.769363, -1.262420),
      new google.maps.LatLng(51.748485, -1.245116)
    ]
  };

  var routesOptions = {
    route1: {
      color: '#70cc23'
    },
    route2: {
      color: '#41444b'
    },
    route3: {
      color: '#016a31'
    },
    route4: {
      color: '#ffd900'
    }
  };


  function renderDirections(result, color) {
    var directionsRenderer = new google.maps.DirectionsRenderer({
      polylineOptions: {
        strokeColor: color,
        strokeWeight: 4,
        clickable: true,
        icons: [{
          icon: ' '
        }]
      },
      suppressMarkers: true,
      infoWindow: infowindow
    });

    directionsRenderer.setMap(map);
    directionsRenderer.setDirections(result);

    google.maps.event.addListener(directionsRenderer, 'click', function(evt) {
      console.log('ev', evt);
      infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
      infowindow.setPosition(evt.latLng);
      infowindow.open(map);
    })
  }

  function drawMarkers(position, color, course) {

    var marker = new google.maps.Marker({
      position: position,
      clickable: true,
      title: 'Click to open ' + course,
      label: {
        text: course,
        fontSize: "0"
      },
      icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 5,
        fillColor: color,
        fillOpacity: 1,
        strokeWeight: 0,
        image: ''
      },
      map: map
    });

    google.maps.event.addListener(marker, 'click', function(evt) {
      // console.log('ev', evt);
      // infowindow.setContent("you clicked on the route<br>" + evt.latLng.toUrlValue(6));
      // infowindow.setPosition(evt.latLng);
      // infowindow.open(map);

      // infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
      //   'Place ID: ' + place.place_id + '<br>' +
      //   place.formatted_address + '</div>');
      //   infowindow.open(map, this);
    })

    redirectTo(marker, marker.label.text);
  }


  function buildPath(origin, destination, wayPoints, color, route) {

    directionsService.route({
        origin: origin,
        destination: destination,
        waypoints: wayPoints,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      },
      function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          renderDirections(result, color);
        }
      });

    var labelPosition = setLabelPosition(route);

    console.log(labelPosition, 'labelPosition');

    /*  var marker1 = new MarkerWithLabel({
        position: origin,
        title: 'Click to open '+ route,
        map: map,
        labelContent: route,
        labelAnchor: new google.maps.Point(0,0),
        labelClass: "labels",
        labelStyle: {
          opacity: 1,
          background: color,
          'padding': ' 5px 12px',
          'font-size': '16px',
          'font-weight':'300',
          'text-transform':' capitalize',
          'color': '#fff',
          'border-radius': '4px',

        },
        icon: " "
      });

    redirectTo(marker1,marker1.labelContent );*/
  }

  function redirectTo(element, identifier) {

    google.maps.event.addListener(element, 'click', function(evt) {


      switch (identifier) {
        case 'route1':
          alert('click route 1');
          break;
        case 'route2':
          alert('click route 2');
          break;
        case 'route3':
          alert('click route 3');
          break;
        case 'route4':
          alert('click route 4');
          break;
      }
    })
  };

  function setLabelPosition(course) {
    switch (course) {
      case 'route1':
        return 'labelAnchor: new google.maps.Point(90,20))';
        break;
      case 'route2':
        return '0, 0';
        break;
      case 'route3':
        return '0, 0';
        break;
    }
  }


  /* (function() {
      var infoMarker = new MarkerWithLabel({
        position: {lat: 51.846437, lng: -1.210338},
        map: map,
        labelContent: 'Select a route to view pick-up & drop-off times',
        labelAnchor: new google.maps.Point(0, 0),
        labelClass: "infoMarker", // the CSS class for the label
        labelStyle: {
          'opacity': '1',
          'background': '#002f63',
          'padding': ' 20px 15px',
          'font-size': '16px',
          'font-weight':'400',
          'width': '200px',
          'text-transform':' capitalize',
          'color': '#fff',
          'border-radius': '6px',
          'text-align': 'center',
          'z-index':'1000'
        },
        icon: " "
      });
    
      google.maps.event.addListener(infoMarker,'click', function (evt) {
        $('.infoMarker').css('display','none');
      })
    })(); */

  Object.keys(myCoords).forEach(function(key) {
    var curentOrigin = myCoords[key][0],
      curentDestination = myCoords[key][myCoords[key].length - 1],
      wayPoints = [],
      color = routesOptions[key].color;

    // for (var j = 0; j < myCoords[key].length  ; j++) {
    //   drawMarkers(myCoords[key][j],color);
    // }

    for (var j = 1; j < myCoords[key].length - 1; j++) {
      wayPoints.push({
        location: myCoords[key][j],
        stopover: true
      });

      if (j === myCoords[key].length - 2) {
        console.log(curentOrigin)
        buildPath(curentOrigin, curentDestination, wayPoints, color, key);
      }
    }

    for (var j = 0; j < myCoords[key].length; j++) {
      drawMarkers(myCoords[key][j], color, key);
    }
  });

  var center;

  function calculateCenter() {
    center = map.getCenter();
  }


  google.maps.event.addListenerOnce(map, 'idle', function() {
    $('.infoMarker').append('<span class="close-btn"></span><div class="routes-icon"></div>');
    map.setZoom(9);
    calculateCenter();

    if ($('body').hasClass('routes')) {
      $('.media-holder .main-loading-overlay').fadeOut();
    }
  });



  google.maps.event.addDomListener(window, 'resize', function() {
    console.log('center');
    setTimeout(function() {
      map.setCenter(center);
    }, 100);

  });

  google.maps.event.addDomListener(window, 'scroll', function() {
    console.log('center');
    setTimeout(function() {
      map.setCenter(center);
    }, 100);

  });

}
google.maps.event.addDomListener(window, 'load', function() {
  busMaps();
});
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='map'></div>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDVBU8xYg4ulXg3HkO7hMjEPKTLVpsUgh0"></script>

Upvotes: 1

Views: 1008

Answers (1)

geocodezip
geocodezip

Reputation: 161334

Using the code from Google Maps click event on route, with a modification to allow it to create multiple routes rather than update a single route (make the declaration of polylines local to renderDirectionsPolylines, and add the color and course arguments):

function renderDirectionsPolylines(response, color, course) {
  var polylines = [];
  polylineOptions.strokeColor = color;
  for (var i = 0; i < polylines.length; i++) {
    polylines[i].setMap(null);
  }
  var legs = response.routes[0].legs;
  for (i = 0; i < legs.length; i++) {
    var steps = legs[i].steps;
    for (j = 0; j < steps.length; j++) {
      var nextSegment = steps[j].path;
      var stepPolyline = new google.maps.Polyline(polylineOptions);
      for (k = 0; k < nextSegment.length; k++) {
        stepPolyline.getPath().push(nextSegment[k]);
      }
      stepPolyline.setMap(map);
      polylines.push(stepPolyline);
      google.maps.event.addListener(stepPolyline, 'click', function(evt) {
        infowindow.setContent("you clicked on "+course+"<br>" + evt.latLng.toUrlValue(6));
        infowindow.setPosition(evt.latLng);
        infowindow.open(map);
      });
    }
  }
}

proof of concept fiddle

code snippet:

function busMaps() {
  var directionsService = new google.maps.DirectionsService;
  // var places = new google.maps.places.PlacesService(map);
  var infowindow = new google.maps.InfoWindow();

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: 51.846437,
      lng: -1.210338
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    styles: [{
      stylers: [{
        saturation: -100
      }]
    }]
  });

  var myCoords = {
    route1: [
      new google.maps.LatLng(52.068903, -1.260588),
      new google.maps.LatLng(52.027057, -1.149292),
      new google.maps.LatLng(51.996436, -1.162611),
      new google.maps.LatLng(51.997970, -1.209802),
      new google.maps.LatLng(51.994775, -1.251997),
      new google.maps.LatLng(52.017494, -1.309684),
      new google.maps.LatLng(51.981498, -1.321367),
      new google.maps.LatLng(51.954807, -1.318343),
      new google.maps.LatLng(51.924264, -1.324991),
      new google.maps.LatLng(51.854053, -1.317165),
      new google.maps.LatLng(51.816201, -1.279594)

    ],
    route2: [
      new google.maps.LatLng(51.904426, -1.059206),
      new google.maps.LatLng(51.896698, -1.150888),
      new google.maps.LatLng(51.872638, -1.185954),
      new google.maps.LatLng(51.846437, -1.210338),
      new google.maps.LatLng(51.824472, -1.239081),
      new google.maps.LatLng(51.796790, -1.182005),
      new google.maps.LatLng(51.793961, -1.175405),
      new google.maps.LatLng(51.757714, -1.221619),
      new google.maps.LatLng(51.760187, -1.224629),
      new google.maps.LatLng(51.748485, -1.245116),
      new google.maps.LatLng(51.767480, -1.259988),
      new google.maps.LatLng(51.769385, -1.262244),
      new google.maps.LatLng(51.773602, -1.259178),
      new google.maps.LatLng(51.769385, -1.262244)
    ],
    route3: [
      new google.maps.LatLng(51.770860, -0.942120),
      new google.maps.LatLng(51.757360, -0.975366),
      new google.maps.LatLng(51.772137, -0.995936),
      new google.maps.LatLng(51.779836, -1.011279),
      new google.maps.LatLng(51.771619, -1.068480),
      new google.maps.LatLng(51.747970, -1.129057),
      new google.maps.LatLng(51.761746, -1.181807),
      new google.maps.LatLng(51.757714, -1.221619),
      new google.maps.LatLng(51.760187, -1.224629),
      new google.maps.LatLng(51.748485, -1.245116),
      new google.maps.LatLng(51.767480, -1.259988),
      new google.maps.LatLng(51.769385, -1.262244),
      new google.maps.LatLng(51.773602, -1.259178),
      new google.maps.LatLng(51.769363, -1.262420),
    ],
    route4: [
      new google.maps.LatLng(51.424203, -0.976910),
      new google.maps.LatLng(51.424088, -0.930640),
      new google.maps.LatLng(51.453720, -0.905135),
      new google.maps.LatLng(51.537599, -0.903588),
      new google.maps.LatLng(51.605565, -0.960766),
      new google.maps.LatLng(51.576115, -0.989035),
      new google.maps.LatLng(51.560421, -0.951550),
      new google.maps.LatLng(51.676793, -0.964094),
      new google.maps.LatLng(51.757714, -1.221619),
      new google.maps.LatLng(51.760187, -1.224629),
      new google.maps.LatLng(51.767480, -1.259988),
      new google.maps.LatLng(51.769385, -1.262244),
      new google.maps.LatLng(51.773602, -1.259178),
      new google.maps.LatLng(51.769363, -1.262420),
      new google.maps.LatLng(51.748485, -1.245116)
    ]
  };

  var routesOptions = {
    route1: {
      color: '#70cc23'
    },
    route2: {
      color: '#41444b'
    },
    route3: {
      color: '#016a31'
    },
    route4: {
      color: '#ffd900'
    }
  };

  var renderer = new google.maps.DirectionsRenderer({
    suppressPolylines: true,
    suppressMarkers: true,
    infoWindow: infowindow,
    polylineOptions: {
      strokeColor: '#C83939',
      strokeOpacity: 0,
      strokeWeight: 1,
      icons: [{
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          fillColor: '#C83939',
          scale: 3,
          strokeOpacity: 1
        },
        offset: '0',
        repeat: '15px'
      }]
    }

  });

  function renderDirections(result, color, course) {
    renderer.setDirections(result);
    renderer.setMap(map);
    renderDirectionsPolylines(result, color, course);
    console.log(renderer.getDirections());
  }
  var polylineOptions = {
    strokeColor: '#C83939',
    strokeOpacity: 1,
    strokeWeight: 4
  };

  function renderDirectionsPolylines(response, color, course) {
    var polylines = [];
    polylineOptions.strokeColor = color;
    for (var i = 0; i < polylines.length; i++) {
      polylines[i].setMap(null);
    }
    var legs = response.routes[0].legs;
    for (i = 0; i < legs.length; i++) {
      var steps = legs[i].steps;
      for (j = 0; j < steps.length; j++) {
        var nextSegment = steps[j].path;
        var stepPolyline = new google.maps.Polyline(polylineOptions);
        for (k = 0; k < nextSegment.length; k++) {
          stepPolyline.getPath().push(nextSegment[k]);
        }
        stepPolyline.setMap(map);
        polylines.push(stepPolyline);
        google.maps.event.addListener(stepPolyline, 'click', function(evt) {
          infowindow.setContent("you clicked on " + course + "<br>" + evt.latLng.toUrlValue(6));
          infowindow.setPosition(evt.latLng);
          infowindow.open(map);
        })
      }
    }
  }

  function drawMarkers(position, color, course) {

    var marker = new google.maps.Marker({
      position: position,
      clickable: true,
      title: 'Click to open ' + course,
      label: {
        text: course,
        fontSize: "0px"
      },
      icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 5,
        fillColor: color,
        fillOpacity: 1,
        strokeWeight: 0,
        image: ''
      },
      map: map
    });

    redirectTo(marker, marker.label.text);
  }

  function buildPath(origin, destination, wayPoints, color, route) {
    directionsService.route({
        origin: origin,
        destination: destination,
        waypoints: wayPoints,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
      },
      function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          renderDirections(result, color, route);
        }
      });
    var labelPosition = setLabelPosition(route);
    console.log(labelPosition, 'labelPosition');
  }

  function redirectTo(element, identifier) {
    google.maps.event.addListener(element, 'click', function(evt) {
      switch (identifier) {
        case 'route1':
          alert('click route 1');
          break;
        case 'route2':
          alert('click route 2');
          break;
        case 'route3':
          alert('click route 3');
          break;
        case 'route4':
          alert('click route 4');
          break;
      }
    })
  };

  function setLabelPosition(course) {
    switch (course) {
      case 'route1':
        return 'labelAnchor: new google.maps.Point(90,20))';
        break;
      case 'route2':
        return '0, 0';
        break;
      case 'route3':
        return '0, 0';
        break;
    }
  }

  Object.keys(myCoords).forEach(function(key) {
    var curentOrigin = myCoords[key][0],
      curentDestination = myCoords[key][myCoords[key].length - 1],
      wayPoints = [],
      color = routesOptions[key].color;
    for (var j = 1; j < myCoords[key].length - 1; j++) {
      wayPoints.push({
        location: myCoords[key][j],
        stopover: true
      });
      if (j === myCoords[key].length - 2) {
        console.log(curentOrigin)
        buildPath(curentOrigin, curentDestination, wayPoints, color, key);
      }
    }
    for (var j = 0; j < myCoords[key].length; j++) {
      drawMarkers(myCoords[key][j], color, key);
    }
  });

  var center;

  function calculateCenter() {
    center = map.getCenter();
  }

  google.maps.event.addListenerOnce(map, 'idle', function() {
    $('.infoMarker').append('<span class="close-btn"></span><div class="routes-icon"></div>');
    map.setZoom(9);
    calculateCenter();
    if ($('body').hasClass('routes')) {
      $('.media-holder .main-loading-overlay').fadeOut();
    }
  });

  google.maps.event.addDomListener(window, 'resize', function() {
    console.log('center');
    setTimeout(function() {
      map.setCenter(center);
    }, 100);
  });

  google.maps.event.addDomListener(window, 'scroll', function() {
    console.log('center');
    setTimeout(function() {
      map.setCenter(center);
    }, 100);
  });
}
google.maps.event.addDomListener(window, 'load', function() {
  busMaps();
});
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='map'></div>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDVBU8xYg4ulXg3HkO7hMjEPKTLVpsUgh0"></script>

Upvotes: 1

Related Questions