1

I'm trying to initialize the google maps init function from a function, the working of function is to add a new div tag which will contain a map. I tried code written in commented area below inside a function but it's not working but its working outside the function.

app.controller('controller1', function($scope, $http, $window) {

$scope.addMapPanel = function() {

    var ref_div = angular.element(document.querySelector('#ref_div'));

    var map_div = angular.element(document.querySelector('#map_div'));

    if(map_div.length){
        console.log('exist');
    }else{
        console.log('doesnot');
        ref_div.append('<div class="col-md-6" id="map_div"></div>');
    }

    /*$scope.initialize = function() {
      var map = new google.maps.Map(document.getElementById('map_div'), {
         center: {lat: -34.397, lng: 150.644},
         zoom: 8
      });
   }

    google.maps.event.addDomListener(window, 'load', $scope.initialize);*/

  };
});

similar type answer : How do I add google map in angular.js controller?

1 Answer 1

0

You still need to have the DomListener call some function once that library has been loaded. From there, just check to see if the div exists. If not, you need to append it and then initialize a map onto that div.

However, I would recommend using directives for DOM interaction, as that is where View logic should exist in the MVC architecture. Plus, it allows reuse.

angular.module('app', []).
controller('mapController', function($scope) {
    $scope.initialize = function () {
      
      var ref_div = angular.element(document.querySelector('#ref_div'));

      var map_div = angular.element(document.querySelector('#map_div'));

      if(map_div.length){
        var map = new google.maps.Map(document.getElementById('map_div'), {
           center: {lat: -34.397, lng: 150.644},
           zoom: 8
        });
      }else{
          ref_div.append('<div class="col-md-6" id="map_div"></div>');
          var map = new google.maps.Map(document.getElementById('map_div'), {
           center: {lat: -34.397, lng: 150.644},
           zoom: 8
        });
      }
    };

    google.maps.event.addDomListener(window, 'load', $scope.initialize);

});
#map_div {
   width: 150px;
   height:  150px;
 }
<div id="ref_div" ng-app="app" ng-controller="mapController">
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js">
</script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.