绘制后点击按钮删除多边形

时间:2019-02-01 06:36:37

标签: javascript google-maps google-maps-api-3

我尝试开发一个应用程序,使用户可以在Google地图中绘制多边形,并在弹出的信息窗口中添加有关该多边形的其他信息。信息输入完成后,用户应单击“保存”以保存信息,如果要删除多边形,则应单击“删除”。删除是指不再在地图上可见。

我没有成功尝试以下代码。问题似乎出在底部“ deletePolygon”函数的作用域。我在polygon.setMap(null);函数中输入了google.maps.event.addListener,它从地图上删除了多边形,但是我不知道如何在单击按钮时触发多边形。

P.S:我将整个脚本粘贴到JSFiddle的“ html”部分中,这可能是错误的。抱歉!

<!DOCTYPE html>
<html>

<head>
  <title>Drawing Tools</title>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <style>
    /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
    
    #map {
      width: 1200px;
      height: 800px;
    }
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=drawing&callback=initMap" async defer></script>
  <script>
    // hier die Einstellungen für den Schutz vor CSRF
    var map;
    var infoWindow;

    //Einstellungen der Grundkarte
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {
          lat: 49.819227,
          lng: 19.230721
        },
        zoom: 13
      });
      //Einstellungen des Drawing Managers
      var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.null, //Zeichnen Standardmäßig nicht ausgewählt wenn die Karte geladen wird (alternativ: polygon, marker etc)
        drawingControl: true, //drawing manger wird angezeigt
        drawingControlOptions: {
          position: google.maps.ControlPosition.TOP_CENTER, //position des drawing managers
          drawingModes: ['polygon'] // Auswahlmöglichkeiten der Werkzeuge :'marker', 'circle', 'polygon', 'polyline', 'rectangle'
        },
        //Optionen zur Darstellung Polygon
        polygonOptions: {
          fillColor: '#ffff00', //Farbwahl
          fillOpacity: 0.5,
          strokeWeight: 3,
          clickable: false, //erweiterte Funktion
          editable: false,
          zIndex: 1
        }
      });
      drawingManager.setMap(map);

      //Erstellung einer Infobox zur Bennenung der Probe
      function polygonCenter(poly) {
        var lowx,
          highx,
          lowy,
          highy,
          lats = [],
          lngs = [],
          vertices = poly.getPath();

        for (var i = 0; i < vertices.length; i++) {
          lngs.push(vertices.getAt(i).lng());
          lats.push(vertices.getAt(i).lat());
        }

        lats.sort();
        lngs.sort();
        lowx = lats[0];
        highx = lats[vertices.length - 1];
        lowy = lngs[0];
        highy = lngs[vertices.length - 1];
        center_x = lowx + ((highx - lowx) / 2);
        center_y = lowy + ((highy - lowy) / 2);
        return (new google.maps.LatLng(center_x, center_y));
      }
      //InfoBox Text
      html = "<table>" +
        "<tr>" +
        "<td>Bezeichnung:</td>" +
        "<td><input type='text' id='feldbezeichnung'/> </td>" +
        "</tr>" +
        "<tr>" +
        "<td><input type='button' value='save' onclick='saveData()'/></td>" +
        "<td><input type='button' value='delete' onclick='deletePolygon()'/></td>" +
        "</tr>";

      //Erstellung einer Infobox wenn ein Feld eingezeichnet wurde
      google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
        drawingManager.setDrawingMode(null);
        //Öffnen der Infobox
        var InfoBoxLoc = polygonCenter(polygon); //Koordinaten der Infobox zur Beschriftung

        infowindow = new google.maps.InfoWindow({
          content: html,
          position: InfoBoxLoc,
        });
        infowindow.open(map);

        //it works here but how to trigger it on button press from the infowindow?
        //##################polygon.setMap(null);

      });
      //Ende Drawing manager
    } //Ende Init Map

    //funktion zum speichern der Daten
    function saveData() {
      var FieldName = escape(document.getElementById("feldbezeichnung").value);
      console.log(FieldName)
      //schließt das InfoWindo nach erfolgreicher Eingabe
      infowindow.close();
    }

    //funktion zum löschen des Polygon bei falscher Eingabe
    function deletePolygon() {
      infowindow.close();
      console.log(polygon)
      polygon.setMap(null);
    }
  </script>
