5

现在我已经找到了一种在Andy Joslin的帮助下在这个 SO initialize-google-map-in-angularjs中初始化 Google Maps 的方法,我正在寻找一种异步加载 Google Map Object 的方法。

我在phonecat项目中找到了如何执行此操作的示例。

注意这个例子中 JS 文件是如何加载的:​​index-async.html

在加载到我的程序中的 Jade Scripts 部分中,我尝试了:

script(src='js/lib/angular/angular.js')
script(src='js/lib/script/script.min.js')

script
  $script([
    'js/lib/angular/angular-resource.min.js',
    'js/lib/jquery/jquery-1.7.2.min.js',
    'http://maps.googleapis.com/maps/api/js?key=AIzaSyBTmi_pcXMZtLX5MWFRQgbVEYx-h-pDXO4&sensor=false',
    'js/app.js',
    'js/services.js',
    'js/controllers.js',
    'js/filters.js',
    'js/directives.js',
    'bootstrap/js/bootstrap.min.js'
    ], function() {
      // when all is done, execute bootstrap angular application
      angular.bootstrap(document, ['ofm']);
    });

当我这样做并加载地图页面时,我得到:

A call to document.write() from an asycrononously-loaded 
external script was ignored.

这就是现在将 Google 地图作为服务加载的方式:

'use strict';

var app = angular.module('ofm.services', []);

app.factory('GoogleMaps', function() {

  var map_id  = '#map';
  var lat     = 46.87916;
  var lng     = -3.32910;
  var zoom    = 15;
  var map     = initialize(map_id, lat, lng, zoom);

  return map;
});

function initialize(map_id, lat, lng, zoom) {
  var myOptions = {
    zoom : 8,
    center : new google.maps.LatLng(lat, lng),
    mapTypeId : google.maps.MapTypeId.ROADMAP
  };
  return new google.maps.Map($(map_id)[0], myOptions);
}

看来这应该是从我记得读过的内容中返回的一个承诺。但是这个 AngularJS 对我来说很新。

4

3 回答 3

7

这是我在不使用 jQuery 的情况下提出的解决方案:( Gist here )

angular.module('testApp', []).
    directive('lazyLoad', ['$window', '$q', function ($window, $q) {
        function load_script() {
            var s = document.createElement('script'); // use global document since Angular's $document is weak
            s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
            document.body.appendChild(s);
        }
        function lazyLoadApi(key) {
            var deferred = $q.defer();
            $window.initialize = function () {
                deferred.resolve();
            };
            // thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
            if ($window.attachEvent) {  
                $window.attachEvent('onload', load_script); 
            } else {
                $window.addEventListener('load', load_script, false);
            }
            return deferred.promise;
        }
        return {
            restrict: 'E',
            link: function (scope, element, attrs) { // function content is optional
            // in this example, it shows how and when the promises are resolved
                if ($window.google && $window.google.maps) {
                    console.log('gmaps already loaded');
                } else {
                    lazyLoadApi().then(function () {
                        console.log('promise resolved');
                        if ($window.google && $window.google.maps) {
                            console.log('gmaps loaded');
                        } else {
                            console.log('gmaps not loaded');
                        }
                    }, function () {
                        console.log('promise rejected');
                    });
                }
            }
        };
    }]);
于 2013-10-31T19:50:47.473 回答
5

如果您在 AngularJS 应用程序中使用 jQuery,请查看此函数,该函数promise在 Google Maps API 加载时返回一个 for:

https://gist.github.com/gbakernet/828536

我可以在 AngularJS 指令中使用它来按需延迟加载谷歌地图。工作一种享受:

angular.module('mapModule') // usage: data-google-map
    .directive('googleMap', ['$window', function ($window) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                // If Google maps is already present then just initialise my map
                if ($window.google && $window.google.maps) {
                    initGoogleMaps();
                } else {
                    loadGoogleMapsAsync();
                }

                function loadGoogleMapsAsync() {
                    // loadGoogleMaps() == jQuery function from https://gist.github.com/gbakernet/828536
                    $.when(loadGoogleMaps())
                        // When Google maps is loaded, add InfoBox - this is optional
                        .then(function () {
                            $.ajax({ url: "/resources/js/infobox.min.js", dataType: "script", async: false });
                        })
                        .done(function () {
                            initGoogleMaps();
                        });
                };

                function initGoogleMaps() {
                    // Load your Google map stuff here
                    // Remember to wrap scope variables inside `scope.$apply(function(){...});`
                }
            }
        };
    }]);
于 2013-07-01T01:23:52.253 回答
2

看看这个我认为它更可靠

    var deferred = $q.defer();
                        var script = document.createElement('script');

                        $window.initMap = function() {
                            //console.log("Map  init ");

                            deferred.resolve();
                        }
                        script.src = "//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&callback=initMap";
                        document.body.appendChild(script);
                        return deferred.promise;
于 2014-12-11T10:28:53.640 回答