Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display alternative route using google map api

I am using google map and i am bit of stuck at one point. i want to display alternative route for my source and destination point. currently i am using the code which is working perfectly and displaying correct result but the only the problem is that this code displaying only single route for my starting and destination path.

Here is my JSFIDDLE WORKING DEMO

Here is sample code which i am using in jsfiddle demo link:

HTML CODE:

<h1>Calculate your route</h1>
<form id="calculate-route" name="calculate-route" action="#" method="get">
  <label for="from">From:</label>
  <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
  <a id="from-link" href="#">Get my position</a>
  <br />

  <label for="to">To:</label>
  <input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
  <a id="to-link" href="#">Get my position</a>
  <br />

  <input type="submit" />
  <input type="reset" />
</form>  

JS CODE:

<script>
  function calculateRoute(from, to) {
    // Center initialized to Naples, Italy
    var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(40.84, 14.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = {
      origin: from,
      destination: to,
      provideRouteAlternatives: true,
      travelMode: google.maps.DirectionsTravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC
    };
    directionsService.route(
      directionsRequest,
      function(response, status)
      {
        if (status == google.maps.DirectionsStatus.OK)
        {
          new google.maps.DirectionsRenderer({
            map: mapObject,
            directions: response
          });
        }
        else
          $("#error").append("Unable to retrieve your route<br />");
      }
    );
  }

  $(document).ready(function() {
    // If the browser supports the Geolocation API
    if (typeof navigator.geolocation == "undefined") {
      $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }

    $("#from-link, #to-link").click(function(event) {
      event.preventDefault();
      var addressId = this.id.substring(0, this.id.indexOf("-"));

      navigator.geolocation.getCurrentPosition(function(position) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
        },
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK)
            $("#" + addressId).val(results[0].formatted_address);
          else
            $("#error").append("Unable to retrieve your address<br />");
        });
      },
      function(positionError){
        $("#error").append("Error: " + positionError.message + "<br />");
      },
      {
        enableHighAccuracy: true,
        timeout: 10 * 1000 // 10 seconds
      });
    });

    $("#calculate-route").submit(function(event) {
      event.preventDefault();
      calculateRoute($("#from").val(), $("#to").val());
    });
  });
</script>

you can see in the demo when you enter starting point and destination point it will give you single route accordingly but i need to display alternative route as well in the map.

Is there any way we can choose and display a route between the given options according to the 'distance' or the 'duration in traffic'?

Thanks in advance for your help and much appreciated

like image 681
Dhaval Bharadva Avatar asked Sep 24 '13 06:09

Dhaval Bharadva


People also ask

How do I get Google Maps to show alternative routes?

To choose an alternate route, either click on a greyed-out route on the map or click on one of the other routes listed on the left-hand side menu. Note that you can also change routes by clicking on one and dragging it so that the directions will take you via certain roads.

Can you overlay multiple routes on Google Maps?

You can create multiple routes in the backend and display them on your Google Maps. Visitors will be able to show/hide them easily on the frontend. Just enter a start and an end point to get directions.

What is the best Google Maps API alternative?

Radar is the best alternative to the Google Maps API. Radar supports geocoding, search, and distance APIs with high-quality address and place data. Radar is more affordable than the Google Maps API, free up to 100,000 API requests per month and $0.50 per 1,000 requests thereafter.

How do I enable routes preferred API?

If you don't already have the Routes Preferred API enabled for your project, navigate to the APIs & Services Library in Google Cloud Console. You can skip this step if Routes Preferred is already enabled. Then search for Routes Preferred to open the Routes Preferred API. To enable the API, select Enable.


1 Answers

What you need to do is check how many routes are returned by the directionsService.route function call, within the callback function which receives the response object response.routes will be an array, so loop through it and use the loop counter to set the routeIndex for the DirectionsRenderer to use. Of course this resulting output is not at all in my opinion desirable, as very often segments of alternative routes will overlap so it won't always be visually obvious to a user whats going on with the other extra lines. As well as if you actually display the text directions, will need different DOM element for display of each set of directions, and then it's confusing too which set is for what. I would rather advise showing the main (first) route only and having buttons to display alternatives which upon clicking would show only those routes & directions. That said, here is the fix for your question:

directionsService.route(
    directionsRequest,
    function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            for (var i = 0, len = response.routes.length; i < len; i++) {
                new google.maps.DirectionsRenderer({
                    map: mapObject,
                    directions: response,
                    routeIndex: i
                });
            }
        } else {
            $("#error").append("Unable to retrieve your route<br />");
        }
    }
);
like image 164
astupidname Avatar answered Nov 09 '22 08:11

astupidname