google-mapsgoogle-maps-api-3driving-directions

calculate the distance of routes of two railway station in google map


I know with the Google API, it is possible to calculate the distances of routes between two points, however most examples I see is the direction service calculate distances on the car/ walking/ bicycle routes.

From the code, it is possible to get the distance between two big cities on railway (code below), but I want to also get the distances of 16 segments, which are small stations between two big cities. How to?

 var directionsService = new google.maps.DirectionsService();
 var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
 directionsDisplay.setMap(map);

 var request = {
       origin: 'Chester', 
       destination: 'Liverpool',
       travelMode: google.maps.TravelMode.TRANSIT,
       unitSystem:google.maps.UnitSystem.METRIC
 };

 directionsService.route(request, function(response, status) {
   if (status == google.maps.DirectionsStatus.OK) {

   ////////////////////////////////////////////////////////////////////////////
     directionsDisplay.setDirections(response);
    var path = response.routes[0].overview_path;
    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 transitMode = steps[j].travel_mode;

        if (transitMode == "TRANSIT") {
                var vehicle = steps[j].transit.line.vehicle.type;
                if (vehicle == "HEAVY_RAIL") {          
                  var nextSegment = steps[j].path;

          console.log('segment   '+nextSegment.length);
          for (k=0;k<nextSegment.length;k++) {
         console.log(nextSegment[k].hb+"     "+nextSegment[k].ib);
             route_polyline.getPath().push(nextSegment[k]);
          }

                  console.log('rail');                       
                }
        }
      }
    }
    route_polyline.setMap(map);
   }
 });

Solution

  • Do you require the shortest distance between stations rather than the distance travelled? If so you require a database of railway stations and to use the Haversine formula to calculate this. I have a Demo which uses this to find railway stations within a radius of a location. This can be modified to suit your requirements