I have the current set up here: fully functional fiddle example and whilst I have managed to zoom to each polygon feature I would also like to display a centralised text label on each... the field_title
variable found within the get_fields
method. I have no idea how to do this and all my googling has come up with this article: http://openlayers.org/en/v3.3.0/examples/vector-labels.html which I find totally confusing as I'm a little new to OL!
Asked
Active
Viewed 2.6k times
11

Helen Danger Burns
- 421
- 2
- 9
- 28
-
Could you move the animating part to another question? It can helps in this initial confusion. – Jonatas Walker Aug 18 '16 at 09:52
-
@JonatasWalker have done. Thanks. – Helen Danger Burns Aug 18 '16 at 10:17
2 Answers
19
To add a text to ol.Feature
you will store the description in the feature and set a style that is a style function (that will get the description from the feature and show it):
field_polygon.set('description', field_title);
field_polygon.setStyle(styleFunction);
function styleFunction() {
return [
new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0.4)'
}),
stroke: new ol.style.Stroke({
color: '#3399CC',
width: 1.25
}),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({ color: '#000' }),
stroke: new ol.style.Stroke({
color: '#fff', width: 2
}),
// get the text from the feature - `this` is ol.Feature
// and show only under certain resolution
text: map.getView().getZoom() > 12 ? this.get('description') : ''
})
})
];
}

Jonatas Walker
- 13,583
- 5
- 53
- 82
-
1This is brilliant! Thank you! How would I only show the text above a certain zoom level? – Helen Danger Burns Aug 18 '16 at 10:24
-
1See updated answer. `map.getView().getZoom() > 12 ? this.get('description') : ''` – Jonatas Walker Aug 18 '16 at 10:37
-
2are you sure this works? I'm getting `Window` on `this` instead of a `ol.Feature` – andre_ss6 Aug 20 '18 at 02:05
-
1I got no a reference to `map`, so better I use a different signature for `styleFunction` : `const styleFunction = (myParams) => (feature, resulution) => . . .` then I compare the `resolution`variable instead of `getZoom()` to change the text content – Juan Salvador May 24 '20 at 21:35
3
Since I am new here and are not allowed to comment, I put my comment as a new answer to the question of @andre_ss6. I also get Window
on this
. What works for me is passing in the feature object as the function's first parameter:
function styleFunction(feature) {
and then use that parameter instead of this
:
text: feature.get('description')

d-tamm
- 31
- 1