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.