-->

(angularjs-google-maps) ng-click inside marker

2019-07-06 20:04发布

问题:

This question is about angularjs-google-maps, https://github.com/allenhwkim/angularjs-google-maps

Is there a way to use ng-click on a marker to set a variable like this? (the value of 1 is hard-coded for testing purposes). Clicking the marker currently does not seem to trigger the ng-click.

<marker ng-repeat="instance in common.instances" 
 position="[{{instance.lat}},{{instance.lng}}]" 
 ng-click="common.selectedinstance = 1">
</marker>

回答1:

From their document, https://developers.google.com/maps/documentation/javascript/events,

User events (such as "click" mouse events) are propagated from the DOM to the Google Maps API. These events are separate and distinct from standard DOM events.

As far as I understand, only google maps event can be applied to google maps objects including markers, shapes, etc.

That was the bad news.

Good news is you still can use on-click event to manipulate $scope variables and events. There is not much difference as long as you use a function for this event.

I will keep investigating if there is work-around, so that we can use AngularJS Event into(i.e. ngMouseenger, ngMouseleave. ngMouseup, ngClick, etc

A working example using on-click is at plunkr to satisfy your requirement.

http://plnkr.co/edit/6qvS0vUYkqVHZ3t6qmn2?p=preview

This is script part

  $scope.myVar = 1;
  $scope.changeMyVar = function(event) {
    $scope.myVar+=1;
    $scope.$apply();
  }

This is html part

  <map zoom="11" center="[40.74, -74.18]">
    <marker ng-repeat="p in positions" 
      position="{{p}}" title="{{p.toString()}}"
      on-click="changeMyVar()">
    </marker>
  </map>
  myVar : {{myVar}}  Click a marker to increase myVar

To know more about angularjs-google-maps events, please take a look at the example about event



回答2:

I used below code to get Latitude and Longitude of clicked marker.

Html:

   <ng-map zoom="12" center="{{vm.geoCenterLoc}}" style="height:500px">
            <marker ng-repeat="p in vm.positions"
                    position="{{p.pos}}"
                    data="{{data[$index]}}"
                    on-click="myFunc($event)";
                    title="pos: {{p.pos}}"></marker>
   </ng-map>

Javascript(on my controller):

 $scope.myFunc = function (evt) {

            markerPosObj = {
                pos: [this.getPosition().lat(), this.getPosition().lng()]
            };
            markerPos = [];
            markerPos.push(markerPosObj);
            console.log('this marker', markerPos);
        }