1

How is it possible to use the Google Maps API with AngularJS?

I am using this code in my AngularJS app:

<style>
  #googleMap {
    width: 200px;
    height: 200px;
  }
</style>

<div id="googleMap"></div>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>

<script language="javascript">

  var map;

  function initialize() {

    var mapOptions = {
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoom: 8,
      center: new google.maps.LatLng(-34.397, 150.644)
    };

    map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
  }

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

</script>

This code is in the view and not in the controller.

I have other functions in the view and they work, but google map is still not working.

This is the error I get in the browser console:

Error: google is not defined @http://localhost:3000/js/jquery-1.11.2.min.js line 2 > eval:10:2 .globalEval/<@http://localhost:3000/js/jquery-1.11.2.min.js:2:2615 .globalEval@http://localhost:3000/js/jquery-1.11.2.min.js:2:2589 .domManip@http://localhost:3000/js/jquery-1.11.2.min.js:3:23105 .after@http://localhost:3000/js/jquery-1.11.2.min.js:3:21067 Cehttp://localhost:3000/js/angular/lib/angular.min.js:176:70 n@http://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:5868 .compile/http://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:6428 Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:128:120 p@http://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:2649 this.$gethttp://localhost:3000/js/angular/lib/angular-route-segment.min.js:7:3989 f/<@http://localhost:3000/js/angular/lib/angular.min.js:112:20 Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:125:301 Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:122:390 Pe/this.$gethttp://localhost:3000/js/angular/lib/angular.min.js:126:56 l@http://localhost:3000/js/angular/lib/angular.min.js:81:169 S@http://localhost:3000/js/angular/lib/angular.min.js:85:301 vf/http://localhost:3000/js/angular/lib/angular.min.js:86:315

What am I doing wrong?

I searched the web but everyone seems to be using libraries like angular-google-map or ui-map. Why is no one using the direct API?

5
  • Are you including the Google Map javascript in the head of the page? <script type="text/javascript" src="maps.googleapis.com/maps/api/js"></script> Commented May 19, 2015 at 20:50
  • No in the partial. But I have tried writing in head too. But not working. Nothing is showing. The div container is visible but no map is there in the div. @UsainBloot Commented May 19, 2015 at 20:52
  • Is it possible to have anymore of your code, perhaps in plunklr? As the error states that the var google has not been defined, which usually means that Google's Map JavaScript is not being loading correctly (or at the correct time) Commented May 19, 2015 at 20:55
  • Now again I restarted the server and now the top most line of the error is this. "Error: invalid property id. Sorry but not possible to post the total code. Its huge. I can try to regenerate it for a smaller one. Commented May 19, 2015 at 20:58
  • Is it possible that when angular reads the script then the map is not available?? Because the map js is a link so may be at that time it was not downloaded. I searched in web but everyone is using any library like angular-google-map, ui-map etc. But why not the direct one is not written anywhere Commented May 19, 2015 at 21:00

2 Answers 2

6

You can implement google maps in angularjs without using any plugins like this,

<!--use this div  where ever you want to create a map-->
     <div id="map"></div>

define the width and height for map div,

#map {
 height:420px;
 width:600px;
}

in controller you glue this id="map" with scope like this,

$scope.mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(41.923, 12.513),
    mapTypeId: google.maps.MapTypeId.TERRAIN
}

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

if you want to create markers for the cities or countries you want,

 var cities = "Atlanta, USA";
 var geocoder= new google.maps.Geocoder();

 $scope.markers = [];

 var createMarker = function (info){
    var marker = new google.maps.Marker({
        map: $scope.map,
        position: new google.maps.LatLng(info.lat(), info.lng())
    });
 }

geocoder.geocode( { 'address': cities }, function(results, status) {
 if (status == google.maps.GeocoderStatus.OK) {
    newAddress = results[0].geometry.location;
    $scope.map.setCenter(newAddress);
    createMarker(newAddress)
 }
});

Last but not least make sure you added the google maps api script before doing all this stuff,

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"> </script>

Here is the working plunker with this code, inside a bootstrap model,

http://embed.plnkr.co/VT7cO0L2ckSWG6g63TVG/preview

Reference

Hope this helps!

Sign up to request clarification or add additional context in comments.

7 Comments

Yes its working. Its same like what I did. I wrote it in view and you wrote the same code in controller and that made it working. I want to know why its not working in view directly? I have used many javascript functions and script directly in view & they works. Why not google map??
have you added the google api scripts before your own script tag for using it.
Yes I have added google api script at the head. Then at the partial I created new google.maps. But at that moment I was writing all those in a function called initialize. Then I was calling google.maps.event.addDomListener(window, 'load', initialize); & this function is not triggering. If I write those codes direct in a script without any initialize function or addDomListener then its working. I did this after watching your answer
yes but can you tell me the answer of my comment which I did previous of this comment.
you are adding an event to google maps, even before it gets defined. so only your function initialize is not getting triggered and map is not shown.
|
0

It was late to post but I have done this as solution. By this there is no need to add the google map script src in the head of the html or there is no chance of any error for google map src related errors. The script will be added automatically by the loadScript function. In angular it is needed to add new js src in partials rather than the head of main script. So I think this will be the best solution

I used this code chunk into my controller.

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

    $scope.loadScript = function() {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://maps.google.com/maps/api/js?sensor=false&callback=initialize';
        document.body.appendChild(script);
        setTimeout(function() {
            $scope.initialize();
        }, 500);
    }

setTimeout is there because some time is needed for google map src to be downloaded and be ready. & callback=initialize is needed because by this google map will be ready for a callback.The main problem was that the code google.maps.event.addDomListener(window, 'load', initialize) was not executing if I add the google map src in partial rather than the head of main index.html. But this setup works flawlessly.

And this chunk to the html

<div class="form-group col-lg-12" id="googleMap">
      <center>Waiting for the map...</center>
</div>

Now place ng-init="loadScript()" anywhere in any outer div so that loadScript initializes before.

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.