4

I have the following code:

var cbcWFS = new ol.source.GeoJSON({
    projection: 'EPSG:3857',
    url: 'http://localhost:7070/geoserver/CuerpoBomberosCurico/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=CuerpoBomberosCurico:CuerpoBomberosCurico&maxFeatures=50&outputFormat=application/json'
  });

var cuerpoBomberosVector = new ol.layer.Vector({
      title: 'Cuerpo Bomberos',
      source: cbcWFS,
      style: new ol.style.Style({
        image: new ol.style.Icon({
          scale: 0.04,
          src: 'https://dl.dropboxusercontent.com/u/27798645/fireman/truck65.svg'
        }),
        text: new ol.style.Text({
          text: 'Hello',
          scale: 1.3,
          fill: new ol.style.Fill({
            color: '#000000'
          }),
          stroke: new ol.style.Stroke({
            color: '#FFFF99',
            width: 3.5
          })
        })
      })
  });

But now, in the part of "Text", I'd like to use the value that it comes from the source.

Any idea to develop it?

7

You can achieve this using a style function on your vector layer. This is a function that is called whenever a feature is rendered, with the feature and the view resolution as arguments. The function is supposed to return an array of styles. The official vector-layer example shows how to do this. To see the example live, go to http://openlayers.org/en/v3.3.0/examples/vector-layer.html and zoom in a few times.

In your specific case, you would have to change your code to something like this:

var cuerpoBomberosVector = new ol.layer.Vector({
  title: 'Cuerpo Bomberos',
  source: cbcWFS,
  style: (function() {
    var style = new ol.style.Style({
      image: new ol.style.Icon({
        scale: 0.04,
        src: 'https://dl.dropboxusercontent.com/u/27798645/fireman/truck65.svg'
      }),
      text: new ol.style.Text({
        text: 'Hello',
        scale: 1.3,
        fill: new ol.style.Fill({
          color: '#000000'
        }),
        stroke: new ol.style.Stroke({
          color: '#FFFF99',
          width: 3.5
        })
      })
    });
    var styles = [style];
    return function(feature, resolution) {
      style.getText().setText(feature.get("text"));
      return styles;
    };
  })()
});

The above snippet assumes that your features have an attribute 'text' that holds the text you want to have as label.

  • Won't this change the text for every feature on this layer? – ca0v Aug 18 '15 at 17:57
  • Not if you make this change on the text style that you return from the styleFunction. – ahocevar Aug 19 '15 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.