#javascript #angularjs #google-maps #google-maps-api-3 #ng-map
#javascript #angularjs #google-карты #google-maps-api-3 #ng-map
Вопрос:
Я получаю следующую ошибку при попытке использовать службу геокодирования для библиотеки 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
Заранее спасибо за вашу помощь.
Ответ №1:
GeoCoder
сервис использует google.maps.Geocoder class
, который, в свою очередь, является частью API Карт Google. Момент, когда GeoCoder.geocode
метод вызывается в библиотеке карт Google контроллера, еще не загружен (в вашем случае он загружается асинхронно с помощью 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>
Комментарии:
1. Отлично, Вадим, это сработало, заключив его в обещание GetMap. Спасибо!
2. Это больше не работает, поскольку требуется ключ API. Кто-нибудь знает полный автономный пример?