如何在Google Maps API中触发开始多边形绘图?

时间:2017-02-16 15:45:48

标签: google-maps-api-3

我想开始使用不同的按钮而不是绘图管理器控件在地图上绘制多边形。

是否可以触发一个与按下绘图管理器多边形控件一样的事件?

1 个答案:

答案 0 :(得分:3)

使用其他控件开始绘制多边形:

  1. 删除现有的绘图控件:
  2. drawingControl: false,
    
    1. 添加您自己的按钮:
    2. <input id="polygonbtn" type="button" value="Draw Polygon"/>
      
      1. 单击时设置绘图模式:
      2. google.maps.event.addDomListener(document.getElementById('polygonbtn'), 'click', function() {
          drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
        });
        

        proof of concept fiddle

        代码段

        &#13;
        &#13;
        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({
            drawingControl: false,
          });
          drawingManager.setMap(map);
          google.maps.event.addDomListener(document.getElementById('polygonbtn'), 'click', function() {
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
          });
          google.maps.event.addDomListener(document.getElementById('cancelbtn'), 'click', function() {
            drawingManager.setDrawingMode(null);
          });
        }
        &#13;
        /* Always set the map height explicitly to define the size of the div
         * element that contains the map. */
        
        #map {
          height: 100%;
        }
        
        
        /* Optional: Makes the sample page fill the window. */
        
        html,
        body {
          height: 100%;
          margin: 0;
          padding: 0;
        }
        &#13;
        <input id="polygonbtn" type="button" value="Draw Polygon" />
        <input id="cancelbtn" type="button" value="Cancel" />
        <div id="map"></div>
        <!-- Replace the value of the key parameter with your own API key. -->
        <script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&callback=initMap" async defer></script>
        &#13;
        &#13;
        &#13;