为什么我无法在Angular中向Google Maps API发出AJAX请求

时间:2016-09-01 16:41:29

标签: javascript angularjs json ajax google-maps

我正在尝试在Angular中验证我的表单中的zipcode字段,并且使用标准DirectionsService.route()证明这是不可能的,所以我正在尝试发出$ http请求。 如果我没有指定方法,我会收到CORS错误。如果我将方法设置为JSONP,它会很好,但它不会触及我的then()函数。我只是得到一个解析错误。我已经尝试过将回调添加到我的网址中,就像文档建议一样,并没有做任何修复。

为什么Directions API会在其文档中提供如此多的示例网址,例如“https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY”如果我无法使用此方法?

var url = 'https://maps.googleapis.com/maps/api/directions/json?origin=53703&destination=54481&key=AIzaSyBXbK2tp2WmjBsnwS8QNiqH7QMKxMIZ86A&callback=JSON_CALLBACK';
            $http({method:'get', url: url}).then(function(response){
                var data = JSON.parse(angular.fromJson(response.data));
                console.log(data);
            });

我无法改变这一点以提出正确的要求。但是如果他们继续显示examples with URLs而不仅仅是DirectionsService,它必须是可能的,这对于Angular中的自定义验证不起作用。

directionsService.route({
        origin: '53075',
        destination: '"'+zip+'"',
        travelMode: 'DRIVING'
    }, this.getDistanceCallback);

2 个答案:

答案 0 :(得分:0)

我通过切换到Mapquest API解决了我的问题。不完全确定Google Maps端点的问题。但Mapquest允许我轻松地在Angular中执行AJAX请求。

答案 1 :(得分:0)

我不知道你正在对你回来的路线做什么,但我能够设置一个简单的应用程序,它将列出overview_path route的所有节点}。

一个难点是,您将同步加载Maps API而不是<script async defer src="...">。我认为制作一个服务工厂有点奇怪,无论何时你可以开始使用该服务我都会解决这个问题。你可以做到,这有点奇怪。

(function() {
  "use strict";

  var mapApp = angular.module("map-app", []);

  mapApp.service("MapSrvc", function($q) {
    var directionsService = new google.maps.DirectionsService;

    this.getDirections = function(start, end, mode) {
      mode = mode || "DRIVING";
      var deferred = $q.defer();

      directionsService.route({
        origin: start.toString(),
        destination: end.toString(),
        travelMode: mode
      }, function(response, status) {
        if (status === "OK") {
          deferred.resolve(response);
        } else {
          deferred.reject("Something went wrong");
        }
      });

      return deferred.promise;
    };
  });

  mapApp.controller("MapCtrl", function($scope, MapSrvc) {
    $scope.start = 53075;
    $scope.end = 54481;
    $scope.mode = "DRIVING";
    $scope.modes = [{
      name: "Driving",
      mode: "DRIVING"
    }, {
      name: "Walking",
      mode: "WALKING"
    }, {
      name: "Transit",
      mode: "TRANSIT"
    }];
    $scope.directions = [];
    $scope.submitHandler = function() {
      MapSrvc.getDirections($scope.start, $scope.end, $scope.mode).then(function(directions) {
        $scope.directions = directions.routes[0].overview_path.map(function(latlng) {
          return {
            lat: latlng.lat(),
            lng: latlng.lng()
          }
        });
      });
      return false;
    }
  });
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBXbK2tp2WmjBsnwS8QNiqH7QMKxMIZ86A"></script>


<main ng-app="map-app">
  <h1>Mapper</h1>
  <div ng-controller="MapCtrl">
    <section>
      <h2>Where do you want to go?</h2>
      <form name="mapper" ng-submit="submitHandler()">
        <fieldset>
          <legend>Travel Parameters</legend>
          <ul>
            <li>
              <label for="start">Start</label>
              <input id="start" type="text" ng-model="start">
            </li>
            <li>
              <label for="end">End</label>
              <input id="end" type="text" ng-model="end">
            </li>
            <li>
              <select ng-model="mode" ng-options="mode.mode as mode.name for mode in modes"></select>
            </li>
            <li>
              <input type="submit">
            </li>
          </ul>
        </fieldset>
      </form>
    </section>
    <section>
      <h2>Directions</h2>
      <ul>
        <li ng-repeat="direction in directions track by $index">{{direction.lat}}, {{direction.lng}}</li>
      </ul>
    </section>
  </div>
</main>