角度缓存谷歌地图方向服务

时间:2015-10-09 01:07:38

标签: angularjs google-maps service factory direction

我的工厂里有这种方法

function getGoogleMapPath(src) {
        var promises = [];

        var directionsService = new google.maps.DirectionsService();

        src.forEach(function(path) {
            var defer = $q.defer();

            directionsService.route(path, function(response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    defer.resolve(response); // i want to cache this response

                    return;
                } 
                console.log(status);
                defer.reject(status);
            });                

            promises.push(defer.promise);
        });

        return $q.all(promises);
    }

我在使用promises访问它的不同状态下有2个视图,但我遇到了OVER_QUERY_LIMIT

要解决这个问题,我希望在获得方向时缓存方向,而不是两次要求方向。

我如何在工厂中缓存它?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

将充当缓存的新服务:

// declare a new service to act as the cache
angular.app('myApp').service('myCache', function() {

  // initialize an object to be the cache dictionary
  this.directions = {};

});

在现有工厂中使用上述缓存服务:

// inject the new cache service into your existing factory
angular.app('myApp').factory('googleMaps', function(myCache) {

  function getGoogleMapPath(src) {
    var promises = [];

    var directionsService = new google.maps.DirectionsService();

    src.forEach(function(path) {
      var defer = $q.defer();

      // check if this path is in cache
      if (myCache[path]) {

        //  and use it, if it is present in the cache
        defer.resolve(myCache[path]);

      } else {  // new path - call Google Maps service

        directionsService.route(path, function(response, status) {
          if (status === google.maps.DirectionsStatus.OK) {

            // this is where new directions are added into the cache
            myCache.directions[path] = response;

            defer.resolve(response); // i want to cache this response

            return;
          }
          console.log(status);
          defer.reject(status);
        });

      }

      promises.push(defer.promise);
    });

    return $q.all(promises);
  }

  return {
    getGoogleMapPath: getGoogleMapPath
  };
});

我没有对此进行过测试 - 因此可能还有一些问题需要解决。但是这应该为您提供一种实现缓存响应的方法。