此语法取自 ngMap https://github.com/allenhwkim/angularjs-google-maps工作正常:
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);
});
});
但是我用于声明 Controller 的语法不同,并且出现错误:
angular.js:13642 TypeError: Cannot read property 'getMap' of undefined
它在线路上失败,如下所示:
NgMap.getMap().then(function (map) {
Controller 声明为:
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 () {
});
我尝试在其他明显的地方添加 NgMap,例如:
...'$routeParams', NgMap,
ActivityDetailsController...
或者在 Controller 声明之前执行 ActivityDetailsController.$inject = NgMap 等,但它会给出与上面类似的错误,因为无法引用 NgMap。
编辑:ngMap 依赖项是在另一个文件中设置的,类似于已经的答案。抱歉,我没有早点把它放在一起,但是上面有效和无效的代码都在同一个地方,所以我认为最初将其排除在外似乎可以。
var app = angular
.module('trails', ['ngMaterial', 'md.data.table', 'ngRoute', 'ngMap'])
我不确定这是否与我错误地尝试使用此 Controller 声明或 NgMap 中的某些内容注入(inject) NgMap 的方式有关...或者很可能是我对任一框架都缺乏经验!
最佳答案
var app= angular.module('trails', ['ngMap']);
app.controller('MyController', function($scope, $interval, NgMap) {
var vm = this;
NgMap.getMap().then(function(map) {
vm.map = map;
});
});
关于angularjs - 在 Angular Controller 内获取 NgMap 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38407876/