Reputation: 735
I try to develop an application where a user can draw a polygon in google maps and add additional information about it in an infowindow that is popping up. Once the entry of information is completed the user should click "save" to save the information or "delete" if the polygon should be deleted. By deleted I mean not visible on the map anymore.
I tried the following code unsuccessfully. The problem seems to be the scope of the "deletePolygon" function at the bottom. It I enter the polygon.setMap(null);
within the google.maps.event.addListener
function it removes the polygon from the map, but I don't know how to trigger it there in button click.
P.S:I pasted the entire script in the "html" section of JSFiddle which is probably wrong. Sorry!
<!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>
Upvotes: 0
Views: 1328
Reputation: 33823
The code below is commented where changes are made but in essence if you listen for infoWindow
events and assign listeners within it is fairly easy. Hopefully the following will demonstrate how to do this
<!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>
Upvotes: 1