How to initialize google maps API in angular without using any directives?

独自空忆成欢 提交于 2019-12-12 03:09:50

问题


I am trying to initalize google maps in the application I am writing, I am using the places api for some of the functionalities which is working fine, Now I am trying to show a map on a page but the map never shows up. i do not get any error on the console when I use the following code.

index.html

<script src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places"></script>

mapview.html

<div ng-controller="MapViewController as mapctrl" ng-init="initialize()">
<div class="container">

  <div class="row">



<div id="map"></div>

</div>

<div ui-view></div>
</div>
</div>

mapViewController.js

(function(angular) {
    angular.module('myapp').controller('MapViewController', ['$state','$http','$stateParams','$window','$route','$document','$localStorage','$scope','$location', function($state,$http,$stateParams,$window,$route,$document,$localStorage,$scope,$location) {

      $scope.initialize = function(){
        console.log("log");
          var mapOptions = {
              zoom: 11,
              center: {lat: -34.397, lng: 150.644},
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };

          var map = new google.maps.Map(document.getElementById('map'), mapOptions);
       };

      }]);
      })(angular)

I get the log message when the contoller is initialized but the map doesn't show on the page. I would like to know how can I make it possible without using any directive.


回答1:


Make sure to define ng-app on your html:

<html ng-app="mapApp">
 . . .
  <body ng-controller="MapController" ng-init="initMap()">
    <div id="map"></div>
  </body>
</html>

Then to initialize correctly your map on JS:

angular.module('mapApp', []);

angular
  .module('mapApp')
  .controller('MapController', MapController);

  function MapController($scope){

    $scope.initMap = function() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 3,
            center: new google.maps.LatLng(32.483, 16.084)
        });
    }

}

And give height and width to your id:

#map{
      height: 400px;
      width:  700px;
      border: 2px solid red;
 }

here you can find A Plunker I made which initializes a map without a directive.

Hope I've been helpful.



来源:https://stackoverflow.com/questions/39469001/how-to-initialize-google-maps-api-in-angular-without-using-any-directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!