qopuir
qopuir

Reputation: 369

AngularUI - Google Maps - map is undefined

I am trying to use GoogleMaps directive this way:

Controller Methods

$scope.myMarkers = [];

$scope.mapOptions = {
    center : new google.maps.LatLng(35.784, -78.670),
    zoom : 15,
    mapTypeId : google.maps.MapTypeId.ROADMAP
};

$scope.addMarker = function($event) {
    $scope.myMarkers.push(new google.maps.Marker({
        map : $scope.myMap,
        position : $event.latLng
    }));
};

UpdateLocation.html

<div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]" ui-event="{'map-click': 'openMarkerInfo(marker)'}"></div>

<div id="map_canvas" ui-map="myMap" class="map" ui-event="{'map-click': 'addMarker($event)'}" ui-options="mapOptions"></div>

The map is shown perfectly but in method addMarker I am getting an undefined when $scope.myMap is executed.

Upvotes: 3

Views: 1871

Answers (1)

bmleite
bmleite

Reputation: 26880

I believe you have a new scope being created somewhere between your controller definition and the ui-map div and what's happening is that the 'myMap' property is being created on that scope and not on your controller's scope.

To avoid this kind of problems, provide the ui-map directive a proper model. For example:

Controller:

$scope.model = { myMap: undefined };

HTML:

<div id="map_canvas" ui-map="model.myMap" class="map" ui-event="{'map-click': 'addMarker($event)'}" ui-options="mapOptions"></div>

This will force the ui-map directive to store the map content inside $scope.model.myMap and due to the prototypically inheritance of the scopes, the $scope.model object will be available on child scopes but will always belong to the parent scope - your controller's scope.

Upvotes: 3

Related Questions