【问题标题】:How can I reinitialize ngMaps when changing routes in Angular, using ui-router?如何在使用 ui-router 在 Angular 中更改路由时重新初始化 ngMaps?
【发布时间】:2016-10-26 17:46:12
【问题描述】:

我正在使用ngMap,这是我的相关代码:

<div map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{googleMapsUrl}}" ng-style="{'height': feedActualHeight + 'px'}">
        <ng-map id="iPadFeedMap" zoom="14" center="Times Square, New York, NY">
        </ng-map>
      </div>

这很好用并且可以完美地加载地图。但是当我离开然后返回页面时,地图显示为灰色:

有没有办法在这个页面加载时重新初始化地图?

【问题讨论】:

    标签: angularjs google-maps google-maps-api-3 ng-map


    【解决方案1】:

    无论center 是如何设置的,我都遇到了完全相同的问题(它在 lat/lng 和物理地址上都失败了),但接受的答案对我来说并不完全有效。

    我的解决方案是每次返回时使用 NgMap 的 lazy-init 属性重新初始化地图。

    <ng-map id="dashboard-map"
            center="Boston, MA"
            lazy-init="true"
            zoom="9"
            map-type-id="TERRAIN">
    </ng-map>
    

    在我的ctrl 中,我使用以下代码 1) 在 DOM 中找到未初始化的映射,然后 2) 对其进行初始化

    // dashboardCtrl.js
    
    NgMap.getMap({ id: "dashboard-map" }).
      then(function(map) {
        NgMap.initMap(map.id);
      });
    

    这样每次我点击仪表板时,ctrl 都会运行并重新初始化地图。现在每次都能正确显示。

    这是一个有用的阅读主题:https://github.com/allenhwkim/angularjs-google-maps/issues/387

    【讨论】:

      【解决方案2】:

      它似乎只发生在 center 属性的值作为 address 值提供的情况下(例如Times Square, New York, NY)。在这种情况下,确定地图中心的方式包括以下步骤:

      因为当中心属性作为位置值提供时(例如[40.759011, -73.98447220000003])我从未发生过这个问题,我建议更改地图的初始化方式:

      • 移除center属性center="Times Square, New York,NY"的设置

      • 改为设置地图中心,如下所示:

      示例:按地址设置地图中心

      NgMap.getMap("iPadFeedMap").then(function (map) {
           NgMap.getGeoLocation($scope.address)
           .then(function (latlng) {
                  map.setCenter(latlng);
           });
      });
      $scope.address = "Times Square, New York, NY";
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 2018-08-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多