简体   繁体   中英

How to hide and show features in OpenLayers 3? (Redraw?)

I'm updating a project from OL2 to OL3 , but I'm stuck on how to redraw features after changing the feature style.

In OL2, this worked:

hidePoints: function(id) {
    if (! this.getMap().center) {
        return;
    }

    var i,
    feature,    
    len = this.points.features.length;

   if (id !== null) {
    for( i = 0; i < len; i++ ) {         
      feature = this.points.features[i];
      if (feature.attributes.aces_id == id) {
          feature.style = null;
        } else {
            feature.style = { display: 'none' };
        }
      }
   } else {
      for( i = 0; i < len; i++ ) {         
        feature = this.points.features[i];
        feature.style = { display: 'none' };
      }
   }
 this.points.redraw();
},

In OL3, I tried updating the function to hide the points layer, but redraw() no longer exists and since the layer I am working with is an ol.layer.Vector , I can't find any updateParams options like other sources besides vectors have. Dispatch Event and changed also did not work. I was hoping changed would, but nothing happens.

hidePoints: function(id) {
    if (! this.getMap().getView().getCenter()) {
        return;
    }

    var i,
        feature,
        layerSourceFeatures = this.pointsLayer.getSource().getFeatures(),
        len = layerSourceFeatures.length;

    if (id !== null) {
        for( i = 0; i < len; i++ ) {
            feature = this.pointsLayer.getSource().getFeatures()[i];

            if (feature.get('aces_id') == id) {
                feature.style = null;
            } else {
                feature.style = { display: 'none' };
            }
        }
    } else {
        for( i = 0; i < len; i++ ) {
            feature = this.pointsLayer.getSource().getFeatures()[i];
            feature.style = { display: 'none' };
        }
    }
    //this.pointsLayer.redraw();
    //this.pointsLayer.dispatchEvent(goog.events.EventType.CHANGE);
    this.pointsLayer.changed();
},

I'm also wondering if changing the style is done this way (fetching each feature to another var) or if that won't just change that feature and leave the original untouched. Plus always fetching getSource().getFeatures() seems abusive on the performance... but I can't seem to find another way.

Regardless, how is redraw performed in OL3 now to render features whose styles have been altered? A layer can be set as visible, but I don't want to hide/show all the features all the time. Sometimes I just want to hide/show a few according to their given id.

Another way to do it is using a style function and a hidden propertie on the feature:

var style = new ol.Style(...);

function Stylefunction (feature, resolution) {
    var prop = feature.getProperties();
    if (prop.HIDDEN)
       return;

    return style;
}

var layer = new ol.layer.Vector({
    source: new ol.source.Vector(...),
    style: Stylefunction 
});

if you change the feature "HIDDEN" propertie, it instant refreshes

So while looking at the documentation over and over, I finally found what would fire the change event, much like seto suggested after.

This is the converted function from OL2 to OL3 that works for me. Redraw is no longer needed since setStyle does it all.

hidePoints: function(id) {
    if (! this.getMap().getView().getCenter()) {
        return;
    }

    var i,
        feature,
        layerSourceFeatures = this.pointsLayer.getSource().getFeatures(),
        len = layerSourceFeatures.length;

    var emptyImgStyle = new ol.style.Style({ image: '' });

    // If an aces id was provided
    if (id !== undefined) {
        for( i = 0; i < len; i++ ) {
            feature = layerSourceFeatures[i];

            feature.setStyle(emptyImgStyle);

            // Resetting feature style back to default function given in defaultPointStyleFunction()
            if (feature.get('aces_id') == id) {
                feature.setStyle(null);
            }
            // Hiding marker by removing its associated image
            else {
                feature.setStyle(emptyImgStyle);
            }
        }
    }
    // No id was provided - all points are hidden
    else {
        for( i = 0; i < len; i++ ) {
            feature = layerSourceFeatures[i];
            feature.setStyle(emptyImgStyle);
        }
    }
},

I can't add comments because I don't have enough reputation, but instead of feature.style = null you might want to call feature.setStyle(null) , because this internally triggers the changed event and should instantaneously and automatically change the style. Also feature.style = { display: 'none' } will not work in openlayers 3 because the style needs to be an ol.style.Style object ( http://openlayers.org/en/v3.14.2/apidoc/ol.Feature.html#setStyle )

If you have the ID of the features, you can use the source.getFeatureById() method instead of cycling through the features.( http://openlayers.org/en/v3.14.2/apidoc/ol.source.Vector.html#getFeatureById )

Regards rendering, I think using the map's map.render() (at openlayers.org/en/v3.14.2/apidoc/ol.Map.html#render) will re-render the map.

If you just to call a function whenever the map is re-rendered, you can listen on the postrender or postcompose events on the map.

If you create a JSFiddle, I can help you further.

Edit: This example might help you - openlayers.org/en/v3.14.2/examples/dynamic-data.html?q=style

I like this approach for layer toggling (applies to other features, as well):

JAVASCRIPT

<script>
    var layerBing = new ol.layer.Tile({
          source: new ol.source.BingMaps({
              imagerySet: 'Aerial',
              key: 'YourKeyBingAccess'
          }),
          name: 'Bing'
    });

    /*
    *  YOUR MAP CODE  GOES HERE
    */

    function toggleLayer(layerObject) {
        var newVisibility = !(layerObject.get('visible'));
        layerObject.set('visible', newVisibility);
    }
</script>

HTML

<button onclick="toggleLayer(layerBing)">Bing Satellite</button>
<div id="map" class="map"></div>

For hiding or showing you need to set visible property of layer to false or true.

var someFeature = ...; // create some feature
someFeature.set('style', someStyle) // set some style
var someFeatureLayer = ...; // create Layer from someFeature
map.addLayer( someFeatureLayer ); // add someFeatureLayer
someFeatureLayer.set('visible', false);
//someFeatureLayer.set('visible', true); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM