0

I'm trying to add features to a vector layer using a checkbox. var featureOverlay = new.ol.FeatureOverlay;

$("input:checkbox").each(function(){
    var $this = $(this);

    if($this.is(":checked")){
        featureOverlay.addFeature(feature);
    }else{
        featureOverlay.removeFeature(feature);
    }
});

var polyCoords = [];
var coords = "95.61,38.60 95.22,37.98 95.60,37.66 94.97,37.65".split(' ');

for (var i in coords) {
  var c = coords[i].split(',');
  polyCoords.push(ol.proj.transform([parseFloat(c[0]), parseFloat(c[1])], 'EPSG:4326', 'EPSG:3857'));
}

var feature = new ol.Feature({
geometry: new ol.geom.Polygon([polyCoords])
})

var layer = new ol.layer.Vector({
source: new ol.source.Vector({
    features: [feature]
    })
});

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'sat'})
    }),
    layer            
  ],
  view: new ol.View({
    center: ol.proj.transform([95.22, 37.98], 'EPSG:4326', 'EPSG:3857'),
    zoom: 4
  })
});
2

First of all, you need to add the FeatureOverlay to the map and then use the onchange event of checkbox.

var featureOverlay = new ol.FeatureOverlay({
    map: map
});
var updateFeat = function(){
    var $this = $(this);

    if($this.is(":checked")){
        featureOverlay.addFeature(feature);
    }else{
        featureOverlay.removeFeature(feature);
    }
};
// each: initialize the status of the feature when the page opens
// change: Update the status of the feature on each click on the checkbox
$("input:checkbox").each(updateFeat).change(updateFeat);

Here is the jsfiddle

| improve this answer | |
  • Yep, I found that out myself over the weekend. You beat me to the answer. @oterral: What if you have multiple arrays that you want to turn on and off individually by their own checkbox? ".each" function? – Dean Apr 13 '15 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.