Reputation: 1106
Inside marked Area I write some text. When I zoom out, text goes out outside Area and disappear. Is there any way to prevent this?
I was trying to change text size depending on Zoom size so that it always match inside the area and never disappear but it only catch the zoom once and later do not change anything.
Below part of my code.
var styleText = function(text) {
var zoom = map.getView().getZoom();
var resolution = map.getView().getResolution();
var font = zoom * 3
return {
text: new ol.style.Text({
font: font+'px Courier New',
fill: new ol.style.Fill({
color: '#ffd300'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 3
}),
textAlign: "center",
textBaseline: "middle",
text: text,
})
}
}
var newVector = new ol.layer.Vector({
name: areaIncra.farmId,
source: kmlVector,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
text: styleText('Text to show').text
})
});
Upvotes: 0
Views: 868
Reputation: 17897
For the style to be recalculated it needs to be a function
style: function(feature, resolution) { return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
text: styleText('Text to show').text
}); }
You might also want to set overflow: true
on ol.style.Text
https://openlayers.org/en/v4.6.5/apidoc/ol.style.Text.html
var styleText = function(text) {
var zoom = map.getView().getZoom();
var resolution = map.getView().getResolution();
var font = (zoom + 1) * 3;
return {
text: new ol.style.Text({
font: font+'px Courier New',
fill: new ol.style.Fill({
color: '#ffd300'
}),
stroke: new ol.style.Stroke({
color: '#000',
width: 3
}),
textAlign: "center",
textBaseline: "middle",
text: text,
overflow: true
})
}
}
var newVector = new ol.layer.Vector({
source: new ol.source.Vector(),
style: function(feature, resolution) {
return new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 3
}),
text: styleText('Text to show').text
});
}
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
newVector
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.addInteraction(new ol.interaction.Draw({
source: newVector.getSource(),
type: 'Polygon',
}));
<link href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<div id="map" class="map"></div>
Upvotes: 3