如何在angular.js控制器中添加谷歌地图? [英] How do I add google map in angular.js controller?

查看:78
本文介绍了如何在angular.js控制器中添加谷歌地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我对角度相当陌生,并且很难实施Google地图API。我不断收到错误:

 未捕获InvalidValueError:初始化不是函数。 

我对脚本标记有这样的看法:

 < script src =https://maps.googleapis.com/maps/api/js?key=MY API KEY GOES HERE& callback = initialize
async推迟>< /脚本>

但是由于我的函数initialize()在我的控制器中,所以它不能识别它。如果我把这个功能放在控制器之外,它确实可以识别它。但是因为我拥有控制器中定义的所有数据,所以我需要它。我甚至不知道我应该问什么,但我只需要让地图显示出来。任何想法?

解决方案

您可以考虑像下面演示的那样同步加载Google Maps API



 

html,body {height:100%;保证金:0; padding:0;}#map_div {height:480px;}

< script src =https://code.angularjs.org/1.3.15/angular.js>< / script> < script src =https://maps.googleapis.com/maps/api/js>< / script> < div ng-app =myAppng-controller =MyCtrl> < div id =map_div>< / div> < / div>


So, I'm fairly new to angular and having hard time implementing google map API. I keep getting error:

Uncaught InvalidValueError: initialize is not a function.

I have this for the script tag:

<script src="https://maps.googleapis.com/maps/api/js?key=MY API KEY GOES HERE&callback=initialize"
    async defer></script>

But since my function initialize() is inside my controller, it doesn't recognize it. If I put the function outside of the controller, it does recognize it. But since I have all the data defined within the controller, I need this inside it. I'm not even sure what I'm supposed to ask but I just need to get the map to show up. Any ideas?

解决方案

You could consider to load Google Maps API synchronously as demonstrated below

angular.module('myApp', [])
    .controller('MyCtrl', function($scope) {
      
       $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);   

    });

html, body {
        height: 100%;
        margin: 0;
        padding: 0;
}
#map_div {
        height: 480px;
}

 <script src="https://code.angularjs.org/1.3.15/angular.js"></script>
 <script src="https://maps.googleapis.com/maps/api/js" ></script>
 <div ng-app="myApp" ng-controller="MyCtrl">
   <div id="map_div"></div>
 </div>

这篇关于如何在angular.js控制器中添加谷歌地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