How to render maps within ng-hide divs using ngMap

2019-07-20 02:23发布

问题:

The problem: Google Maps elements that are within divs that are initially rendered as ng-hidden come up as gray rectangles when they are ng-shown.

I've put together this Plunker to demonstrate: https://plnkr.co/edit/emzlIT?p=preview

Others have had success using google.maps.event.trigger(map,'resize'), but for me it is no help, perhaps because I have multiple maps hidden. On this plunker, 'resize' seems to make a difference, but not consistently. If you play with the Plunker and everything seems to be working, try panning around an ng-shown map and you'll get the gray.

The example shown is, of course, a very simplified version of the actual web-app I'm working on. Suffice it to say that using ng-if instead of ng-show (also worked for others) isn't an option, nor is having my maps always shown (though if no solutions are found, I may have to think outside the div.)

Note: if you get a grayed out map, zooming the browser in or out seems to jump-start the render & then the maps work perfectly, even if hidden and re-shown I don't know what about the browser zoom triggers the desired behavior, but perhaps that's a clue to you.

回答1:

This behavior is most likely related with ng-hide directive which in turn adds display: none style on the parent element. It was already reported (link) that Google Maps control has some issues with rendering once the map is located inside the element that has display: none style.

I would suggest to replace ng-hide directive:

<div ng-hide="div1Hide" class="mapCase">
    <ng-map id="map1" class="map" center="[-33.851371, 151.277736]" zoom-level="18">Parsley</ng-map>
</div>

with, for example, ng-class directive:

<div class="mapCase" ng-style="{'visibility': !div1Hide ? 'visible':'hidden'}">
     <ng-map id="map1" class="map" center="[-33.851371, 151.277736]" zoom-level="18">Parsley</ng-map>
</div>

Modified plunker