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

Usin addListener on Polygon to delete vertex with AngularJs NgMap


I'm trying to delete a single vertex on the polygon drawn on the map using AngularJs NgMap, but nothing happens. I know I need to bind a rightClick event on the polygon, but nothing is happening.

I know there is a guide on how to delete the vertex here, but I'm not able to fire the event to proced.

Here is my code so far:

html:

<ng-map center="[{{vm.googleMaps}}]" zoom="13" map-type-control="false" street-view-control="false">
    <marker position="[{{vm.googleMaps}}]"></marker>

    <shape name="polygon" paths="{{vm.paths}}" editable="true"
        stroke-color="#cde"
        stroke-opacity="0.8"
        stroke-weight="2"
        fill-color="#cde"
        fill-opacity="0.4">
    </shape>
</ng-map>

controller:

$scope.$on('mapInitialized', function(event, map) {
    var polygon = new google.maps.Polygon({
        paths: vm.polygonPath
    });

    google.maps.event.addListener(polygon, 'rightclick', function() {
        console.log('RightClick')
    });
});

When I left click on the Polygon vertex, nothing happens, but I'm able to fully edit the polygon.

What am I doing wrong?


Solution

  • In order to have the proper event without using mapInitialized, I had to set a custom listener inside the ng-map directive and pass the event from there as well.

    After that, I was able to use the googleMaps functions without using google.maps.event.addListener.

    This is the final code:

    html

    <ng-map center="[{{vm.googleMaps}}]" zoom="13" map-type-control="false" street-view-control="false">
        <marker position="[{{vm.googleMaps}}]"></marker>
    
        <shape name="polygon" paths="{{vm.paths}}" editable="true"
            on-rightclick="vm.myFunction($event)" //This is where we get the event with the point reference
            stroke-color="#cde"
            stroke-opacity="0.8"
            stroke-weight="2"
            fill-color="#cde"
            fill-opacity="0.4">
        </shape>
    </ng-map>
    

    AngularJs

    I don't need to use the code I used on the question, so we can remove it.

    vm.myFunction = function(event) {
        NgMap.getMap().then(function(evtMap) {
            var path = evtMap.shapes[0].getPath();
            return path.removeAt(event.vertex);
        });
    }
    

    The only difference from the GoogleMaps example, is that this way is going to remove the point right away, without the little box.