2
votes

This seemed simple on the face of it, but I am unable to figure out how to toggle the visibility of a marker feature using the Version 3 API of OpenLayers.

In my situation, I am adding features to a vector layer. Each feature is a marker icon denoting a place of interest. When I click on a checkbox somewhere else on the page, I'd like for the feature to appear of disappear (as the case may be). I am using JQuery in conjunction with OL3, but I don't care whether the solution is jquery or vanilla javascript.

Code snippets:

var vectorSource = new ol.source.Vector({
    projection: "EPSG:4326"
});
var vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: fieldIconStyle
});



var map = new ol.Map({
    layers: [osm, digitalglobe, vectorLayer],//osm and digitalglobe exist in unquoted code
    target: 'map',
    controls: ol.control.defaults({
        attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
            collapsible: false
        })
    }).extend([mousePositionControl]),
    view: new ol.View({
        center: [0, 0],
        zoom: 2
    })
});

function checkedchanged(item)//item is the checkbox that was clicked
{
    //this function does get called successfully.
    //alert($(item).prop('checked'));
    var selected = $(item).prop('checked');
    var id = $(item).val();

    vectorSource.forEachFeature(function (item) {

        var props = item.getProperties();
        if (props.FieldId = id) {
            item.setStyle({visible: selected});//I have tried many different things here, all to no avail
        }
    });
}
1
Please, keep your question in one single place, here or there. - Jonatas Walker
Can you provide a fiddle for this? - void

1 Answers

3
votes

You may set the Point nodes into an array, which will be valid the whole runtime of the map. On click of an point remove all features of the layer first, then iterate over this array again and add only items which are not clicked. Then just redraw the layer on the map - this should do the trick. Therefore it is necessary that every Point has an unique ID.