source

구글 지도를 앵귤러로 초기화하다JS

itover 2023. 2. 15. 21:51
반응형

구글 지도를 앵귤러로 초기화하다JS

backbonejs에서 angularjs로의 이행을 검토하고 있습니다.

backbone에서는 뷰를 초기화할 수 있습니다.이 시점에서 구글 맵의 인스턴스를 만듭니다.그러면 지도의 현재 상태를 잃지 않고 화면을 이동/확대/축소할 수 있습니다.

angularjs를 사용하여 다음을 지정합니다.

layout.displaces(레이아웃).

<body>
  <div class="container-fluid" ng-view></div>

map.syslog

<div id="map_canvas" ng-controller="MapCtrl"></div>

나는 지도를 잘 그려내라는 지시를 내릴 수 있었다.문제는 맵 뷰로 돌아갈 때마다 맵이 새로고침된다는 것입니다.

<map></map>

그래서 Angular에 대해 배운 바로는 MapController를 만들고 거기서 지도를 초기화해야겠다고 생각했습니다.성공하지 못했습니다.

결론은 구글 맵을 비동기화하고 로컬 또는 리모트로 데이터를 푸시하여 매번 맵을 처음부터 다시 로드하지 않고 앱을 탐색할 수 있어야 한다는 것입니다.

누가 올바른 접근방식을 제안할 수 있습니까?

감사합니다:)

Andy Joslin의 제안에 따라 시행:

app.js:

// Generated by CoffeeScript 1.3.3
(function() {
  "use strict";

  angular.module("ofm", ["ofm.filters", "GoogleMaps", "ofm.directives"]).config([
    "$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
      $routeProvider.when("/", {
        templateUrl: "partials/home"
      }).when("/map", {
        templateUrl: "partials/map",
        controller: MapCtrl
      }).otherwise({
        redirectTo: "/"
      });
      return $locationProvider.html5Mode(true);
    }
  ]);

}).call(this);

서비스 중js:

angular.module('GoogleMaps', []).
  factory('wasMapInitialized', function() {
    console.log("inside service");
    var maps = 0;

    if (!maps) {
      maps += 1;
      return 0;
    } else {
      return 1;
    }
  });

in controllers.js:

function MapCtrl($scope) {
  if (!GoogleMaps.wasMapInitialized()) {
    var lat = 46.87916;
    var lng = -3.32910;
    var map_id = '#map';
    initialize(map_id, lat, lng);
  }
  function initialize(map_id, lat, lng) {
    var myOptions = {
      zoom : 8,
      center : new google.maps.LatLng(lat, lng),
      mapTypeId : google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map($(map_id)[0], myOptions);
  }
}

map.html의 경우

#map
<div ng-controller="MapCtrl"></div>

오류: 알 수 없는 공급자:Google Maps Provider <- Google Maps

뷰가 변경되면 뷰가 컨트롤러를 생성 및 파기하므로 맵 데이터를 다른 곳에 보관해야 합니다.데이터를 저장할 GoogleMap 서비스를 만들어 보십시오.

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;
  };
}

이 솔루션이 마음에 들지 않으면 다른 방법도 있습니다.

이것이 내가 백본에서 하고 있는 일이다.백본은 파괴하지 않고 시야를 유지하기 위해서다.id="div"를 가진 div가 있고 라우터에 대응하는 경로가 있다고 가정합니다.

routes: {
    "":"home",
    "map": "showMap"
},

showMap: function() {
    $("#container").children().detach();
    if(!this.mapView) {
        this.mapView = new MapView(); 
        this.mapView.render();
    }
    $("#container").html(this.mapView.el);
}

Angularjs routeProvider에서 맵 API를 사용하기 위한 솔루션을 다음에 나타냅니다.인덱스에 추가해야 합니다.

angular-google-min.min.display 및 lodash.min.display를 지정합니다.

응용 프로그램 중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"
    });

});

})();

마지막 컨트롤러:

(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);

})();

안녕하세요, Larry Eitel 씨, 그리고 여러분, 저는 다음과 같은 접근방식을 가지고 있습니다.

먼저 몇 가지 글로벌 변수를 작성해야 합니다.

var mapGlobal, flag=0, CurrentmapNode;

그럼 인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
   });

}

"on destroy" 함수는 현재 맵 상태를 다른 글로벌 변수에 저장합니다.이 경우 뷰가 다시 생성될 때 다른 맵인스턴스를 생성할 필요가 없습니다.

다른 맵 인스턴스를 생성하면 메모리 누수가 발생하여 뷰가 다시 생성될 때마다 Google 맵 API 사용량이 증가할 수 있습니다.

안부 전합니다

언급URL : https://stackoverflow.com/questions/11180750/initialize-google-map-in-angularjs

반응형