manutdfan
manutdfan

Reputation: 295

Google Maps not working with Angular Routing

I am using ng-view to load the map page. I can see for a split second that the form inputs show from the map page and then they go away.

map-page.html

<input id="pac-input" class="controls" type="text"
    placeholder="Enter a location">
<div id="type-selector" class="controls">
  <input type="radio" name="type" id="changetype-geocode">
  <label for="changetype-geocode">Geocodes</label>
</div>

<div id="map" ng-init="initializeMap()"></div>

Index.html

<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Google Libraries -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&libraries=places"></script>

<!-- Bootstrap Core JavaScript -->
<script src="https://code.angularjs.org/1.5.0/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0/angular-route.js"></script>

<script src="js/app.js"></script>

App.js

Route -

 .when('/show', {
      templateUrl: './views/show.html',
      controller: 'planController'
    })

planController

$scope.initializeMap = function() {
var map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: -33.8688, lng: 151.2195},
  zoom: 13
});

  }

What am I doing wrong. I have tried almost everything from reading google docs to reading other answers on STOverflow. For now I just resorted to rendering map page from the server, which works fine.

But I would ideally want to use angular routing for loading this map.

Upvotes: 2

Views: 1387

Answers (1)

manutdfan
manutdfan

Reputation: 295

Figured it out. To make Angular routing work with Google Maps Api,

DOM elements have to load before the map script is initiated. And before the DOM elements and the map script, the Google API Library has to be loaded. So in order

  1. Load the Google API in the head before angular routing or use a callback in the body tags like

  2. Before the callback is executed, the DOM element with the id=Map should be loaded.

  3. So before anything, load the DOM and use ng-init to execute map initialization script.

This took care of my problem.

P.S - Side note about Google Maps, all the parent elements of the map container should have a height property in CSS or the map does not show.

Upvotes: 2

Related Questions