We are using following code and toggling polygons. If we click multiple times this is not working. From fourth time this is getting drawn again and again and the shape becomes white. Please help.
We are storing polygon coordinates in a hidden textbox and passing them to the function ‘displaypolygons’. Actually we will be having more polygons and they will come from DB. In this sample code we have shown only one. Here 142 is the incremental value which incremented using loop.
<input class="cbarea" type="checkbox" name="cb_142" id="cb_142" onclick="javascript:displaypolygons('142')"> <input type="hidden" name="latlon_142" id="latlon_142" value="(11.050885924877363,77.04118423201588),(11.050885924877363,77.04342655875233),(11.048769408381661,77.04341582991627),(11.049074777375772,77.04037956931141)"> <input type="hidden" name="area_142" id="area_142" value="A Area">
Here we are pushing the polygon coordinates to ‘gpolygons’ global array. Here we are assigning unique id using the incremental value.
<script>
function displaypolygons(ai) {
var sel_latlon= document.getElementById("latlon_"+ai).value;
document.getElementById("coords").value = sel_latlon;
var sel_latlon = sel_latlon.replaceAll("(", "");
var latlon = sel_latlon.split("),");
var mid = parseInt(latlon.length/2); var cent = latlon[mid].split(",");
var peditable = false;
var cbchecked = $('#cb_' + ai).is(":checked")
if (!cbchecked) return togglePolygon(ai);
//if (ai==3) peditable = true;
const triangleCoords = []; //var idx =0;
for(var i=0; i<latlon.length; i++){
var arr = latlon[i].split(",");
triangleCoords.push(new google.maps.LatLng({lat: parseFloat(arr[0]), lng: parseFloat(arr[1])}, true));
}
bounds = new google.maps.LatLngBounds();
for (i = 0; i < triangleCoords.length; i++) {
bounds.extend(triangleCoords[i]);
}
// Construct the polygon.
bermudaTriangle = new google.maps.Polygon({
_uniqueId: ai,
paths: triangleCoords,
strokeWeight: 2,
fillOpacity: 0.45,
fillColor: '#ffffff',
strokeColor: '#ffffff',
editable:peditable,
draggable:false
});
bermudaTriangle.setMap(map);
gpolygons.push(bermudaTriangle);
map.setCenter(new google.maps.LatLng(bounds.getCenter()), 4);
var area_lbl= document.getElementById("area_"+ai).value;
var mapLabel = new MapLabel({
text: area_lbl+" (Id: "+ai+" )",
position: new google.maps.LatLng(bounds.getCenter()),
map: map,
fontSize: 14,
align: 'center'
});
labelObjects.push(mapLabel);
};
google.maps.event.addDomListener(window,"load", initMap);
</script>
Then using toggle function we are toggling the polygons. We are looping through the ‘gpolygons’ array and based on the matching unique id we are displaying /hiding
<script>
function togglePolygon(id) {
for (var i = 0; i < gpolygons.length; i++) {
if (gpolygons[i]._uniqueId == id) {
if (gpolygons[i].getMap() != null) {
gpolygons[i].setMap(null);
} else {
gpolygons[i].setMap(map);
}
labelObjects[i].setMap((labelObjects[i].getMap())?null:mymap)
}
}
}
</script>