简体   繁体   English

如何使用Angular指令强制将Google Maps加载到我的Angular应用中

[英]How can I force Google Maps to load in my Angular app using an Angular Directive

I have an issue where my Google Map does not display 80% of the time. 我遇到一个问题,即我的Google地图在80%的时间内都无法显示。 It seems to be a situation where my map has not completely rendered by the time the rest of my data has been populated in my Angular view. 在我的Angular视图中填充剩余数据时,似乎还没有完全渲染地图。

How can I force my map to load? 如何强制加载地图?

I have done some research, and I have found this answer on a related questions, but I am not sure how and if I can implement something like this: 我已经进行了一些研究,并在一个相关的问题上找到了这个答案,但是我不确定如何以及是否可以实现以下内容:

This was bothering me for a while with GMaps v3. 使用GMaps v3困扰了我一段时间。 I found a way to do it like this: 我找到了这样的方法:

 google.maps.event.addListenerOnce(map, 'idle', function(){ // do something only the first time the map is loaded }); 

The "idle" event is triggered when the map goes to idle state - everything loaded (or failed to load). 当地图进入空闲状态时,即触发“空闲”事件-一切已加载(或加载失败)。 I found it to be more reliable then tilesloaded/bounds_changed and using addListenerOnce method the code in the closure is executed the first time "idle" is fired and then the event is detached. 我发现它比tilesloaded / bounds_changed更可靠,并使用addListenerOnce方法,在第一次触发“ idle”后执行关闭中的代码,然后分离事件。

Link: How can I check whether Google Maps is fully loaded? 链接: 如何检查Google Maps是否已满载?

This is my current setup: 这是我当前的设置:

1. My Google Maps API link and key is in my index.html file: 1.我的Google Maps API链接和密钥位于index.html文件中:

<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXX"></script>

2. I use the following as my Angular Directive: 2.我将以下内容用作我的Angular指令:

'use strict';

angular.module('portalDashboardApp')
  .directive('ogGoogleMap', function ($http, $q) {
      return {
          restrict: 'E',
          scope: {
              twitter: '=',
              instagram: '='
          },
          template: '<div id="gmaps"></div>',
          replace: true,
          link: function (scope, element, attrs) {

              var map, infoWindow;
              var markers = [];

              // map config
              var mapOptions = {
                  center: new google.maps.LatLng(-0.013026, 21.333860),
                  zoom: 3,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
              };

              // init the map
              function initMap() {
                  if (map === void 0) {
                      map = new google.maps.Map(element[0], mapOptions);
                  }
              }

              // place a marker
              function setMarker(map, position, title, content, icon) {

                  if (icon === 'IN') {
                      icon = 'images/instagramMarker.png';
                  }
                  else {
                      icon = 'images/twitterMarker.png';
                  }

                  var marker;
                  var markerOptions = {
                      position: position,
                      map: map,
                      title: title,
                      icon: icon
                  };

                  marker = new google.maps.Marker(markerOptions);
                  markers.push(marker); // add marker to array

                  google.maps.event.addListener(marker, 'click', function () {
                      // close window if not undefined
                      if (infoWindow !== void 0) {
                          infoWindow.close();
                      }
                      // create new window
                      var infoWindowOptions = {
                          content: content
                      };
                      infoWindow = new google.maps.InfoWindow(infoWindowOptions);
                      infoWindow.open(map, marker);
                  });
              }

              function deleteCurrentMarkers() {
                  for (var i = 0; i < markers.length; i++) {
                      markers[i].setMap(null);
                  }
                  markers = [];
              }

              scope.$watch('instagram', function () {
                  deleteCurrentMarkers();
                  populateMarkers(scope.twitter, 'TW');
                  populateMarkers(scope.instagram, 'IN');
              });

              // show the map and place some markers
              initMap();

              function populateMarkers(locationArray, type) {

                  angular.forEach(locationArray, function (location) {

                      setMarker(map, new google.maps.LatLng(location[0], location[1]), '', '', type);

                  });

              }

          }
      };
  });

3. I use the following simple method of assigning my map data in my Angular Controller: 3.我使用以下简单方法在Angular Controller中分配地图数据:

First I retrieve my data: 首先,我检索数据:

function pullSocialData() {

    SocialMediaUserService.getKeywordProfileID().then(function (keywordProfileID) {

        GetFusionDataService.getItems(getRequestURL(keywordProfileID))
          .success(function (data) {

              formatDataAccordingToLocation(data);

          })
          .error(function (error, status) {
              handleDataRetrievalError(error, status);
          });

    });
}

The I assign my data: 我分配我的数据:

function formatDataAccordingToLocation(data) {
    $scope.twitterLocations = data.lat_longs_twitter;
    $scope.instagramLocations = data.lat_longs_instagram;
}

This is what my data from the API looks like: 这是我来自API的数据:

lat_longs_twitter: [
    [
    -25.77109,
    28.09264
    ],
    [
    -26.1078272,
    28.2229014
    ]
]

4. My HTML map div: 4.我的HTML地图div:

<div ng-show="!demographics.showDemographicsGraph">
    <og-google-map twitter="twitterLocations" instagram="instagramLocations"></og-google-map>
</div>

When my map loads properly, it looks like this: 当我的地图正确加载时,它看起来像这样:

在此处输入图片说明

When it doesn't load properly it looks like this: 如果无法正确加载,则如下所示:

在此处输入图片说明

Thank you in advance! 先感谢您!

In your directive link function, try to move initMap inside the map idle callback: 在指令链接函数中,尝试将initMap移到地图idle回调中:

google.maps.event.addListenerOnce(map, 'idle', function(){ 
   // show the map and place some markers
   initMap();
});

To make my map load, I added some validation to check whether my data has returned before initializing the map. 为了加载地图,我添加了一些验证以在初始化地图之前检查数据是否已返回。 I also added a timeOut for good measure, to give the map more time to render. 我还添加了timeOut作为很好的度量,以便给地图更多的渲染时间。

I made the following change in my Angular Directive: 我在“角度指令”中进行了以下更改:

scope.$watch('instagram', function () {
  if (scope.twitter != undefined || scope.instagram != undefined) {
      initMap();
      setTimeout(function () {
          deleteCurrentMarkers();
          populateMarkers(scope.twitter, 'TW');
          populateMarkers(scope.instagram, 'IN');
      }, 3000);
  }
});

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

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