</head>

<body>
  <!--Einbinden von Google Maps -->
  <div id="map"></div>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

下面的代码注释了进行更改的位置,但从本质上讲,如果您侦听infoWindow事件并在其中分配侦听器是相当容易的。希望以下内容将演示如何做到这一点

<!DOCTYPE html>
<html>
    <head>
        <title>Drawing Tools</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <style>
        /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */

        #map {
          width: 1200px;
          height: 800px;
        }
        /* Optional: Makes the sample page fill the window. */

        html,
        body {
          height: 100%;
          margin: 0;
          padding: 0;
        }
        </style>

        <script>
            var map;
            var infoWindow;

            function initMap() {
              var map = new google.maps.Map(document.getElementById('map'), {
                center: {
                  lat: 49.819227,
                  lng: 19.230721
                },
                zoom: 13
              });


              var drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: google.maps.drawing.OverlayType.null,
                drawingControl: true,
                drawingControlOptions: {
                  position: google.maps.ControlPosition.TOP_CENTER,
                  drawingModes: ['polygon']
                },
                polygonOptions: {
                  fillColor: '#ffff00',
                  fillOpacity: 0.5,
                  strokeWeight: 3,
                  clickable: false,
                  editable: false,
                  zIndex: 1
                }
              });
              drawingManager.setMap(map);


              function polygonCenter(poly) {
                var lowx,
                  highx,
                  lowy,
                  highy,
                  lats = [],
                  lngs = [],
                  vertices = poly.getPath();

                for (var i = 0; i < vertices.length; i++) {
                  lngs.push(vertices.getAt(i).lng());
                  lats.push(vertices.getAt(i).lat());
                }

                lats.sort();
                lngs.sort();
                lowx = lats[0];
                highx = lats[vertices.length - 1];
                lowy = lngs[0];
                highy = lngs[vertices.length - 1];

                center_x = lowx + ((highx - lowx) / 2);
                center_y = lowy + ((highy - lowy) / 2);
                return (new google.maps.LatLng(center_x, center_y));
              }

              /*
                remove inline event handlers from HTML
                and assign dynamically when the content
                is actually loaded into the DOM
              */
              html = "<table>" +
                "<tr>" +
                "<td>Bezeichnung:</td>" +
                "<td><input type='text' id='feldbezeichnung'/> </td>" +
                "</tr>" +
                "<tr>" +
                "<td><input type='button' value='save' data-action='save' /></td>" +
                "<td><input type='button' value='delete' data-action='delete' /></td>" +
                "</tr>";


              google.maps.event.addListener(drawingManager, 'polygoncomplete', function( polygon ) {
                drawingManager.setDrawingMode(null);

                var InfoBoxLoc = polygonCenter(polygon);

                infowindow = new google.maps.InfoWindow({
                  content: html,
                  position: InfoBoxLoc,
                });

                infowindow.open(map);


                /*
                    The `infoWindow` will fire a `ready` event when it is loaded and, as you are loading HTML data into
                    an infoWindow, it makes sense to watch for that event and assign event listeners accrdingly to any
                    child elements
                */
                google.maps.event.addListener( infowindow, 'domready', event => {
                    /*
                        Obtain a reference to the buttons `save` and `delete` 
                        and assign event listeners
                    */
                    document.querySelector('td > input[type="button"][data-action="save"]').addEventListener('click', e=>{
                        let fieldname = escape( document.getElementById("feldbezeichnung").value )
                        console.log( fieldname )
                        infowindow.close();
                    });     

                    document.querySelector( 'td > input[type="button"][data-action="delete"]' ).addEventListener('click', e=>{
                        infowindow.close();
                        console.log(polygon)
                        polygon.setMap(null);
                    }); 
                });
              });
            }
        </script>
        <script src="//maps.googleapis.com/maps/api/js?key=APIKEY&libraries=drawing&callback=initMap" async defer></script>
    </head>
    <body>
      <div id="map"></div>
    </body>
</html>
相关问题