Search code examples
javascriptgoogle-mapsgoogle-maps-api-3postgis

how to register click listener on drawing manager icons panel in google map?


i have successfully used google map drawing manger. Now i am facing one problem. in the image two shapes poly-line and polygon are shown. i want to show simply an alert when these icons are clicked that is when polygon is clicked show a message 'polygon is clicked' and when line is clicked it show a message 'polyline is clicked'.icons image is here


Solution

  • If you want to know when the drawing mode of the DrawingManager changes (clicking the buttons is one way of doing that), add a listener to the DrawingManager for the "drawingmode_changed" event:

    google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
      console.log("drawing mode changed:"+drawingManager.getDrawingMode());
    })
    

    proof of concept fiddle

    code snippet:

    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {
          lat: -34.397,
          lng: 150.644
        },
        zoom: 8
      });
    
      var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
          position: google.maps.ControlPosition.TOP_CENTER,
          drawingModes: ['marker', 'circle', 'polygon', 'polyline', 'rectangle']
        },
        markerOptions: {
          icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
        },
        circleOptions: {
          fillColor: '#ffff00',
          fillOpacity: 1,
          strokeWeight: 5,
          clickable: false,
          editable: true,
          zIndex: 1
        }
      });
      google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
        console.log("drawing mode changed:" + drawingManager.getDrawingMode());
      })
      drawingManager.setMap(map);
    }
    #map {
      height: 100%;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" async defer></script>