簡體   English   中英

繪制后單擊按鈕時刪除多邊形

[英]Delete polygon on button click after drawing

我嘗試開發一個應用程序,使用戶可以在Google地圖中繪制多邊形,並在彈出的信息窗口中添加有關該多邊形的其他信息。 信息輸入完成后,用戶應單擊“保存”以保存信息,如果要刪除多邊形,則應單擊“刪除”。 刪除是指不再在地圖上可見。

我嘗試了以下代碼失敗。 問題似乎出在底部“ deletePolygon”函數的作用域。 我輸入了polygon.setMap(null); google.maps.event.addListener函數中,它從地圖上刪除了多邊形,但是我不知道如何在單擊按鈕時觸發該多邊形。

PS:我將整個腳本粘貼到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> 

下面的代碼注釋了進行更改的位置,但實質上,如果您偵聽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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM