Openlayers 3: add text label to feature - javascript

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!

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') : ''
})
})
];
}
Your fiddle.

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')

Related

Animate icon in GoJS

I have a graph with nodes that contains icons:
$(go.TextBlock, {
font: '18pt Material Icons', alignment: go.Spot.LeftCenter, stroke: '#FFFFFF',
margin: new go.Margin(0, 5, 0, -34),
},
new go.Binding('text', 'statusIcon')),
I would like to rotate statusIcon infinitly but only if statusIcon matchs a value.
I have looked how to add a css rule like this.
font: '18pt Material Icons', alignment: go.Spot.LeftCenter, stroke: '#FFFFFF',
margin: new go.Margin(0, 5, 0, -34),animation:'spin 4s linear infinite';
But I get an error
Trying to set undefined property "animation" on object: TextBlock
I suppose that only few css rules are accepted by gojs TextBlock.
How can I add animation to only a node sub element ?
I created a StackBlitz example here.
$(go.TextBlock, {
font: '18pt Material Icons', alignment: go.Spot.LeftCenter, stroke: '#FFFFFF',
margin: new go.Margin(0, 5, 0, -34),
},
new go.Binding('text', 'statusIcon'),
new go.AnimationTrigger("angle")),
animate() {
this.dia.commit(diag => {
var node = this.dia.nodes.first();
var textblock = node.findObject("TEXTBLOCK_TO_ROTATE");
textblock.angle = textblock.angle + 30;
});
}
Animation is not a property like you used above. If you want to rotate, you should use AnimationTrigger and angle property for that.
I made a simple example to use GoJS animation, you can apply the codes from node template of TextBlock and the method to animate as you wish.
For more information, you can follow the description and the examples here.

pixijs text is cutted

I'm trying to draw text in pixijs app stage and the text is cut off a bit. See the screenshot below.
I've tried to put it inside container but I can't fix it.
const style = new PIXI.TextStyle({
fontFamily: 'Bangers',
fontSize: 256,
fontWeight: 'bold',
fill: ['#ffa512', '#ff9e00'], // gradient
stroke: '#fff',
strokeThickness: 5,
dropShadow: true,
dropShadowColor: '#000000',
dropShadowBlur: 4,
dropShadowAngle: Math.PI / 6,
dropShadowDistance: 2,
});
const richText = new PIXI.Text('Nagitto', style);
richText.x = 50;
richText.y = 250;
app.stage.addChild(richText);
No exceptions.
I'm using a font from google fonts.
Use padding property inside style.
padding: 5,
I suggest you can use https://pixijs.io/pixi-text-style/# to dynamically create text with a preview.
The text is hardly cut from the code you wrote to create it. In my experience, this is only happening when there is a mask on the stage.
Please show the code for your container where you add the text in.

SAP UI5 Gantt Chart color based on condition

How can I set the fill color of a Gantt chart shape based on the value of a property in the bound json model?
Here's the code I am using to configure the sap.gantt.config.Shape :-
var oRectangle = new sap.gantt.config.Shape({
key: "Rectangle",
shapeDataName: "schedule",
shapeClassName: "sap.gantt.shape.Rectangle",
shapeProperties: {
time: "{startTime}",
endTime: "{endTime}",
height: 32,
fill: "green",
title: "{name}",
level: 0
}
});
The use case I am trying to address is :-
If there are 4 or more schedules, then fill the shape with GREEN else fill YELLOW.
I have already tried expression binding like :
fill: "{= ${data>/schedule}.length > 4 ? 'green' : 'yellow' }"
But that didn't give any result and filled the shape with the default BLACK color.
Is there some other way of getting it possible?
Also, is there a way we can configure Gantt shapes in XML views itself ratherer than doing all these configurations the in controller?
delete the attribute from your shape definition.
Before you define the oRectangle, put the following code segment:
sap.ui.define(["sap/gantt/shape/Rectangle"], function (Rectangle) {
var shapeRectangle = Rectangle.extend("sap.test.shapeRectangle");
shapeRectangle.prototype.getFill = function (oRawData) {
return oRawData.color;
};
return shapeRectangle;
}, true);
After that, you have to provide the property color to the order in your data model on the same level as startTime, endTime, etc...

