在单页应用程序上重用Google Maps API实例

URL*_*L87 7 javascript google-maps google-maps-api-3 angularjs

假设我有一个单页面应用程序(Angular JS应用程序),并在元素id上绘制一个Google Map实例googleMap-

var mapInstance = new google.maps.Map(document.getElementById(`googleMap`), mapOption)
Run Code Online (Sandbox Code Playgroud)

然后我浏览应用程序路由,因此,销毁googleMapDOM元素,最后我回到使用此元素的路径,现在我必须在此元素上重新绘制地图.

重绘地图的正确方法是什么?

当我在这个答案中读到时, 我不必重新创建它,而是使用相同的实例.

Jag*_*ags 5

我会小心

$scope.on('$destroy', function(){
    mapInstance = null;
})
Run Code Online (Sandbox Code Playgroud)

我有一个包含地图 DOM 元素的指令,并调用此方法从数据层、所有侦听器中删除所有地图引用,然后将地图设置为 null。我正在检查页面导航之间的堆,并且正在重新创建地图实例,但旧地图仍在堆中,导致内存使用量不断增加。

此外,您链接的答案建议重新使用您的地图实例,而不是尝试删除它。谷歌地图开发人员也推荐这种方法。我找到的解决方案是将指令元素传递给服务,并将子元素附加到在新子元素上创建地图的子元素。如果地图已经存在,只需将地图 div 附加到指令元素即可。下面是我的代码。

ng-view 元素

<map-container></map-container>
Run Code Online (Sandbox Code Playgroud)

指示

angular.module('project')
  .directive('mapContainer', function($timeout, mapService) {
     return {
       template: '<div></div>',
       restrict: 'E',
       replace: true,
       link: function(scope, element) {
         $timeout(function () {
           //Use the $timeout to ensure the DOM has finished rendering
           mapService.createMap(element).then(function() {
              //map now exists, do whatever you want with it
           });
        });
      }
    };
 })
Run Code Online (Sandbox Code Playgroud)

服务

angular.module('project')
  .service('mapService', function($q) {

    var lat = -33.1798;
    var lng = 146.2625;
    var minZoom = 5;
    var maxZoom = 20;
    var zoom =  6;
    var mapOptions = null;
    var map = null;

    function initialiseGmap(element) {

      return $q(function (resolve) {
        if (map) {
          //Map already exists, append it
          element.append(map.getDiv());
          resolve();
        } else {
          //No map yet, create one
          element.append('<div id="map_canvas"></div>');

          mapOptions = {
            zoom: zoom,
            center: new google.maps.LatLng(lat, lng),
            styles: hybridMap, //your style here
            minZoom: minZoom,
            maxZoom: maxZoom,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            streetViewControl: false,
            panControl: false,
            scaleControl: true,
            zoomControl: false
          };

          map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

          //create any map listeners you want here. If you want to add data to the map and add listeners to those, I suggest a seperate service.

          resolve();
        }
      });
    }

    return {
      createMap: function(elem) {
        return initialiseGmap(elem);
      },
      getMap: function() {
        return map;
      },
      //Create as many functions as you like to interact with the map object
      //depending on our project we have had ones to interact with street view, trigger resize events etc etc.
      getZoom: function() {
        return zoom;
      },
      setZoom: function(value) {
        map.setZoom(zoom);
      }
    };
  });
Run Code Online (Sandbox Code Playgroud)


jon*_*bbs 2

这个问题有 angularjs 标签,所以我假设这是一个 Angular JS 应用程序。在这种情况下,您可能不应该在页面控制器中执行此操作。

您可以使用预先存在的指令,例如https://angular-ui.github.io/angular-google-maps/#!/或者您可以编写自己的指令。

如果您编写自己的指令,那么您应该在每次使用 $scope.on('$destroy', fn) 事件销毁该指令时销毁 google 地图实例。像这样..

$scope.on('$destroy', function(){
    mapInstance = null;
})
Run Code Online (Sandbox Code Playgroud)