[GIS] OpenLayers display labels

labelingopenlayers-2zoom

I am displaying and labelling a polygon Layer using a GeoJSON file and the field nom_comm. I would like to label the polygons between two scales i.e. two zooms.
(So to speak, labels are to be invisible when scale of the map is too high or too little.)

How can I do that?

Sample of HTML:

var styleDS = new OpenLayers.Style({
                        'fillOpacity': 0,
                        'strokeColor': "red",
                        'strokeWidth': 0.8,
                        'fontFamily': "Verdana",
                        'fontWeight': "bold",
                        'fontSize': "6.5px",
                        'labelOutlineColor': "white",
                        'labelOutlineWidth': 1,
                        'label': "${getLabel}"/* options */
                                        },
                        {
                        context: { getLabel:function(feature) //affichage nom commune en fonction echelle
                                    { if (map.getZoom() > 9 && map.getZoom() < 12.5) 
                                    { console.log('affiché'); var label = feature.attributes['nom_comm']; 
                                    return label; } 
                                    else { console.log('caché'); return ''; }
                                    } 
                                }  
                            });     

Then I applied the style like this:

var commune = new OpenLayers.Layer.Vector(
        "commune", {
        strategies: [new OpenLayers.Strategy.Fixed()],
        protocol: new OpenLayers.Protocol.HTTP({
            url: "communes.geojson",
            format: new OpenLayers.Format.GeoJSON()
        }),
        //autre maniere de creer un style
        styleMap: styleDS, 
        }
);
  map.addLayer(commune);

And I don't have a link to the map because it belongs to a domain.

Best Answer

You could use a style with a context :

var monstyle = new OpenLayers.Style({
    'fillOpacity': 0,
    'strokeColor': "red",
    'strokeWidth': 0.8,
    'label': "${getLabel}",
    'fontFamily': "Verdana",
    'fontWeight': "bold",
    'fontSize': "7px",
    'labelOutlineColor': "white",
    'labelOutlineWidth': 1
}, {
    context: {
        getLabel: function(feature) {
            if (map.zoom > 10 && map.zoom < 13) {
                return feature.attributes.nom_comm;
            } else {
                return '';
            }
        }
    }
});