New to OpenLayers, issue with zoom, attributes and advice with hit detection

I am new to client-side programming. Thus far I've been writing only asp and php based solutions. But now I need to retrieve data from json and plot on a map (I don't know how to do that yet, but this is later).
After days of searching, I think OpenLayers can give me what I need.
I have gone through the Examples on dev.openlayers site, (such as this one http://dev.openlayers.org/releases/OpenLayers-2.13.1/examples/vector-features-with-text.html), and also searched (and found some) solutions on stackoverflow, but they don't offer solutions to my problems).
Please view what I've done so far:
http://www.nusantech.com/bangkuujian/openlayer.html
The canvas.js is as follows:
// create some sample features
var Feature = OpenLayers.Feature.Vector;
var Geometry = OpenLayers.Geometry;
var features = [
new Feature(new Geometry.Point(-220, -60),attributes = { name: "Mercury",align: "cm",xOffset:10,yOffset:50 }),
new Feature(new Geometry.Point(-70, 120),attributes = { name: "Venus" }),
new Feature(new Geometry.Point(0, 0),attributes = { name: "Earth" }),
new Feature(new Geometry.Point(160, -100),attributes = { name: "Mars",align: "cm",xOffset:10,yOffset:50 })];
// create rule based styles
var Rule = OpenLayers.Rule;
var Filter = OpenLayers.Filter;
var style = new OpenLayers.Style({
pointRadius: 10,
strokeWidth: 3,
strokeOpacity: 0.7,
strokeColor: "#ffdd77",
fillColor: "#eecc66",
fillOpacity: 1,
label : "${name}",
fontColor: "#f0f0f0",
fontSize: "12px",
fontFamily: "Calibri, monospace",
labelAlign: "${align}",
labelXOffset: "${xOffset}",
labelYOffset: "${yOffset}",
labelOutlineWidth : 1
},
{
rules: [
new Rule({
elseFilter: true,
symbolizer: {graphicName: "circle"}
})
]
});
var layer = new OpenLayers.Layer.Vector(null, {
styleMap: new OpenLayers.StyleMap({'default': style,
select: {
pointRadius: 14,
strokeColor: "#e0e0e0",
strokeWidth: 5
}
}),
isBaseLayer: true,
renderers: ["Canvas"]
});
layer.addFeatures(features);
var map = new OpenLayers.Map({
div: "map",
layers: [layer],
center: new OpenLayers.LonLat(50, 45),
zoom: 0
});
var select = new OpenLayers.Control.SelectFeature(layer);
map.addControl(select);
select.activate();
What I have problems with:
Label offset
In the samples, the labels should offset from the centre by labelXOffset: "(xvalue)", labelYOffset: "(yvalue)", but this is not happening in my page. Is there something I forgot?
Zoom-in
When I click the + button on the map, all the features look like they are zoomed in, however, the sizes of the features stay the same. How do I enlarge the features (circles) too?
Hit Detection
i) When I click on a circle, it is selected as designed. However, is it possible when I select a circle, I also change the right side (now there is a red "text here") and fill it up with html? Can you show me an example how to change the red "text here" to the label-name of the selected circle with a different colour?
ii) Secondly, after I select a circle, how do I add a label under all the other circles denoting the distance between each circle and the selected circle?
Thank you in advance, hopefully these questions are not too much.
I have another question about retrieving an array of coordinates from json to plot the circles, but I will do more research on that. If you can point me in the right direction with regards to this, it would be much appreciated too.
I know how to do them server-side asp or php, but client side is very new to me. However client-side can do all of this much-much faster and can reduce a lot of load.
Cheers,
masCh
I think I have managed to most of it.
Labels not offsetting
Not sure what I did, but I declared a WMS layer and made a few changes to offset and now it is offsetting correctly.
var wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://hendak.seribudaya.com/starmap.jpg",
{
layers: "modis,global_mosaic",
}, {
opacity: 0.5,
singleTile: true
});
var context = {
getSize: function(feature) {
return feature.attributes["jejari"] / map.getResolution() * .703125;
}
};
var template = {
pointRadius: "${getSize}", // using context.getSize(feature)
label : "\n\n\n\n${name}\n${jarak}",
labelAlign: "left",
labelXOffset: "${xoff}",
labelYOffset: "${yoff}",
labelOutlineWidth : 0
};
var style = new OpenLayers.Style(template, {context: context});
And I declared xoff & yoff under new OpenLayers.Geometry.Point(x,y), { jejari:5, xoff: -10, yoff: -15 }
2) Zoom in on point features.
This was a weird problem. Anyway, I declared a radius called jejari as in the code above next to xoff and yoff. Then modified pointRadius from a static number to "${getSize}" And then added the getSize function to var template which retrieves the current radius. I think that was all I did for that. But the labels were running all over the place, I still haven't solved that.
3) Hit detection and changing another in html
This adds what happens to the once a point feature has been selected
layer.addFeatures(features);
layer.events.on({ "featureselected": function(e) {
kemasMaklumat('maklumat', "<FONT FACE='Calibri' color='#f0f0f0' size=5><center>"+
e.feature.attributes.name+
"<p>This is displayed text when a feature has been selected";
maklumat.style.color="black";
layer.redraw();
}
});
map.addLayers([layer]);
And in the html the and the kemasMaklumat function is declared as
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<td valign="top"><div id="maklumat" style="border-radius:25px; background-color:#000000;box-shadow: 8px 8px 4px #686868;">
Write Something Here<P>
</div></td>
The second part of this question was changing the labels of all the UNselected features, i.e. modifying attributes of all features that weren't the selected one. To do this, I added a for loop through all the features and check if it has the same label as the feature that was selected, this was done under the layer.events.on "featureselected" as was done in the above part 1 of this question.
layer.addFeatures(features);
layer.events.on({ "featureselected": function(e) {
kemasMaklumat('maklumat', "<FONT FACE='Calibri' color='#f0f0f0' size=5><center>"+
e.feature.attributes.name+
"<p>This is displayed text when a feature has been selected";
maklumat.style.color="black";
for (var i = 0, l = layer.features.length; i < l; i++) {
var feature = layer.features[i];
if (feature.attributes.name!=e.feature.attributes.name) {
feature.attributes.name="I was not selected"; }}
layer.redraw();
}
});
map.addLayers([layer]);

Openlayers - Draw String on Map

Im trying to draw a String/Character on a layer in Openlayers (eg displaying a Route --> draw description or floor number near the Route).
Problem: It is possible to add a Label to a Openlayers.Vector, but my Application has one Vector with multiple geometries in it, which should be rendered with a different String each.
Maybe there exists some Geometry like this: layer.addFeature(new Openlayers.StringGeometry("text", x,y) or so. I couldnt find anything.
Can someone give me a hint?
To add custom text label to the features of Vector layer, I suggest the following:
1) add StyleMap to your Vector layer as such:
var vectorLayer = new OpenLayers.Layer.Vector("Vector",
{
styleMap: new OpenLayers.StyleMap(
{
label : "${labelText}",
fontColor: "blue",
fontSize: "12px",
fontFamily: "Courier New, monospace",
fontWeight: "bold",
labelAlign: "lc",
labelXOffset: "14",
labelYOffset: "0",
labelOutlineColor: "white",
labelOutlineWidth: 3
})
});
note that labelText in this style map says that text for this label will be taken from corresponding feature attribute.
2) For each feature you add to your layer specify the attributes having labelText defined:
var features = [];
var pt = new OpenLayers.Geometry.Point(0, 0);
features.push(new OpenLayers.Feature.Vector(pt, {labelText: "This is my label"}));
vectorLayer.addFeatures(features);
The only limitation with this solution is that you will have to add feature for each point and not able to use OpenLayers.Geometry.MultiPoint.

Categories

Resources