简体   繁体   English

Google地图无法在模态内工作

[英]Google maps not working inside modal

I have been trying to get google maps to work inside a modal but when i run it i get the error TypeError: Cannot read property 'offsetWidth' of null, i have read through all the solutions on here already and i think it may be because the modal doesn't exist when the page loads so i tried using ng-init to load it when the modal loads but i still get the same error. 我一直试图让谷歌地图在模式内工作,但是当我运行它时出现错误TypeError:无法读取null的属性“ offsetWidth”,我已经阅读了这里的所有解决方案,我认为这可能是因为页面加载时模态不存在,所以我尝试使用ng-init在模态加载时加载它,但是我仍然遇到相同的错误。 I tried putting an alert inside the map controller and found that it was running when the main page loads rather than when the modal loads. 我尝试在地图控制器中放置一个警报,发现该警报在主页加载而不是模式加载时正在运行。

Controller 控制者

.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;
}
})

Modal 模态

<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>

This error occurs when 发生此错误时

document.getElementById("map") document.getElementById(“ map”)

has no offsetWidth , so when it's not displayed. 没有offsetWidth ,因此不显示时。 You have to initialize the map when you want to show it, not before. 您必须在想要显示地图时(而不是之前)初始化地图。 So your 所以你

init() 在里面()

has been called when you click to open the modal. 单击以打开模态时已被调用。

Try to wrap the map initialization with $timeout . 尝试使用$timeout包装地图初始化。

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

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

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