John Tough
John Tough

Reputation: 312

Google Maps not correctly initialising within Angular directive

I am trying to use the Google Maps API to display a map within an Angular site but it appears to not initialise correctly.

My html page uses bootstrap nav nav-tabs and I use an Angular controller to switch between them.

<ul class="nav navbar-nav">
    <li ng-class="{ active:myCtrl.isSet('map') }">
        <a href ng-click="myCtrl.setTab('map')">Show Map</a>
    </li>
</ul>

With one of the tabs containing only the google map canvas element - set up using an angular directive

Module.directive('mapPage', function() {
    return {
        restrict: 'E',
        template: '<div id="map-canvas"></div>'
    };
});

Within my angular controller I set up a listener for the window 'load' event to initialise the map as follows:

google.maps.event.addDomListener(window, 'load', myCtrl.initMap);


myCtrl.initMap = function() {

    var mapOptions = {
        zoom: 12,
        center: new google.maps.LatLng(55.937879, -3.241619),
    };

    myCtrl.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(55.937879, -3.241619),
        map: myCtrl.map
    });

    myCtrl.map.setCenter(new google.maps.LatLng(55.937879, -3.241619));
}

What I see on screen is the map element showing a grey area with the location marker not centered correctly (it's just off screen).

If I move the map-canvas div to the main section of my index.html page (rather than a sub page within the app) it loads correctly, so I know my Google API js code and html is correct. The map also shows if the page is resized.

It just doesn't work when used on a page that is not rendered immediately. I have tried searching for similar questions/answers but could not find this particular issue.

I have created a simple fiddle that demonstrates the issue.

http://jsfiddle.net/johntough/nc0u7h2c/5/

Any help appreciated!

Upvotes: 1

Views: 147

Answers (1)

Anand G
Anand G

Reputation: 3200

The issue is, you are loading Map on window load whereas the container will appear on click. Google Map has behavior (never seen documented yet but I have observed it many time though) that if the container is hidden on load, it does not load map in there. I changed your "load" to "click" and its working. The only change is as below,

google.maps.event.addDomListener(window, 'click', myCtrl.initMap);

See fiddle and verify yourself. http://jsfiddle.net/anandgh/nc0u7h2c/6/

Upvotes: 1

Related Questions