nachtigall
nachtigall

Reputation: 2497

Only print ol.style.Text to polygon if text label fits inside its geometry

In OpenLayers I use ol.style.Text to add a text label to federal states polygons. The states have names of different length and also polygons of different sizes. It looks like this:

enter image description here

Is it possible to only print the text marker if it fits inside its polygon (e.g. after zooming in)? For instance, in the above example Hessen, Thüringen, Sachsen and Bayern would be printed, but Rheinland-Pfalz, Saarland and Baden-Württemberg would be omitted because the text goes beyond its feature's geometry...

I know I can set the font property of an ol.style.Text to a particular size based on the resolution but this does not help here as text would still overlap the borders sometimes...

Upvotes: 4

Views: 1261

Answers (1)

ahocevar
ahocevar

Reputation: 5648

This is currently not possible with help from the library. But you can use CanvasRenderingContext2D#measureText() in your vector layer's stlyeFunction to get the width of the label, and compare that with the extent's width of the polygon at a certain resolution, and decide based on that whether to render or not. You can also get smarter than using the extent's width, but it is probably a good enough approximation for many cases.

Upvotes: 3

Related Questions