谷歌地图无法在modal中工作

Google maps not working inside modal

本文关键字:工作 modal 谷歌地图      更新时间:2023-09-26

我一直试图让谷歌地图在模态中工作,但当我运行它时,我得到了错误TypeError:无法读取null的属性offsetWidth,我已经阅读了这里的所有解决方案,我认为这可能是因为页面加载时模态不存在,所以我尝试在模态加载时使用ng init加载它,但我仍然得到了相同的错误。我试着在映射控制器中放置一个警报,发现它在加载主页时而不是在加载模式时运行。

控制器

.controller('mapCtrl', function($scope) {
  $scope.init = function() {
    var myLatlng = new google.maps.LatLng(51.508742,-0.120850);
  var mapProp = {
    center: myLatlng,
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("map"),mapProp);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map
    });
    $scope.map = map;
}
})

模式

<ion-modal-view ng-controller="mapCtrl">
    <ion-header-bar id="modalheader">
        <h1 class="title"></h1>
<!-- button to close the modal -->
        <button class="button icon ion-android-close" ng-click="closeModal();"></button>
    </ion-header-bar>
<ion-content class="item-icon-right item-text-wrap" id="modal">
<ion-list id="modalitem">
<ion-item>
<!-- displays the larger view of the office address -->
    <h1>{{office.LocationName}}</h1>
        <p id="mdets">{{office.LocAddressLine1 + ", " + office.LocAddressLine2 + ", " + office.LocCity + ", " + office.LocCountryDescription + ", " + office.LocZipPostalCode}}</p>
        <i ng-class="{'icon ion-android-star': favicon(office.id), 'icon ion-android-star-outline': !favicon(office.id)}"  ng-click="togglefav(office.id); $event.stopPropagation();"></i>
    </ion-item>
</ion-list>
<!-- creates the map view from the json data -->
<div ng-init="init()">
    <div id="map" style="width:500px;height:380px;"></div>
</div>
</ion-content>
</ion-modal-view>

出现此错误

document.getElementById("map")

没有offsetWidth,因此当它不显示时。您必须在想要显示地图时对其进行初始化,而不是在之前。所以你的

init()

已在单击打开模态时调用。

尝试用$timeout封装映射初始化。

$timeout(function() {
  $scope.init();
})