简体   繁体   中英

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. 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")

has no offsetWidth , so when it's not displayed. 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(function() {
  $scope.init();
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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