Rishabh Rishabh - 2 months ago 36
AngularJS Question

How to initialize google maps API in angular without using any directives?

I am trying to initalize google maps in the application I am writing, I am using the places api for some of the functionalities which is working fine,
Now I am trying to show a map on a page but the map never shows up. i do not get any error on the console when I use the following code.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places"></script>


mapview.html

<div ng-controller="MapViewController as mapctrl" ng-init="initialize()">
<div class="container">

<div class="row">



<div id="map"></div>

</div>

<div ui-view></div>
</div>
</div>


mapViewController.js

(function(angular) {
angular.module('myapp').controller('MapViewController', ['$state','$http','$stateParams','$window','$route','$document','$localStorage','$scope','$location', function($state,$http,$stateParams,$window,$route,$document,$localStorage,$scope,$location) {

$scope.initialize = function(){
console.log("log");
var mapOptions = {
zoom: 11,
center: {lat: -34.397, lng: 150.644},
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById('map'), mapOptions);
};

}]);
})(angular)


I get the log message when the contoller is initialized but the map doesn't show on the page.
I would like to know how can I make it possible without using any directive.

Answer

Make sure to define ng-app on your html:

<html ng-app="mapApp">
 . . .
  <body ng-controller="MapController" ng-init="initMap()">
    <div id="map"></div>
  </body>
</html>

Then to initialize correctly your map on JS:

angular.module('mapApp', []);

angular
  .module('mapApp')
  .controller('MapController', MapController);

  function MapController($scope){

    $scope.initMap = function() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 3,
            center: new google.maps.LatLng(32.483, 16.084)
        });
    }

}

And give height and width to your id:

#map{
      height: 400px;
      width:  700px;
      border: 2px solid red;
 }

here you can find A Plunker I made which initializes a map without a directive.

Hope I've been helpful.