Google Direction API directionsService.route()不会返回结果

时间:2015-07-23 13:08:42

标签: google-maps google-maps-api-3

我试图利用方向api来计算两个地方之间的距离。但是,.route()服务似乎不成立。

$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;
};

我正在调用calcRoute来返回距离。

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;
};

我收到以下错误:

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

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>

我无法弄清楚为什么状态在directionsService.route调用中始终不合适[带有“失败”的警报始终是要出现的警告]

我做错了吗?我使用角度,但我认为它不是问题。

1 个答案:

答案 0 :(得分:1)

在它存在之前(在DirectionsService回调函数内),您无法访问myroute。在那里你需要使用值:

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

代码段

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