简体   繁体   English

如何在不使用任何指令的情况下以角度初始化Google Maps API?

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

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. 我正在尝试在正在编写的应用程序中初始化google maps,我正在使用places api来正常工作的某些功能,现在我试图在页面上显示地图,但该地图从未显示。 i do not get any error on the console when I use the following code. 使用以下代码时,控制台上没有任何错误。

index.html index.html

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

mapview.html 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 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. 初始化Contoller时,我收到日志消息,但该地图未显示在页面上。 I would like to know how can I make it possible without using any directive. 我想知道如何在不使用任何指令的情况下使其成为可能。

Make sure to define ng-app on your html: 确保在html上定义ng-app

<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: 然后在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: 并给你的身份证的heightwidth

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

here you can find A Plunker I made which initializes a map without a directive. 在这里,您可以找到我制作的Plunker,它无需指令即可初始化地图。

Hope I've been helpful. 希望我有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM