3

I'm trying to add a google map in angular JS... and have been struggling. I didn't want to use one of the angular dependencies, but simulate the 'async defer' on the Google JS API site.

I'm pretty new to Angularjs but get the concept of keeping things assigned to the controllers scope. Pretty sure it's just something dumb, but not sure what... any help would be awesome :-)

    (function () {
  'use strict';
  app.controller('travelCtrl', ['$scope', function($scope) {

    $scope.injectScript = function(element) {
        var scriptTag = angular.element(document.createElement('script'));
        scriptTag.attr('charset', 'utf-8');
        scriptTag.attr('src', 'https://maps.googleapis.com/maps/api/js?key=MYKEY');
        element.append(scriptTag);
        return {
          link: function(scope, element) {
            injectScript(element)}}};

    $scope.initMap = function() {
            var uluru = {lat: -25.363, lng: 131.044};
            var map = new google.maps.Map(document.getElementById('kc-map'), {
            zoom: 4,
            center: uluru
          });
        };
    }]);
  })();

HTML

<div ng-controller="travelCtrl" id="kc-map"></div>
5
  • What exactly isn't working ? Map isn't loading ? Commented Oct 13, 2017 at 22:06
  • Map's not loading. No error messages on the page, just doesn't load. Commented Oct 13, 2017 at 22:23
  • Do this: angular.element(element).append(scriptTag); MKEY seems to be invalid api key tho Commented Oct 13, 2017 at 22:30
  • Yeah, I just put that key in as a place holder :-P Commented Oct 13, 2017 at 22:48
  • Also... still not working Commented Oct 14, 2017 at 5:17

1 Answer 1

3

Figured it out...

  app.controller('travelCtrl', ['$scope', function($scope) {
    $scope.initialize = function() {
         $scope.mapOptions = {
             zoom: 8,
             center: new google.maps.LatLng(22.649907498685803, 88.36255413913727)
         };
         $scope.map = new google.maps.Map(document.getElementById('kc-map'), $scope.mapOptions);
     }

     $scope.loadScript = function() {
         var script = document.createElement('script');
         script.type = 'text/javascript';
         script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyD-5e8hV-uCuE1pEgTyMhk_gJJPK2f3F5A&callback=initialize';
         document.body.appendChild(script);
         setTimeout(function() {
             $scope.initialize();
         }, 500);
     }
    }]);

Add this to outer div.

ng-init="loadScript()"

Answer thanks to this post

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.