我在尝试将地理编码器服务用于ng-map库时收到以下错误:
angular.js:13642 ReferenceError: google is not defined
at Object.t [as geocode] (http://localhost:6240/Scripts/ng-map.min.js:25:28246)
我正在将服务注入我的控制器
appModule.controller('MyController', ['$scope', 'NgMap', 'NavigatorGeolocation', 'GeoCoder',
function ($scope, NgMap, NavigatorGeolocation, GeoCoder) {
GeoCoder.geocode({address: 'Avenida Calle 26 # 40-40, Bogotá'}).then(function (result) {
//... do something with result
console.log('RESULT GEOCODER: ', result);
});
}]);
我还使用 NgMap 函数对其进行了测试,获得了相同的引用错误
NgMap.getGeoLocation('Avenida Calle 26 # 40-40, Bogotá').then(function (result) {
console.log('GETGEOLOCATION: ', result);
}, function (error) {
console.log('Error getting geolocation: ', error);
});
如代码片段所示,我已经成功地使用了其他NgMap和NavigatorGeolocation服务。
这是我页面的代码
<div map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{ $ctrl.googleMapsUrl }}">
<div class="row">
<div class="col-md-6">
<ng-map id="map"
center="{{ $ctrl.mapCenter }}"
street-view="{{ $ctrl.svp }}"></ng-map>
</div>
<div class="col-md-6">
<ng-map id="sv" />
</div>
</div>
</div>
并在相应的控制器/组件中
$ctrl.googleMapsUrl = "https://maps.googleapis.com/maps/api/js?key=MY-API-KEY";
$ctrl.mapCenter = 'current-location';
NavigatorGeolocation.getCurrentPosition({ timeout: 10000 }).then(function (ll) {
$ctrl.svp = "StreetViewPanorama(document.querySelector('ng-map#sv'), {position:new google.maps.LatLng(" + ll.coords.latitude + " , " + ll.coords.longitude + ")})";
}, function (error) {
console.log('error getCurrentPosition: ', error);
});
我正在使用 AngularJS v1.5.6
提前感谢您的帮助。
GeoCoder
服务利用google.maps.Geocoder class
而在控制器 Google 地图库中调用该方法GeoCoder.geocode
尚未加载(在您的情况下,它是通过 map-lazy-load
指令异步加载的(,这就是发生此错误的原因。
您可以使用NgMap.getMap
函数来保证Google Maps API已准备就绪:
NgMap.getMap("map").then(function () {
GeoCoder.geocode({ address: 'Avenida Calle 26 # 40-40, Bogotá' })
.then(function (result) {
//...
});
});
演示
angular.module('mapApp', ['ngMap'])
.controller('mapCtrl', ['$scope', 'NgMap', 'NavigatorGeolocation', 'GeoCoder',
function ($scope, NgMap, NavigatorGeolocation, GeoCoder) {
vm = this;
NgMap.getMap("map").then(function () {
GeoCoder.geocode({ address: 'Avenida Calle 26 # 40-40, Bogotá' })
.then(function (result) {
vm.mapCenter = result[0].geometry.location;
});
});
vm.googleMapsUrl = "https://maps.googleapis.com/maps/api/js";
vm.mapCenter = null;
}]);
<script src="https://code.angularjs.org/1.5.6/angular.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div ng-app="mapApp" ng-controller="mapCtrl as vm">
<div map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{ vm.googleMapsUrl }}">
<ng-map id="map" center="{{ vm.mapCenter }}"></ng-map>
</div>
</div>