Akhil Alluri
Akhil Alluri

Reputation: 13

Google Direction API directionsService.route() does not return result

I have tried to utilise the direction api to calculate distance between two places. However, the .route() service does not seem to hold.

$scope.getRes = function(id) {
    $scope.bookingReference = {};
    $http.get('/api/carpooler/'+id)
        .success(function(data) {
            data.travelDate = new moment(data.travelDate).format("MMM Do YYYY");
            data.travelTime = new moment(data.travelTime).format("h:mm:ss a");
            $scope.bookingReference = data;
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

    for(i = 0;i<$scope.bookings.length;i++) {
        dd = calcRoute($scope.bookings[i].Destination,$scope.bookingReference.Destination);
        if( dd < 5000) {// 5 KM
            $scope.bookingResultArray.push($scope.bookings[i]);

        }
    }
    $scope.status2 = true;
};

I am calling the calcRoute to return the distance.

var directionsService = new google.maps.DirectionsService();
function calcRoute(ref1,ref2) {
    var start = String(ref1);
    var end = String(ref2);
    var args = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING
    }
    directionsService.route(args, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var myroute=directionsDisplay.directions.routes[0];
        } else {
            alert("fail");
        }
    });
    var distance= 0;
    for(i = 0; i < myroute.legs.length; i++){
        distance += myroute.legs[i].distance.value;
        //for each 'leg'(route between two waypoints) we get the distance and add it to the total
    }
    return distance;
};

I get the following error :

Error: myroute is not defined
calcRoute@http://localhost:3000/controllers/home.js:73:12
$scope.getRes@http://localhost:3000/controllers/home.js:91:20
Parser.prototype.functionCall/<@http://localhost:3000/vendor/angular.js:11026:15
ngEventHandler/</<@http://localhost:3000/vendor/angular.js:20468:17
$RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:3000/vendor/angular.js:12874:16
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:3000/vendor/angular.js:12972:18
ngEventHandler/<@http://localhost:3000/vendor/angular.js:20467:15
m.event.dispatch@https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:8497
m.event.add/r.handle@https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js:4:5235

The source for google maps api

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>

I cannot figure out why the status is always not okay in the directionsService.route call [the alert with "fail" is always the one to turn up]

Am i doing it wrong? I am using angular but i think its not the issue.

Upvotes: 0

Views: 7141

Answers (1)

geocodezip
geocodezip

Reputation: 161324

You can't access myroute until it exists (inside the DirectionsService callback function). There you need to use the value:

function calcRoute(ref1, ref2) {
    var start = String(ref1);
    var end = String(ref2);
    var args = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    }
    directionsService.route(args, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var myroute = directionsDisplay.directions.routes[0];
            var distance = 0;
            for (i = 0; i < myroute.legs.length; i++) {
                distance += myroute.legs[i].distance.value;
                //for each 'leg'(route between two waypoints) we get the distance and add it to the total
            }
            document.getElementById('distance').innerHTML = distance +" meters";
        } else {
            alert("fail");
        }
    });

};

proof of concept fiddle

code snippet:

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

function initialize() {
  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
    });
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay.setMap(map);
  calcRoute("New York, NY", "Baltimore, MD");
}
google.maps.event.addDomListener(window, "load", initialize);

function calcRoute(ref1, ref2) {
  var start = String(ref1);
  var end = String(ref2);
  var args = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
  }
  directionsService.route(args, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var myroute = directionsDisplay.directions.routes[0];
      var distance = 0;
      for (i = 0; i < myroute.legs.length; i++) {
        distance += myroute.legs[i].distance.value;
        //for each 'leg'(route between two waypoints) we get the distance and add it to the total
      }
      document.getElementById('distance').innerHTML = distance + " meters";
    } else {
      alert("fail");
    }
  });

};
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="distance"></div>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

Upvotes: 1

Related Questions