简体   繁体   English

如何在Angular应用中重新加载现有的地图对象?

[英]How do I reload an existing map object in my Angular app?

I have an Angular/Ionic javascript app in which I have google maps loaded in a view. 我有一个Angular / Ionic javascript应用程序,其中在视图中加载了Google地图。 When I run a build of the app on my iPhone, I notice that whenever Google Maps loads, it consumes quite a bit of memory. 当我在iPhone上运行该应用程序的构建时,我注意到无论何时加载Google Maps,它都会消耗大量内存。 In 1 session, I'm finding a user sees a map 30-40 times. 在1次会话中,我发现用户看到一张地图30至40次。 Each time a user gets back to the map view from a different view, I believe a new map object is created and more memory is consumed. 每次用户从不同的视图返回到地图视图时,我相信都会创建一个新的地图对象并消耗更多的内存。 As a result, I'm finding my app crashes after particularly longer sessions. 结果,我发现在经过特别长的会话后,我的应用程序崩溃了。

My question: instead of creating a new map object each time, how do I reload the same map again when the user goes to that specific view? 我的问题:不是每次都创建一个新的地图对象,而是当用户转到该特定视图时如何再次重新加载同一地图? Here is the relevant part of the code: 这是代码的相关部分:

Controller: 控制器:

    .controller('GuessCtrl', function($scope, $state, $stateParams, $ionicPopup, $ionicLoading, $ionicHistory) {

            $scope.initialise = function() {
              var myLatlng = new google.maps.LatLng(37.758446, -122.411789);
              var markersArray = [];

              //Initial settings for the map
              var mapOptions = {
                      center: myLatlng,
                      zoom: 2,
                      mapTypeId: google.maps.MapTypeId.ROADMAP,
                      styles: [{ featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }]}]

                  };

              //Load the initial map
              console.log(map); //null
              var map = new google.maps.Map(document.getElementById("map"), mapOptions);
              console.log(map); //map object details


              $scope.map=map;

            };

            google.maps.event.addDomListener(document.getElementById("map"), 'load', $scope.initialise());

    })

View: 视图:

<ion-view view-title="Guess" cache-view="false"  can-swipe-back="false">
  <ion-content scroll="false">

  <!-- START OF IMAGE -->
  <div id = "map" data-tap-disabled="true" style = "height:{{heightWidth}}px;"></div>
  <!-- END OF IMAGE -->


  </ion-content>
</ion-view>

Seem to be having a problem with the API key in the sample below but you can get the gist. 以下示例中的API密钥似乎有问题,但是您可以了解要点。 Can create an element that you just append to the directives element as you navigate between views, caution here though this means only one of these elements can be in view at once. 可以在视图之间导航时创建仅添加到指令元素的元素,请注意此处,尽管这意味着一次只能看到其中一个元素。

Some stuff in here for dealing with when an array of markers changes and compiling the infowindow contents too so buttons with ng-click and whatnot would work in there. 这里的一些内容用于处理标记数组的更改以及编译信息窗口的内容,因此带有ng-click和whatnot的按钮将在其中起作用。 The bounds related stuff is just to change the zoom level to contain some set of markers added to the map, can be removed if you don't need that, but this should give you good base. 与边界相关的内容只是更改缩放级别以包含添加到地图的一组标记,如果不需要,可以将其删除,但这应该为您提供了良好的基础。

 /** * itSimpleGoogleMap Module * * Just a google maps api wrapper */ (function(){ 'use strict'; angular.module('itSimpleGoogleMap', []) .directive('itSimpleGoogleMap', function($compile, $timeout){ // Runs during compile var _currentMarkers = []; var newdiv = document.createElement('div'); newdiv.style.width = "100%"; newdiv.style.height = "100%"; var map = new google.maps.Map(newdiv, { center: {lat: 41.90, lng: -87.65}, zoom: 10, mapTypeId: google.maps.MapTypeId.SATELLITE }); return { scope: { markers:'=', overlays:'=', triggerResize:'=' }, // {} = isolate, true = child, false/undefined = no change link: function(scope, iElm) { console.log(newdiv); iElm[0].appendChild(newdiv); _.each(_currentMarkers, function(marker){ marker.setMap(null); }) google.maps.event.trigger(map, 'resize'); scope.$watch('triggerResize', function(){ google.maps.event.trigger(map, 'resize'); }); $timeout(function(){ var mapOptions = { center: {lat: 41.90, lng: -87.65}, zoom: 10 }; scope.$watchCollection('markers', function(){ if(!scope.markers || !scope.markers[0] || !scope.markers[0].coords.latitude) { return; } _.forEach(_currentMarkers, function(curMarker){ curMarker.setMap(null); google.maps.event.clearInstanceListeners(curMarker); }); _currentMarkers = []; var bounds = new google.maps.LatLngBounds(); var infowindow = new google.maps.InfoWindow(); if(scope.markers.length==0){ map.setCenter({lat: 41.90, lng: -87.65}); return; } _.forEach(scope.markers, function(markerData){ var marker = new google.maps.Marker({ position: new google.maps.LatLng(markerData.coords.latitude,markerData.coords.longitude), map: map, icon:markerData.icon // title:markerData.data['Growing Site Name'].answer }); bounds.extend(marker.position); var infoWindowElement; $compile(markerData.infoWindow)(scope, function(cloneElm){ infoWindowElement = cloneElm[0]; }); google.maps.event.addListener(marker, 'click', function() { infowindow.close(); infowindow.setContent(infoWindowElement); infowindow.open(map,marker); }); _currentMarkers.push(marker); }); map.fitBounds(bounds); }); },500) } }; }); })(); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script> <script src="https://maps.googleapis.com/maps/api/js"></script> <div ng-app='itSimpleGoogleMap' style="width:500px; height:500px;"> <it-simple-google-map markers="model.mapOpts.markers" trigger-resize="resizeMap"> </it-simple-google-map> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM