0

I want to display map in my angularJS page like below.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="js/angular.min.js"></script>
</head>
<body ng-app="abc">
<div id="controller" ng-controller="def as ctrl">
    <div id="googlemap" style="height:100%; width:100%"></div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/scripts.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=displayMap"></script>
</body>
</html>

And my scripts.js file is as follows.

var mainApp = angular.module('abc',[]);
mainApp.controller('def', function($scope,$http) {

    this.displayMap=function() {
            var mapOptions = {
                zoom: 4,
                center: new google.maps.LatLng(40.0000, -98.0000),
                mapTypeId: google.maps.MapTypeId.TERRAIN
            }

            $scope.googlemap = new google.maps.Map(document.getElementById('googlemap'), mapOptions);
        }

}

I am getting displayMap is not a function InvalidValueError message. How can it be resolved?

1 Answer 1

1

displayMap function passed via callback parameter is expected to be visible from the global scope but in the provided example it is only accessible in the scope of def controller.

In Angular app instead of invoking displayMap function via callback parameter you could invoke it from the contoller like this:

google.maps.event.addDomListener(window, 'load', displayMap);

Example

angular.module('mapApp', [])

    .controller("mapCtrl", function ($scope, $http) {
       
        var displayMap = function (data) {
            var mapOptions = {
                zoom: 4,
                center: new google.maps.LatLng(48.209500, 16.370691),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map_div"), mapOptions);
        };

        google.maps.event.addDomListener(window, 'load', displayMap);

    });
#map_div {
        height: 280px;
      }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<script src="app.js"></script>


<div ng-app="mapApp" ng-controller="mapCtrl">
    <div id="map_div" ></div>
</div>

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.