Using Google maps with AngularJS and Angular UI

You can use AngularUI to integrate Google Maps in your angularjs app. The following code snippet shows a simple example of Google maps with Angular UI.

To hookup the events with map elements such as marker, polyline, you need to create html div elements with existing Google maps objects. It is a bit confusing part, but it helps to keep your controller free from adding listener codes.

//Add the requried module 'angular-ui' as a dependency
angular.module('maptesting', ['ui']);

function MapCtrl($scope) {
    var ll = new google.maps.LatLng(13.0810, 80.2740);
    $scope.mapOptions = {
        center: ll,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    //Markers should be added after map is loaded
    $scope.onMapIdle = function() {
        if ($scope.myMarkers === undefined){
            var marker = new google.maps.Marker({
                map: $scope.myMap,
                position: ll
            });
            $scope.myMarkers = [marker, ];
        }
    };

    $scope.markerClicked = function(m) {
        window.alert("clicked");
    };

}​

<div ng-app='maptesting'>
    <div ng-controller="MapCtrl">
        <div id="map_canvas" ui-map="myMap" 
      style="height:300px;width:400px;border:2px solid #777777;margin:3px; border:1px solid" 
      ui-options="mapOptions" 
      ui-event="{'map-idle' : 'onMapIdle()'}"
      >
        </div>

        <!--In addition to creating the markers on the map, 
       div elements with existing google.maps.Marker object 
        should be created to hook up with events -->
        <div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"
                      ui-event="{'map-click': 'markerClicked(marker)'}">
        </div>
    </div>
</div>

JS Fiddle

http://jsfiddle.net/ramandv/xSPAA/

This entry was posted in AngularJS, Javascript. Bookmark the permalink.

18 Responses to Using Google maps with AngularJS and Angular UI

  1. Pingback: Google Maps does not fill with angularjs | CodersDiscuss.com

Leave a Reply

Your email address will not be published. Required fields are marked *