2017-09-19 2 views
0

를 정의되어 있지 않습니다. 지도는 내가 지오 기능을 사용하려고 할 때마다 그러나, 나는 오류 ReferenceError가 얻을, 고급로드 : Google은를 정의되어 있지 않습니다.AngularJS와 구글지도 API는 - 구글은 내가 AngularJS와 단일 페이지 응용 프로그램에서 일하고 있어요, 나는 응용 프로그램에 대한 매핑 시스템을 구축하기 위해 노력하고있어

지도 컨트롤러

(function() { 
    'use strict'; 
    angular 
     .module('CityWits') 
     .controller('mapCtrl', mapCtrl); 

    mapCtrl.$inject = ['$scope', '$http', 'mapApi', '$q']; 

    function mapCtrl($scope, $http, mapApi, $q){ 
     var vm = this; 
     vm.setQuery = setQuery; 

     // todo: Switch this out with deals that are loaded depending on the radius of the map 


     getBranches(); 

     function setQuery(query) { 
      console.log("business deal filter controller : query=" + query); 
      vm.query = query; 
      vm.focus = false; 
     } 

     function getBranches(){ 
      $http.get('app/cwitsTestData/branchData.json').then(function(data){ 
       vm.branches = sortBranches(data.data.branches); 
       $scope.$broadcast("branchesSorted", vm.branches); 

      }); 
     } 

    } 
    function sortBranches(branches){ 
     var locations, address, text; 
     locations = []; 
     for(var branch in branches){ 
      address = branches[branch].address; 
      text = address.street_line1 + " " + address.city+ " " +address.state; 
      locations.push(text); 
     } 
     return locations; 
    } 

})(); 

여기에 내가 API를 처리하기 위해 쓴 구글 공장이다 :

(function() { 
    'use strict'; 

    angular 
     .module('CityWits') 
     .factory('mapApi', mapApi); 



    function mapApi() { 
     var mapApi = {} 
     var markers = []; 
     var geocoder; 
     var service; 


     mapApi.geocode = geocode; 
     mapApi.marker = marker; 
     mapApi.distance = distance; 
     return mapApi; 

     function geocode (addresses){ 
      geocoder = new google.maps.Geocoder(); 
      var coords = []; 
      if(geocoder){ 
       for(var i in addresses){ 
        geocoder.geocode({ 'address': addresses[i]}, function(results, status) { 

          if (status === 'OK') { 
          coords.push(results[0].geometry.location); 
          } else { 
          alert('Geocode was not successful for the following reason: ' + status); 
          } 
        }); 
       } 
      } 
     } 

     function distance(start, end, method="DRIVING"){ 
      service = new google.maps.DistanceMatrixService; 
      service.getDistanceMatrix({ 
       origins: start, 
       destinations: end, 
       travelMode: method 
      }, function (status, response){ 
       if(status ==! "OK"){ 
        console.log("Error: "+status); 
       } else { 
        console.log("distance measured"); 

        var result = {}; 
        for(var i in response.rows){ 
         result = response.rows[i].element; 
        } 
        return result; 
       } 
      }); 
     } 

     function marker(positions, json){ 
      if(markers.length > 0){ 
       for(o in markers){ 
        markers[o].setMap(null); 
       } 
      } 
      for(x in positions){ 

      } 
     } 

    } 


})(); 

을 그리고 마지막으로이 API를 시작하는 지시자입니다 : 분명히

