0

I have piece of code in openlayers. I need to auto hide some text after zooming in.

nothing worked so far. This is what I have now:

this.addMarker = function(lon, lat) {
    var mar = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
    });
    var iconBlue = new ol.style.Style({
      image: new ol.style.Icon({
        anchor: [12, 40],
        anchorXUnits: 'pixels',
        anchorYUnits: 'pixels',
        opacity: 1,
        src: '../../images/marker_blue.png'
      }),
      text: new ol.style.Text({
        text: "Test text",
        scale: 1.2,
        fill: new ol.style.Fill({
          color: "#fff"
        }),
        stroke: new ol.style.Stroke({
          color: "0",
          width: 3
        })
      })
    });
    mar.setStyle(iconBlue);
    vectorSource.addFeature(mar);
  }

Need to hide text while the user zooms in fully(or after a particular zoom). Any help/guidance is appreciated.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Issac Saji
  • 106
  • 6

1 Answers1

1

Separate the icon and text styles and use a style function where you can test the resolution. In a live environment I expect you would also want to replace "Test text" with a property of your feature? You could also make the style function the style of your layer instead of setting it in each feature, as it is passed the feature.

var iconBlueIcon = new ol.style.Style({
  image: new ol.style.Icon({
    anchor: [12, 40],
    anchorXUnits: 'pixels',
    anchorYUnits: 'pixels',
    opacity: 1,
    src: '../../images/marker_blue.png'
  })
});
var iconBlueText = new ol.style.Style({
  text: new ol.style.Text({
    text: "Test text",
    scale: 1.2,
    fill: new ol.style.Fill({
      color: "#fff"
    }),
    stroke: new ol.style.Stroke({
      color: "0",
      width: 3
    })
  })
});
var iconBlue = function(feature, resolution) {
    var styles = [iconBlueIcon];
    if (resolution > minRes) {
        iconBlueText.getText().setText(feature.get('someProperty'))
        styles.push(iconBlueText);
    }
    return styles;
}

this.addMarker = function(lon, lat) {
    var mar = new ol.Feature({
      geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
    });
    mar.setStyle(iconBlue);
    vectorSource.addFeature(mar);
  }
Mike
  • 16,042
  • 2
  • 14
  • 30