Can I let the color of the GPX track be determined by values associated with each track point, e.g. elevation or speed? - colors

My gpx file already contains elevation information for each trkpt and I can augment this with a speed for each trkpt. I would like to represent the elevation or the speed at each trkpt by varying the color of the track. For instance: slow is blue, fast is red.
How can I do this?
And this probably means: Which files and functions in Openlayers do I have to change to do this?

You can try the ol/style/FlowLine of ol-ext to achieve this.
Using this style, you can change the with/color of the feature along the line using a function. This example show how to: http://viglino.github.io/ol-ext/examples/style/map.style.flowline2.html.
You just have to calculate the width (or color) along the feature geometry varying according the speed or altitude:
const flowStyle = new ol.style.FlowLine({
width: function(f, step) {
// calculate the with of the feature f at the given step
// step is the curvilinear abscissa between 0,1
// (0: first coordinate, 1: last one)
const width = ...
return width;
}
});
#+

You should go with a stylefunction for the vector layer:
https://openlayers.org/en/v4.6.5/apidoc/ol.html#.StyleFunction
This function is checked for each feature to be displayed on the vector layer and the related style can be set/returned programmatically. For example:
function gpxStyle(feature) {
var style = null;
if (feature.get("speed")>="100") {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'red'
})
})
});
}
else {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'blue',
width: 2
}),
fill: new ol.style.Fill({
color: 'blue'
})
})
});
}
return [style];
}
var gpxLayer = new ol.layer.Vector({
source: new ol.source.Vector(),
style: gpxStyle
});

Related

OpenLayers text label fuzzy

I have an issue with OpenLayers (v 6.14.1 from npm) where the text on the text label is rather fuzzy.
See the attached image. Compare the text labels with the text in the dialog to the right.
I create the map with pixelRatio: 1, but that shouldn't affect this (?)
const map = new Map({
target: div,
view: new View({
center: fromLonLat ([startLocation.lon, startLocation.lat]),
zoom: startLocation.zoom,
constrainResolution: true,
}),
pixelRatio: 1, //Important, otherwise tiles (WMS) with strange size will be requested
});
I create the text label thus:
export default function (feature, resolution, options) {
return new Text ({
font: 'Normal 14px serif', // Normal 14px Arial
text: getText (feature, resolution, options),
fill: new Fill ({ color: 'black' }),
stroke: new Stroke ({ color: 'white', width: 2 }),
offsetX: -12,
offsetY: -8,
textAlign: 'right',
textBaseline: 'bottom',
placement: 'point',
});
}
I've already tried other fonts (e.g. a sans-serif).
I did as #Mike suggested - see their comment under the question - here's the result:
I think the labels are now a fair bit sharper. Picture doesn't show this too well tho'.

Graph search for element by element's name in jointJS

I have a problem in Rappid/jointJS
I have in stencil.js 4 shapes(2 basic.Circle and 2 basic.Rect) with names START(basic.Circle), END(basic.Circle), Activity(basic.Rect) and Workitem( basic.Rect) and I want in my main.js from all my graph to get the basic shape with name(I mean with attrs text ) "Activity".
This is the Stencil description for "Activity" :
new joint.shapes.basic.Rect({ size: { width: 5, height: 3 },
attrs: {
rect: {
rx: 2, ry: 2, width: 50, height: 30,
fill: '#0000FF'
},
text: { text: 'Activity', fill: '#ffffff', 'font-size': 10,
stroke: '#000000', 'stroke-width': 0 }
}
}),
How wil I get it? The only way I can search in my graph so far is if a cell has type basic.Circle(use of get('type') === 'basic.Circle')). but with type Circle I have two items:Activity and Workitem.
Is it so difficult to search for the graph element with name : "Activity"?
Thank you in advance
You can obtain all the elements (except for links) from following method
var allElement = graph.getElements()
Next if you want to obtain elements with 'Activity' do as follows
var activityElements = [];
allElement.forEach(elem => {
var textVal = elem.attributes.attrs.text.text;
if(textVal !== undefined && textVal === 'Activity') {
activityElements.push(elem);
}
});
Now the activityElements array will contain all the elements you require.
I solved my problem by taking element data in JSON format:
_.each(this.graph.getElements(), function(element) {
if(element.attributes.attrs["text"]["text"] == "Activity"){
//alert("YEAHHHHHH");
}
});
you could use the api on element as well, element.attr('text') returns the text object from the shape: { text: 'Activity', fill: '#ffffff', 'font-size': 10,
stroke: '#000000', 'stroke-width': 0 }
You could also set an "id" attribute to your shape and use graph.getCell('id_name_goes_here'); which would be much simpler if you didn't mind adding an id field to each shape.

Fabricjs How to scale object but keep the border (stroke) width fixed