(function() { 
    'use strict'; 
    angular 
     .module('CityWits') 
     .directive('dealMap', dealMap); 

    dealMap.$inject = ['$timeout', '$http', 'mapApi']; 

    function dealMap($timeout, $http, mapApi){ 
     var directive = { 
      link: link, 
      templateUrl: 'app/map/map.directive.html', 
      scope: { 
       deals: '=', 
       branches: '=' 
      }, 
      restrict: 'EA' 
     }; 
     return directive; 

     function link(scope, element, attrs) { 
      var script = document.createElement('script'); 
      script.type = 'text/javascript'; 
      script.async = true; 
      script.defer = true; 
      script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB4RaOArTNm9C7crfutMVc0KkWIoQG-ZE0"; 
      document.body.appendChild(script); 

      $timeout(function(){ 
       scope.initialize(); 

      }, 500); 

      // todo: Do stuff after deals are loaded based on map radius 
      scope.$on('branchesSorted', function(event, data) { 
       console.log('deals loaded'); 
       console.log(data); 
       var points = mapApi.geocode(data); 
       console.log(points); 
      }); 

      scope.initialize = function() { 

       scope.mapOptions = { 

        zoom: 8, 
        center: new google.maps.LatLng(22.649907498685803, 88.36255413913727) 
       }; 
       scope.map = new google.maps.Map(document.getElementById('map'), scope.mapOptions); 

      }; 

      console.log(scope); 
     } 
    } 
})(); 
+0

나는 각도에서 아주 좋은 아니지만, API가 완전히 충전 된 나는 어떤 일 마녀 코드에서 이러한 의미에서 이동 표시되지 않습니다 후 일반적으로 당신은 당신의지도를 초기화해야한다. –

답변

0

은 이 오류는 Google Maps API가 아직로드되지 않았기 때문에 발생합니다.

데이터가로드지고 순간 :

scope.$on('branchesSorted', function(event, data) { 
      console.log('deals loaded'); 
      console.log(data); 
      var points = mapApi.geocode(data); //<--Google Maps API could be still not loaded at that moment 
      console.log(points); 
     }); 
:

$http.get('app/cwitsTestData/branchData.json').then(function(data){ 
     vm.branches = sortBranches(data.data.branches); 
     $scope.$broadcast("branchesSorted", vm.branches); 
}); 

, 그 후 한 번 Geocoder 구글지도 API가 이미 그 순간에로드되었는지 어떤 보장도 없다, 활용 Google지도 라이브러리 이후

은 다음과 같이 귀하의 예제에서 비동기 로드지고 :

var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.async = true; 
script.defer = true; 
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB4RaOArTNm9C7crfutMVc0KkWIoQG-ZE0"; 
document.body.appendChild(script); 

내가 대신 다음과 같은 솔루션을 제안합니다.

.factory('googleMapsApi', function ($rootScope,$window, $q) { 
    return { 
     load: function (key) { 
      var deferred = $q.defer() 

      if ($window.google && $window.google.maps) { 
       deferred.resolve($window.google); 
      } 
      else { 
        var url = 'https://maps.googleapis.com/maps/api/js?callback=googleMapsLoad'; 
        if (key) url += "&key=" + key; 
        var script = document.createElement('script'); 
        script.type = 'text/javascript' 
        script.src = url; 
        $window.googleMapsLoad = function() { 
         deferred.resolve($window.google); 
        } 
        document.body.appendChild(script); 
      } 
      return deferred.promise; 
     }, 
     createMap : function(scope,id,options){ 
      var mapObject = new google.maps.Map(document.getElementById(id), options); 
      scope.$emit('google-maps-loaded',mapObject); 
     }, 
     onMapReady : function(scope, ready){ 
      var handler = $rootScope.$on('google-maps-loaded', function(evnt,data){ return ready(data);}); 
      scope.$on('$destroy', handler); 
     } 
    } 
}) 

그런 다음지도는 지침link 기능을 통해 다음과 같이 작성할 수 있습니다 :

이 준비되면 이제 Google지도 API를로드지도를 만들고 알리기 위해 다음과 같은 서비스를 소개하자

link: function (scope, element, attributes) { 
      googleMapsApi.load(scope.key) 
      .then(function() { 
       var mapOptions = { 
        center: scope.center, 
        zoom: scope.zoom, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
       }; 
       googleMapsApi.createMap(scope,attributes.id,mapOptions); 
      }); 
     } 

데이터 이렇게 제어기에로드된다

,617,
.controller('MyCtrl', function ($scope, googleMapsApi) { 

    googleMapsApi.onMapReady($scope, function(mapInst) { 
     console.log('Google Map is ready'); 
     mapInst.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json'); 
    }); 
}); 

JSFiddle example