Thursday, 24 November 2016

jquery - How to set an ol.style.text using a source in OpenLayers?


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?



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...