【问题标题】:How to let the angular-google-maps load lazily and not break the page if the google-maps-api is not visitable?如果 google-maps-api 不可访问,如何让 angular-google-maps 延迟加载而不破坏页面?
【发布时间】:2014-09-04 16:00:41
【问题描述】:

我正在使用 requirejs + angularjs + angular-google-maps 在地图上显示一些房子的位置。

在我的页面上,有一张地图和一些其他信息,其他信息比地图更重要,所以我希望地图可以懒惰显示,即使地图由于某种原因不显示也没关系(e.g.无法加载谷歌地图 api)。

我的代码是这样的:

ma​​in.js

require.config({
    baseUrl: 'app',
    paths: {
        jquery: '../bower_components/jquery/dist/jquery',
        angular: '../bower_components/angular/angular',
        'angular-google-maps': '../bower_components/angular-google-maps/dist/angular-google-maps',
        googlemaps: '../bower_components/googlemaps-amd/src/googlemaps',
        async: '../bower_components/requirejs-plugins/src/async',
        underscore: '../bower_components/underscore/underscore'
    },
    shim: {
        angular: {
            exports: "angular"
        },
        'angular-google-maps': {
            deps: ['googlemaps!', 'angular', 'underscore']
        }
    }
});

require(['googlemaps!', 'jquery', 'angular', 'angular-google-maps', 'controllers'],
    function (googlemaps, jquery, angular, angularGoogleMaps, controllers) {
        angular.module('app', ['controllers', 'google-maps']);

        angular.element(document).ready(function () {
            angular.bootstrap(document, ['app']);
        });
    }
);

我使用了 googlemaps-amd 库,它是一个 requirejs 模块,将异步加载 google-maps-api-v3,并等待 api 加载成功。

angular-google-maps 模块提供了一个名为 google-maps 的 angularjs 模块,我的主要 angular 模块 app 依赖于它。

所以在代码中,我的 angularjs 代码将在 google-maps-api-v3 和 angular-google-maps 全部加载后执行。这是我对这个问题最关心的问题。

controllers.js的内容:

controllers.js

define(['angular'], function (angular) {
    return angular.module('controllers', [])
        .controller('Ctrl', ['$scope', function ($scope) {
            $scope.hello = "Hello, world";
            $scope.houses = [
                {
                    key: '111',
                    location: {
                        "longitude": 144.99918,
                        "latitude": -37.81859
                    }
                },
                {
                    key: '222',
                    location: {
                        "longitude": 140.99918,
                        "latitude": -40.81859
                    }
                }
            ];

            $scope.map = {
                center: {
                    "longitude": 144.99918,
                    "latitude": -37.81859
                },
                zoom: 13,
                options: {
                    disableDefaultUI: !0,
                    mapTypeControl: !1,
                    tilt: 45
                }
            }
        }])
});

它只是定义了一个控制器和地图所需的数据。

还有html:

index.html

<html>
<head>
    <link type="text/css" rel="stylesheet" href="css/main.css">
</head>
<body>
hello
<div ng-controller="Ctrl">
    {{hello}}
    <div ng-if="map">
        <google-map center="map.center" zoom="map.zoom" options="map.options">
            <markers
                    models="houses"
                    idKey="'key'"
                    doRebuildAll="true"
                    doCluster="true"
                    fit="true"
                    coords="'location'">
            </markers>
        </google-map>
    </div>
    {{houses}}
</div>
</body>
<script type="text/javascript" data-main="../build/main" src="../bower_components/requirejs/require.js"></script>
</html>

../build/main是打包压缩成一个js文件,但你可以认为是我一开始提供的main.js

现在地图可以正确显示了,但是您知道,出于某种原因,google-map-api 在某些国家/地区有时会被阻止或速度极慢是很常见的。然后页面完全损坏,您会看到占位符@显示了 987654332@ 和 {{houses}},即使它们在地图上不是很相关。可悲的是。

是否可以让 angular-google-maps 指令延迟加载?

即使速度很慢或损坏也不阻止其他内容?

【问题讨论】:

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


    【解决方案1】:

    好吧,代替使用 {{ variableName }} 您可以使用括号不显示...这样可以解决该问题。

    否则,您只需添加一些 try...catch 语句以确保页面不会中断

    【讨论】:

      【解决方案2】:

      在一个使用谷歌地图的小项目中,我遇到了在绘制地图之前准备好数据的问题。 我在地图“tilesloaded”事件中解决的承诺中操纵了地图。 类似的东西应该适合你,虽然我没有使用 angular-google-maps...

      .directive('aMap', function() {
          var mapid = 1;
          return {
              restrict: 'E',
              link: function (scope, element, attrs, ctrl) {
                  var el = document.createElement("div");
                  el.style.width = "100%";
                  el.style.height = "100%";
                  element.prepend(el);
                  var mapOptions = {
                          center: new google.maps.LatLng(0,0),
                          zoom  : 1
                  };
                  var map = new google.maps.Map(el, mapOptions);
                  map.id = mapid++;
                  google.maps.event.addListener(map, 'tilesloaded', function () {
                      google.maps.event.clearListeners(map, 'tilesloaded');
                      if ( scope.mapDefer )
                          scope.mapDefer.resolve(map);
                      return;
                  });
              }
          };
      })
      .controller('myCtrl', function ($log, $scope, $q, StudyData, mngGeocodeService) {
          $scope.mapDefer = $q.defer();
          $scope.mapDefer.promise
          .then( function ( map ) { drawMap(map) } );
      
          function drawMap ( map ) {
      
              mngGeocodeService.get('United States of America')
              .then (
                      function ( results, status ) {
                          if ( results.length === 0 )
                              return;
                          var bounds = new google.maps.LatLngBounds(
                                  new google.maps.LatLng(results[0].geometry.viewport.southwest.lat, results[0].geometry.viewport.southwest.lng ),
                                  new google.maps.LatLng(results[0].geometry.viewport.northeast.lat, results[0].geometry.viewport.northeast.lng )
                          );
                          map.fitBounds(bounds);
                      }
              );
      
              for ( var i=0; i<StudyData.length; i++ ) {
                  addCircle(map, i);
              }
          }
          function addCircle ( map, index ) {
              mngGeocodeService.get(StudyData[index].name)
              .then (
                      function ( results, status ) {
                          if ( results.length === 0 )
                              return;
                          var radius = 30000 * Math.sqrt(100/StudyData[index].yearsBetweenAccidents);
                          new google.maps.Circle({
                              strokeColor: '#FF0000',
                              strokeOpacity: 0.8,
                              strokeWeight: 2,
                              fillColor: '#FF0000',
                              fillOpacity: 0.35,
                              map: map,
                              center: results[0].geometry.location,
                              radius: radius
                          });
      
                      }
              );
          }
      
          return;
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 2011-03-15
        • 1970-01-01
        相关资源
        最近更新 更多