Steve Steve - 4 months ago 204
AngularJS Question

Getting a reference to NgMap inside Angular controller

This syntax taken from ngMap https://github.com/allenhwkim/angularjs-google-maps works fine:

angular
.module('trails')
.controller('MyController', function (NgMap) {
NgMap.getMap().then(function (map) {
console.log(map.getCenter());
console.log('markers', map.markers);
console.log('shapes', map.shapes);
});
});


But the syntax I use for declaring controllers is different and I get the error:


angular.js:13642 TypeError: Cannot read property 'getMap' of undefined


It fails on the line as further below:


NgMap.getMap().then(function (map) {


The controller is declared as:

angular
.module('trails')
.controller('ActivityDetailsController', [
'$mdSidenav', '$mdBottomSheet', '$timeout', '$log', '$http', '$location', '$routeParams',
ActivityDetailsController
]);
function ActivityDetailsController($mdSidenav, $mdBottomSheet, $timeout, $log, $http, $location, $routeParams, NgMap) {
var self = this;

$http.get('/activity/detailStats/' + $routeParams.id, {
params: { max: "1000" }
})
.success(function (data) {
self.stats = data.stats;

// Zoom to fit
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < self.stats.activityTrackPoints.length; i++) {
var latlng = new google.maps.LatLng(self.stats.activityTrackPoints[i][0], self.stats.activityTrackPoints[i][1]);
bounds.extend(latlng);
}
NgMap.getMap().then(function (map) {
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
});

})
.error(function (data, status) {
console.error('https error', status, data);
})
.finally(function () {
});


I have tried adding the NgMap in other obvious places, such as:

...'$routeParams', NgMap,
ActivityDetailsController...


or doing a ActivityDetailsController.$inject = NgMap before the controller declaration etc but it gives a similar error to above in that NgMap cannot be referenced.

Edit: ngMap dependency was setup in another file similar to the answers already. Sorry I didn't put this earlier, but the above code that works and doesn't work are in the same place together so I thought it seemed ok to leave that out originally.

var app = angular
.module('trails', ['ngMaterial', 'md.data.table', 'ngRoute', 'ngMap'])


I'm not sure if this is to do with the way I am incorrectly trying to inject NgMap using this controller declaration or something in NgMap...or most likely my inexperience with either framework!

Answer
var app= angular.module('trails', ['ngMap']);
  app.controller('MyController', function($scope, $interval, NgMap) {
    var vm = this;
    NgMap.getMap().then(function(map) {
      vm.map = map;
    });
});