Initialize Google Map in AngularJS

后端 未结 4 1144
一个人的身影
一个人的身影 2020-12-07 19:17

I am considering migrating from backbonejs to angularjs.

In backbone I am able to initialize a view at which point I create an instance of google map. I can then pa

相关标签:
4条回答
  • 2020-12-07 19:35

    Here's my solution for using the maps api with Angularjs routeProvider: in your index you have to add:

    angular-google-maps.min.js and lodash.min.js

    in application.js:

    (function() {
    
    var app = angular.module("myApp", ["ngRoute", "uiGmapgoogle-maps"]);
    
    
    app.config(function(uiGmapGoogleMapApiProvider) {
        uiGmapGoogleMapApiProvider.configure({
            key: 'YOUR KEY HERE',
            v: '3.17',
            libraries: 'weather,geometry,visualization'
        });
    });
    
    app.config(function($routeProvider) {
        $routeProvider
            .when("/home", {
                templateUrl: "home.html",
                controller: "HomeController"
            })
            .when("/workwith", {
                templateUrl: "workwith.html",
                controller: "WorkwithController"
            })
    
    
    
    
        .otherwise({
            redirectTo: "/home"
        });
    
    });
    

    })();

    Last But not least in your controller:

    (function() {
    var app = angular.module("myApp");
    var MyController = function($scope, $http, $log, $location, $routeParams, uiGmapGoogleMapApi) {
        $log.info("MyController");
        $log.info($routeParams);
    
        // Define variables for our Map object
        var areaLat = 44.2126995,
            areaLng = -100.2471641,
            areaZoom = 3;
    
        uiGmapGoogleMapApi.then(function(maps) {
            $scope.map = {
                center: {
                    latitude: areaLat,
                    longitude: areaLng
                },
                zoom: areaZoom
            };
            $scope.options = {
                scrollwheel: false
            };
        });    
     };
    app.controller("MyController", MyController);
    

    })();

    0 讨论(0)
  • 2020-12-07 19:38

    Hi Larry Eitel and everyone, I have the following approach:

    First, we need to create some global variables:

    var mapGlobal, flag=0, CurrentmapNode;
    

    Then in Controller:

        function MapCtrl($scope) {
        var lat = 46.87916;
        var lng = -3.32910;
        var map_id = '#map';
    
         if (flag==0)
           initMap(mapId, lat, lng);
         else
           reinitMap(mapId);
    
      function initMap(map_id, lat, lng) {
        var myOptions = {
          zoom : 8,
          center : new google.maps.LatLng(lat, lng),
          mapTypeId : google.maps.MapTypeId.ROADMAP
        };
        mapGlobal = new google.maps.Map($(map_id)[0], myOptions);
    
        if (typeof mapGlobal != 'undefined')
           flag=1;
      }
    
      function reinitMap(mapId){
         $(mapId)[0].append(CurrentmapNode);
       }
    
       $scope.$on("$destroy", function(){
            CurrentmapNode = mapGlobal.getDiv(); //save current map in an auxiliar variable
       });
    
    }
    

    The "on destroy" function saves current map state in another global variable, then, when view is recreated, we don't need to create another map instance.

    Creating another map instance can cause memory leak and increase Google maps API usage each time view is recreated.

    Best regards

    0 讨论(0)
  • 2020-12-07 19:52

    Since views create and destroy controllers when the view changes, you want your maps data to persist somewhere else. Try creating a GoogleMap service which will store the data.

    myApp.factory('GoogleMaps', function() {
      var maps = {};
    
      function addMap(mapId) {
        maps[mapId] = {};
      }
      function getMap(mapId) {
        if (!maps[mapId]) addMap(mapId);
        return maps[mapId];
      }
    
      return {
        addMap: addMap,
        getMap: getMap
      }
    });
    
    function MyController($scope, GoogleMaps) {
      //Each time the view is switched to this, retrieve supermanMap
      $scope.map = GoogleMaps.getMap('supermanMap');
    
      $scope.editMap = function() {
        $scope.map.kryptonite = true;
      };
    }
    

    If you don't like this solution, there are some other ways to do it too.

    0 讨论(0)
  • 2020-12-07 19:54

    This is what I am doing in Backbone to keep the view instead of destroying it. Suppose you have a div with id="container" and your router have the corresponding routes.

    routes: {
        "":"home",
        "map": "showMap"
    },
    
    showMap: function() {
        $("#container").children().detach();
        if(!this.mapView) {
            this.mapView = new MapView(); 
            this.mapView.render();
        }
        $("#container").html(this.mapView.el);
    }
    
    0 讨论(0)
提交回复
热议问题