Search code examples
ruby-on-railsrubygoogle-mapsgmaps4railsrails-geocoder

How get car route between two coordinates using ruby?


I'm developing rails app with google maps and car routes.

I have a start and finish points for car route - two coordinates. How can I get a full car route (array of coordinates for car through streets)? Can I do it using gmaps4rails and geocoder?

Something like this:

start_point = [41,2423; 45,323452]
end_point   = [42,2423; 42,323452]

full_route = some_method_for_calculate_route( start_point, end_point )

#paint line on map from array of points
paint_line( full_route )

Please help, thanks kindly :)


Solution

  • If you want to do it client side, you have a plunkr here.

    It is highly inspired by the google documentation here.

    Basically its a way to interact with google libraries

      var handler = Gmaps.build('Google');
      handler.buildMap({ internal: {id: 'map'}}, function(){
    
        var start_point = [43.2423, 5.323452];
        var end_point   = [44.2423, 5.323452];
    
        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();
    
        directionsDisplay.setMap(handler.getMap());
        var request = {
          origin:      new google.maps.LatLng(start_point[0], start_point[1]),
          destination: new google.maps.LatLng(end_point[0], end_point[1]),
          travelMode:  google.maps.TravelMode.DRIVING
        };
    
        directionsService.route(request, function(response, status) {
          if (status === google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          }
        });
      });