How do I add google map in angular.js controller?

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

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?

回答1:

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>


回答2:

You have to read this documentation and use simple googlemap angularjs directive.

I hope this works for you

All The best



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