I'm developing a diagram tool based on fabricjs. Our tool has our own collection of shape, which is svg based. My problem is when I scale the object, the border (stroke) scale as well. My question is: How can I scale the object but keep the stroke width fixed. Please check the attachments.
Thank you very much!
Here is an easy example where on scale of an object we keep a reference to the original stroke and calculate a new stroke based on the scale.
var canvas = new fabric.Canvas('c', { selection: false, preserveObjectStacking:true });
window.canvas = canvas;
canvas.add(new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: '#faa',
originX: 'left',
originY: 'top',
stroke: "#000",
strokeWidth: 1,
centeredRotation: true
}));
canvas.on('object:scaling', (e) => {
var o = e.target;
if (!o.strokeWidthUnscaled && o.strokeWidth) {
o.strokeWidthUnscaled = o.strokeWidth;
}
if (o.strokeWidthUnscaled) {
o.strokeWidth = o.strokeWidthUnscaled / o.scaleX;
}
})
canvas {
border: 1px solid #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<canvas id="c" width="600" height="600"></canvas>
There is a property called: strokeUniform
Use it like this
shape.set({stroke: '#f55b76', strokeWidth:2, strokeUniform: true })
I have found what feels like an even better solution, works really well with SVG paths.
You can override fabricjs' _renderStroke method and add ctx.scale(1 / this.scaleX, 1 / this.scaleY); before ctx.stroke(); as shown below.
fabric.Object.prototype._renderStroke = function(ctx) {
if (!this.stroke || this.strokeWidth === 0) {
return;
}
if (this.shadow && !this.shadow.affectStroke) {
this._removeShadow(ctx);
}
ctx.save();
ctx.scale(1 / this.scaleX, 1 / this.scaleY);
this._setLineDash(ctx, this.strokeDashArray, this._renderDashedStroke);
this._applyPatternGradientTransform(ctx, this.stroke);
ctx.stroke();
ctx.restore();
};
You may also need to override fabric.Object.prototype._getTransformedDimensions to adjust the bounding box to account for the difference in size.
Also a more complete implementation would probably add a fabric object property to conditionally control this change for both overridden methods.
Another way is to draw a new object on scaled and remove the scaled one.
object.on({
scaled: function()
{
// store new widht and height
var new_width = this.getScaledWidth();
var new_height = this.getScaledHeight();
// remove object from canvas
canvas.remove(this);
// add new object with same size and original options like strokeWidth
canvas.add(new ...);
}
});
Works perfect for me.

openlayers polygon change color

i'm using OL3 and javascript to draw several polygon on a map. Each polygon came from a database in WKT format like "POLIGON((39 -9, ....))". I can draw them on the map but i want to change fill color of each one, but don't know how to do it.
Here is my code:
//WKTpoly -> this is my array of POLYLINES
var format = new ol.format.WKT();
var vectorArea = new ol.source.Vector({});
for (var i=0;i<WKTpoly.length;i++) {
var featureGeom = format.readFeature(WKTpoly[i]);
featureGeom.getGeometry().transform('EPSG:4326', 'EPSG:3857');
vectorArea.addFeature(featureGeom);
}
VectorMap = new ol.layer.Vector({
name: map,
source: vectorArea,
});
map.addLayer(VectorMap);
Well, after LessThanJake response and some more google search, i found the solution, i had to create a style and call setStyle() before addFeature():
(...)
var style = new ol.style.Style({
fill: new ol.style.Fill({
color: FillColor,
weight: 1
}),
stroke: new ol.style.Stroke({
color: LineColor,
width: 1
})
});
featureGeom.setStyle(style);
(...)
Thanks LessThanJake for pointing the right direction.
Or you can setup the layer to use a function as style
the function signature is
var makeStyle = function(feature,resolution) {
return [styles];
};
You can use this to manage style by feature and resolution (zoom level).
As the function is called at each feature render, you'll need to cache the style in a js object to gain performance.

How to rotate text with view using OpenLayers 3

I am developing a navigation application, which draws planned route on a map. Planned route consists of points connected with a line. Each point is labelled with distance and direction. When I initially draw the route on the map, I calculate text position in a way, where it doesn't interfere with the line - I use offsetX, offsetY and rotation style attributes. Unfortunately, when the map view is rotated, not of the mentioned attributes is changed - text is not rotated. Is there a way, how to rotate the text with the view, so it will remain on it's position relative to the point? I have already tried rotateWithView: true with both image and text parts.
My style is defined like:
return [new ol.style.Style({
image: new ol.style.Circle({
radius: 20,
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'black', width: 1})
}),
text: new ol.style.Text({
textAlign: "center",
textBaseline: "middle",
font: 'normal 1.5rem Arial',
text: "This is my text",
fill: new ol.style.Fill({color: 'black'}),
stroke: new ol.style.Stroke({color: 'black', width: 1}),
offsetX: 10,
offsetY: 15,
rotation: 0.3
})
})];
Update feature rotation on map view property change event.
map.getView().on('propertychange', function(event) {
textStyle.setRotation(this.getRotation());
mySource.changed();
});
var textStyle = new ol.style.Text({
// ...
});
var layer = new ol.layer.Vector({
source: mySource,
style: new ol.style.Style({
text: textStyle,
// ...
})
});

Resources