多次切换多边形不工作



我们正在使用以下代码和切换多边形。如果我们点击多次,这是不工作。从第四次开始,它被一次又一次地画出来,形状变成了白色。请帮助。

我们将多边形坐标存储在一个隐藏的文本框中,并将它们传递给函数displaypolygons。实际上我们会有更多的多边形它们来自DB。在这个示例代码中,我们只展示了一个。这里142是使用循环递增的增量值。

<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">

这里我们将多边形坐标推入' gpolygons '全局数组。这里我们使用增量值来分配唯一的id。

<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>

然后使用切换函数切换多边形。我们循环遍历' gpolygons '数组并根据匹配的唯一id显示/隐藏

<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>

而不是遍历存储在全局gpolygons数组中的所有多边形-如果这是一个对象字面量,那么您可以非常快速地访问单个多边形引用。全局可以存储多边形和MapLabel引用使用一个共同的ID -即输入元素(如:cb_142等)

<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Google Maps: Toggle Polygons...</title>
<style>
body{
padding:0;
margin:0;
width:100%;
height:100vh;
}
#map{
width:100%;
height:600px;
}
</style>
</head>
<body>
<div id='map'></div>
<form name='poly'>

<input type='text' id='coords' />

<!-- more before -->

<input class='cbarea' type='checkbox' name='cb' data-id=142 />
<input type='hidden' name='area'  data-id=142 value='A Area' />
<input type='hidden' name='latlon'  data-id=142 value='
(11.050885924877363,77.04118423201588),
(11.050885924877363,77.04342655875233),
(11.048769408381661,77.04341582991627),
(11.049074777375772,77.04037956931141)' 
/>

<input class='cbarea' type='checkbox' name='cb' data-id=143 />
<input type='hidden' name='area'  data-id=143 value='B Area' />
<input type='hidden' name='latlon'  data-id=143 value='
(11.060885924877363,77.05118423201588),
(11.060885924877363,77.05342655875233),
(11.068769408381661,77.05341582991627),
(11.069074777375772,77.05037956931141)' 
/>

<input class='cbarea' type='checkbox' name='cb' data-id=144 />
<input type='hidden' name='area'  data-id=144 value='C Area' />
<input type='hidden' name='latlon'  data-id=144 value='
(11.070885924877363,77.06118423201588),
(11.070885924877363,77.06342655875233),
(11.078769408381661,77.06341582991627),
(11.079074777375772,77.06037956931141)' 
/>

<!-- and repeat for all others -->


</form>
<script>
const d=document;

class MapLabel{// no idea what this is....
constructor(args){
return Object.assign({

},args);
}
}



function initMap(){

let polygons={
polys:{},
labels:{}
};
let coords=d.querySelector('#coords');

const map = new google.maps.Map( document.querySelector('div#map'), {
zoom: 3,
center: { lat:0, lng:0 }
});

d.forms.poly.addEventListener('change',e=>{
if( e.target instanceof HTMLInputElement && e.target.type=='checkbox' ){


let id=e.target.dataset.id;
let area=d.querySelector(`input[name="area"][data-id="${id}"]`);
let latlon=d.querySelector(`input[name="latlon"][data-id="${id}"]`);

coords.value=latlon.value;

if( !polygons.polys.hasOwnProperty( id ) ){
let path=[];
let bounds = new google.maps.LatLngBounds();

let pairs=latlon.value.replace(/[()t]/g,'').trim().split(',');
for( let i=0; i < pairs.length; i+=2 ){
let lat=pairs[i];
let lng=pairs[i+1];
let latlng=new google.maps.LatLng(lat,lng);

path.push( latlng );
bounds.extend( latlng );
}

// only green so that it is easily visible!!!
let poly=new google.maps.Polygon({
_uniqueId: id,    
paths: path,
strokeWeight: 2,
fillOpacity: 0.45,
fillColor: '#00ff00',
strokeColor: '#000000',
editable:e.target.checked,
draggable:false
});

let label=new MapLabel({
text: `area_lbl ( Id: ${id} )`,
position: new google.maps.LatLng( bounds.getCenter() ),
map: map,
fontSize: 14,
align: 'center'
});

poly.setMap( map );     

polygons.polys[ id ]=poly;
polygons.labels[ id ]=label;

map.fitBounds( bounds );
}else{
polygons.polys[ id ].setMap( e.target.checked ? map : null  );
//polygons.labels[ id ].setMap( e.target.checked ? map : null );
}
}
})
}
</script>
<script async defer src='//maps.googleapis.com/maps/api/js?key=KEY&callback=initMap'></script>
</body>
</html>

概念证明

相关内容

  • 没有找到相关文章

最新更新