Search code examples
angularjsgoogle-mapsgoogle-maps-api-3ng-map

ng-map: How can I get the Marker object when I click it?


I am using the pretty cool ng-map library for angular, and I want to know how to access the underlying Marker Object referenced by ng-map marker directive

So, I have this markup:

<div id="map-search" data-tap-disabled="true">
  <map zoom="15" disable-default-u-i="true">
    <marker ng-repeat=" pos in positions" position="{{pos.latitude}}, {{pos.longitude}}" id="{{pos.index}}" on-click="pinClicked()">
    </marker>
  </map>
</div>

I haven't found a straight-forward way of accessing the Google Maps Marker Object during a on-click event in this case; From the controller:

  app.controller('MapSearchController', function($scope) {

      $scope.$on('mapInitialized', function(event, map) {
        $scope.map = map;
        //Assume existence of an Array of markers
        $scope.positions = generatePinPositionsArray();
      });

      $scope.pinClicked = function(event, marker) {
        console.log('clicked pin!');
        //HOW CAN I GET THE MARKER OBJECT (The one that was clicked) HERE?
        console.log('the marker ->', marker); //prints undefined
      };
  });

Thanks in advance,


Solution

  • You need to create an array of markers ! That's (in my opinion) the only way. See here

    UPDATE: Does something like this plunkr works for you?

    The idea is to pass the marker on the event on-click="pinClicked(this)". And then you can catch it later on the controller: $scope.pinClicked = function(events, marker) {...}