user3557112 user3557112 - 5 months ago 109
Javascript Question

Set style zoom level openlayers 3

In Openlayers it was possible to turn certain features on or off depending on the zoom level. I have not found the same functionality in OpenLayers 3 despite looking through the documentation. Does anyone know how to do this? This is the feature I'm placing on the map and

ol.style.Text
is what I would like to display only after the user is zoomed in to a particular zoom level.

var geoJsonObj = {
'type': 'Feature',
'geometry': JSON.parse(response.FieldList[key].Shape)
}
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geoJsonObj)
});
Fields[Field.FieldID] = new ol.layer.Vector({
projection: 'EPSG:4269',
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'yellow',
width: 1
}),
fill: new ol.style.Fill({
color: rcisWebMapUtilities.convertHex(response.FieldList[key].Shade, '0.5')
}),
text: new ol.style.Text({
textAlign: 'Center',
text: response.FieldList[key].Acres,
scale: 1
})
})
});

Answer

The vector layer example demonstrates the use of a style function for resolution dependent styling: http://openlayers.org/en/latest/examples/vector-layer.html

Here is a simplified version:

var layer = new ol.layer.Vector({
  source: new ol.source.Vector(),
  style: function(feature, resolution) {
    var text = resolution < 5000 ? feature.get('name') : '';
    return new ol.style.Style({
      text: new ol.style.Text({
        text: text,
        fill: new ol.style.Fill({
          color: '#000'
        }),
        stroke: new ol.style.Stroke({
          color: '#f00',
          width: 3
        })
      })
    });
  }
});

The layer above would render feature names at resolutions below 5000 map units per pixel.

The vector layer example above has some additional code to reuse styles when possible. If you've got a ton of features, you can put excess pressure on the garbage collector by creating new style instances for every render frame.

Comments