Angular Js and google api client.js (gapi)

后端 未结 8 1523
不思量自难忘°
不思量自难忘° 2020-11-29 00:46

It took me one day to make it works so I think my experience may be useful from someone. And maybe some others will find improvement.

So I start angularJS two days a

8条回答
  •  猫巷女王i
    2020-11-29 01:16

    I wrote a simple directive to load the google map API asynchronously :

    // js/directives/gmapAsync.js
    
    (function(){
    'use strict';
    
    angular.module('app').directive('gmapAsync',
        ['$window', '$rootScope', gmapAsync]
    );
    
    function gmapAsync($window, $rootScope){
    
        var gmapScript = $window.document.createElement('script');  
    
        $window.onGmapScriptLoaded = function(){
            console.log('google maps script loaded');
    
            $rootScope.gmapApiLoaded = true;
            $rootScope.$broadcast('gmap.api.loaded');
    
        };
    
        return {
            restrict: 'A',
            transclude: false,
            scope:false,
            link:   function(scope, element, attributes){
    
                if (navigator.onLine) {
                    appendScript();
                } else {
                    $window.addEventListener('online',appendScript);
                }
    
                function appendScript(){
                    gmapScript.type = 'text/javascript';
                    gmapScript.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'callback=onGmapScriptLoaded';
                    $window.document.body.appendChild(gmapScript);
                }
            }
        };
    }
    })();
    

    Then in your main controller, you can handle the event :

    // js/controllers/AppCtrl.js
    
    (function(){
    'use strict';
    
        angular.module('app').controller('AppCtrl',[$scope,AppCtrl])
    
        function AppCtrl($scope){
    
            $scope.$on('gmap.api.loaded',function(){
                // your stuff to init after the api is loaded
            });
        }
    
    })();
    

    You just have to declare the directive in your body tag :

    
    
    
        
    
        
    
            
    
            
            
            
        
    
    
    

提交回复
热议问题