Different colors for each feature of a collection of features - openlayers-3

I've uploaded a geojson file in my map with openlayers 3. The geojson file is a FeatureCollection with 5 features of type LineString.
How can I color each feature differently to distinguish my paths?
If I add the color to the style of the geojson file this is not read and if I add color to stroke, all the features are colored in a single color.
Below I add the code.
Thanks.
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: 'http://localhost/joggo_wp/percorsi.geojson'
}),
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#ff000",
width: 2.5,
})
}),
});
FILE GEOJSON:
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4326" } },
"features": [
{ "type": "Feature", "properties": { "ID": 1.0, "LUNGH_M": 1970.0, "NOME": "Percorso 1", "PARTENZA": "Via del Poggio Imperiale 4", "ARRIVO": "Via di S. Leonardo 59n", "LUNGHEZZA": "1,97 km" }, "style": { "color": "#ff0000" }, "geometry": { "type": "LineString", "coordinates": [ [ 11.24203700040032, 43.759969754752376 ], [ 11.247204649917521, 43.750208064502473 ], [ 11.247446659153409, 43.750240561464494 ], [ 11.247746238597509, 43.750179530458503 ], [ 11.247960306028226, 43.750118937742307 ], [ 11.248108264989046, 43.749966781403657 ], [ 11.248240378523741, 43.749814084940027 ], [ 11.248897533371567, 43.75006527742493 ], [ 11.249140299088037, 43.750277668555015 ], [ 11.250198620263028, 43.751078552926899 ], [ 11.250259518649738, 43.751623211022611 ], [ 11.250562891152564, 43.751940055106814 ], [ 11.250844806161599, 43.752116454510677 ], [ 11.250976903611187, 43.752184285854881 ], [ 11.251025276742347, 43.752394633135999 ], [ 11.251095944135562, 43.752551715399683 ], [ 11.252075754111447, 43.753064192693351 ], [ 11.252260569522404, 43.753162663730734 ], [ 11.252298216347477, 43.753302788154329 ], [ 11.252042422884459, 43.753607171300693 ], [ 11.252089750740879, 43.754005360713535 ], [ 11.252046702595303, 43.754152945071198 ], [ 11.251940462780629, 43.754342861090443 ], [ 11.251887408111035, 43.754762904036816 ] ] } },
.........

You need to create a style function to handle such cases.
So make your style function:
var styleFunction = function(feature) {
console.log(feature);
//now you can use any property of your feature to identify the different colors
//I am using the ID property of your data just to demonstrate
var color;
if (feature.get("ID")==1){
color = "red";
} else if (feature.get("ID")==2){
color = "green";
} else {
color = "black";
}
var retStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: color,
width: 5
})
});
return retStyle;
};
And then assign this function to the style of your vector layer
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON(),
url: 'http://localhost/joggo_wp/percorsi.geojson'
}),
style: styleFunction
});
here is a fiddle

Related

Change colour of buffers in openlayers

I have the following JS code to create a 1 mile buffer in Openlayers using JSTS. However, I'd like to add 2 or 3 buffers but change the colour from the default for easier viewing.
So far, I've tried this as this styling as changed the fill/stroke of my points before
var source = new ol.source.Vector();
fetch('http://18.207.139.64:8080/geoserver/egm715/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=egm715:Mid_Ulster1&' +
'outputFormat=application/json&srsname=EPSG:3857').then(function(response) {
return response.json();
}).then(function(json) {
var format = new ol.format.GeoJSON();
var features = format.readFeatures(json, {featureProjection: 'EPSG:3857'});
var parser = new jsts.io.OL3Parser();
for (var i = 0; i < features.length; i++) {
var feature = features[i];
// convert the OpenLayers geometry to a JSTS geometry
var jstsGeom = parser.read(feature.getGeometry());
// create a buffer of 1 mile =1609 metres
var buffered = jstsGeom.buffer(1609);
// convert back from JSTS and replace the geometry on the feature
feature.setGeometry(parser.write(buffered));
}
source.addFeatures(features);
});
var buffer1 = new ol.layer.Vector({
source: source,
title: 'Mid Ulster Buffer - 1 mile',
visible: false,
style: new ol.style.Style(
{
image: new ol.style.Circle(
{
stroke: new ol.style.Stroke(
{
color: [0, 102, 77],
width: 2
}
),
fill: new ol.style.Fill(
{
color: [230, 255, 255, 0.6]
}
)
}
)
}
)
});
However, the default colour remains - is there any way I can change it?
As #Mike indicated in his comment: "The image option in ol.style.Style is used to style point features with an icon or regular shapes such as a circle. Your buffered geometry is a polygon, and is styled by stroke and fill options of ol.style.Style"
Change the style:
style: new ol.style.Style({
image: new ol.style.Circle({
stroke: new ol.style.Stroke({
color: [0, 102, 77],
width: 2
}),
fill: new ol.style.Fill({
color: [230, 255, 255, 0.6]
})
})
})
To remove the image: new ol.styld.Circle, something like:
var vectorLayer = new ol.layer.Vector({ // VectorLayer({
source: source,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3,
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.3)',
}),
}),
});
code snippet
html,
body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
.map {
height: 100%;
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSTS Integration</title>
<link rel="stylesheet" href="https://openlayers.org/en/v6.5.0/css/ol.css" type="text/css">
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL,TextDecoder"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/build/ol.js"></script>
<script src="https://unpkg.com/jsts#2.3.0/dist/jsts.min.js"></script>
<style>
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var json = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "FoodOutlets-MidUlst1.1",
"geometry": {
"type": "Point",
"coordinates": [-760868.77651775, 7266893.59283424]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.2",
"geometry": {
"type": "Point",
"coordinates": [-745762.5639359, 7273034.00676835]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.3",
"geometry": {
"type": "Point",
"coordinates": [-746154.82706286, 7273335.72201827]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.4",
"geometry": {
"type": "Point",
"coordinates": [-744607.30629421, 7255093.16775183]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.5",
"geometry": {
"type": "Point",
"coordinates": [-745202.69041239, 7255413.35399374]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.6",
"geometry": {
"type": "Point",
"coordinates": [-753889.58828371, 7266121.43420011]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.7",
"geometry": {
"type": "Point",
"coordinates": [-753078.05077876, 7267405.03419487]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.8",
"geometry": {
"type": "Point",
"coordinates": [-797828.64640079, 7249092.54222032]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.9",
"geometry": {
"type": "Point",
"coordinates": [-753881.35356931, 7266025.39133859]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.10",
"geometry": {
"type": "Point",
"coordinates": [-742327.05477715, 7302434.75328766]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.11",
"geometry": {
"type": "Point",
"coordinates": [-750757.26468702, 7294103.95069428]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.12",
"geometry": {
"type": "Point",
"coordinates": [-742442.85453496, 7302225.99299248]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.13",
"geometry": {
"type": "Point",
"coordinates": [-750678.90941561, 7293250.62728349]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.14",
"geometry": {
"type": "Point",
"coordinates": [-751029.88000637, 7293128.14558216]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.15",
"geometry": {
"type": "Point",
"coordinates": [-750678.90941561, 7293250.62728349]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.16",
"geometry": {
"type": "Point",
"coordinates": [-750757.26468702, 7294103.95069428]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.17",
"geometry": {
"type": "Point",
"coordinates": [-743083.01564625, 7280176.20812626]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.18",
"geometry": {
"type": "Point",
"coordinates": [-750837.75665786, 7294119.26420537]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.19",
"geometry": {
"type": "Point",
"coordinates": [-750757.26468702, 7294103.95069428]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.20",
"geometry": {
"type": "Point",
"coordinates": [-750790.13706862, 7294411.61511293]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.21",
"geometry": {
"type": "Point",
"coordinates": [-751029.88000637, 7293128.14558216]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.22",
"geometry": {
"type": "Point",
"coordinates": [-729059.04788702, 7288230.5536544]
},
"geometry_name": "the_geom",
"properties": {}
}, {
"type": "Feature",
"id": "FoodOutlets-MidUlst1.23",
"geometry": {
"type": "Point",
"coordinates": [-771157.83824017, 7283468.51757007]
},
"geometry_name": "the_geom",
"properties": {}
}, ],
"totalFeatures": 140,
"numberMatched": 140,
"numberReturned": 140,
"timeStamp": "2021-03-02T05:15:46.157Z",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:EPSG::3857"
}
}
};
var format = new ol.format.GeoJSON();
var features = format.readFeatures(json, {
featureProjection: 'EPSG:3857'
});
var source = new ol.source.Vector(); // VectorSource();
var parser = new jsts.io.OL3Parser();
parser.inject(
ol.geom.Point,
ol.geom.LineString,
ol.geom.LinearRing,
ol.geom.Polygon,
ol.geom.MultiPoint,
ol.geom.MultiLineString,
ol.geom.MultiPolygon
);
for (var i = 0; i < features.length; i++) {
var feature = features[i];
// convert the OpenLayers geometry to a JSTS geometry
var jstsGeom = parser.read(feature.getGeometry());
// create a buffer of 1 mile =1609 metres adjusted for the projection
var buffered = jstsGeom.buffer(1609 / ol.proj.getPointResolution('EPSG:3857', 1, ol.extent.getCenter(feature.getGeometry().getExtent())));
// create a buffer of 40 meters around each line
// var buffered = jstsGeom.buffer(1000);
// convert back from JSTS and replace the geometry on the feature
feature.setGeometry(parser.write(buffered));
}
source.addFeatures(features);
var vectorLayer = new ol.layer.Vector({ // VectorLayer({
source: source,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 3,
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.3)',
}),
}),
});
var rasterLayer = new ol.layer.Tile({ // TileLayer({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: ol.proj.fromLonLat([126.979293, 37.528787]),
zoom: 15,
}),
});
map.getView().fit(source.getExtent());
</script>
</body>
</html>

With GetJSON, I lose the properties

With this file "segment.geojson", I draw a red segment of thickness 20 :
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"stroke": "#ff0000",
"stroke-width": 20,
"stroke-opacity": 1
},
"geometry": {
"type": "LineString",
"coordinates": [[-3,48],[7,45]]
}
}
]
}
and with getJSON I display it on my map:
<body>
<div id="viewerDiv"></div>
<script>
window.onload= function() {
var map = L.map("viewerDiv").setView([50,50],5) ;
L.tileLayer(...blabla...).addTo(map);
var segment = '';
$.getJSON("segment.geojson", {dataType: "json"}, function (data) {
segment = new L.GeoJSON(data);
map.fitBounds(segment.getBounds());
})
.done(function () {
segment.addTo(map);
});
}
</script>
</body>
but it is blue and thick 1 !!! Can anyone help me? thank you in advance, JLC
The source is here: https://cavaliers23.fr/iti/ign/test_couleur.html
You are using the wrong definition. You should pass the style as a second argument.
$.getJSON("segment.geojson", { dataType: "json" }, function (data) {
segment = new L.GeoJSON(data, {
style: {
color: "#ff0000",
weight: 20,
opacity: 0.65,
},
});
You can also pass individual styles to features using the properties field
"features": [
{
"type": "Feature",
"properties": {
"color": "blue"
},
"geometry": {
"type": "LineString",
"coordinates": [
[-3, 48],
[7, 45]
]
}
},
{
"type": "Feature",
"properties": {
"color": "red"
},
"geometry": {
"type": "LineString",
"coordinates": [
[-33, 48],
[7, 45]
]
}
}
$.getJSON("segment.geojson", { dataType: "json" }, function (data) {
segment = new L.GeoJSON(data, {
style: (f) => {
switch (f.properties.color) {
case "red":
return {
color: "#ff0000",
weight: 20,
opacity: 0.65,
};
case "blue":
return {
color: "#0000ff",
weight: 20,
opacity: 0.65,
};
}
},
});

Change coordinates precision while serializing geodjano objects

I have a GeoDjango polygon model as below
class PolygonFeature(models.Model):
shapefile = models.ForeignKey(Shapefile,
on_delete=models.CASCADE, related_name='polygon_shp')
geom = models.PolygonField(srid=4326, blank=True, null=True)
def __str__(self):
return str(self.shapefile.filename) + "-" + str(self.pk)
I am adding polygon to model via LayerMapping in which out is the shapefile
mapping = {
'shapefile':{'id':'survey_pk'},
'geom': geom,
}
lm = LayerMapping(model, out, mapping, transform=transform, encoding='iso-8859-1')
lm.save(verbose=False)
I need to change coordinates precision while serializing polygon object geometry to GeoJSOn
feat = PolygonFeature.objects.filter(shapefile=obj)
json_obj = serialize('geojson', feat)
Current
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"name": "EPSG:4326"
},
"features": [
{
"type": "Feature",
"properties": {
"shapefile": 53,
"pk": "45269"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
75.6083423241,
31.315054275
],
[
75.5543398801,
31.30543373742
],
[
75.5970812345,
31.2980635331
],
[
75.6543504465,
31.30345354185
],
[
75.6035348241,
31.315035375
]
]
]
}
}
]
}

HighCharts not displaying series data

I have a timeseries data which I am trying to display with Highstocks:
Here is the data:
{
"title": {
"text": "My Graph"
},
"series": [
[
{
"name": "Future Index Longs",
"data": [
[
"2019-02-05",
104516
],
[
"2019-02-06",
127260
],
[
"2019-02-07",
156291
],
[
"2019-02-08",
167567
]
]
}
],
[
{
"name": "Future Index Longs",
"data": [
[
"2019-02-05",
21
],
[
"2019-02-06",
0
],
[
"2019-02-07",
1263
],
[
"2019-02-08",
12
]
]
}
],
[
{
"name": "Future Index Longs",
"data": [
[
"2019-02-05",
33873
],
[
"2019-02-06",
61093
],
[
"2019-02-07",
43125
],
[
"2019-02-08",
41928
]
]
}
],
[
{
"name": "Future Index Longs",
"data": [
[
"2019-02-05",
47542
],
[
"2019-02-06",
55084
],
[
"2019-02-07",
75256
],
[
"2019-02-08",
77786
]
]
}
],
[
{
"name": "Future Index Longs",
"data": [
[
"2019-02-05",
185952
],
[
"2019-02-06",
243437
],
[
"2019-02-07",
275935
],
[
"2019-02-08",
287293
]
]
}
]
]
}
The graph is empty and no data is displayed. What am I doing wrong?
Sorry to add this filler here but I am required to add more text to post this question and since this is a pretty simple question, I don't have much to add.
You have the wrong format on your series, it should be an array of objects.
Like this: series: [{ ... }, { ... }]
Check this fiddle: https://jsfiddle.net/wg1vnyzp/1/
To have a chart with datetime axes in Highcharts you have to pass the X value as the timestamp in milliseconds since 1970.
Highstock example:
https://jsfiddle.net/BlackLabel/f0rsz6cd/1/
Note that in Highcharts you have to define xAxis.type as datetime like that:
xAxis: {
type: 'datetime'
}
Highcharts demo:
https://jsfiddle.net/BlackLabel/kas2oywp/
API reference:
https://api.highcharts.com/highcharts/series.line.data.x
https://api.highcharts.com/highcharts/xAxis.type

Show and Hide Features of layers openlayers 3

I am trying to hide Feature of a layer from jason where I define the feature by category. I tried Jonatas Walker method but my code is different not working http://jsfiddle.net/jonataswalker/z10de36z/ but my code is different so not working
Below is my json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Missing Person",
"src": "resources/icon.png",
"category": "cat1"
},
"geometry": {
"type": "Point",
"coordinates": [-0.45755, 51.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Wanted",
"src": "resources/icon.png",
"category": "cat1"
},
"geometry": {
"type": "Point",
"coordinates": [-0.12755, 52.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Missing 1",
"src": "resources/Blue_pointer.png",
"category": "cat2"
},
"geometry": {
"type": "Point",
"coordinates": [-1.12755, 52.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Wanted 3",
"src": "resources/icon.png",
"category": "cat1"
},
"geometry": {
"type": "Point",
"coordinates": [-2.12755, 53.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Wanted 7",
"src": "resources/icon.png",
"category": "cat1"
},
"geometry": {
"type": "Point",
"coordinates": [-0.1287, 53.507222]
}
},
{
"type": "Feature",
"properties": {
"name": "Wanted 9",
"src": "resources/Blue_pointer.png",
"category": "cat2"
},
"geometry": {
"type": "Point",
"coordinates": [-3.12755, 50.907222]
}
},
{
"type": "Feature",
"properties": {
"name": "Missing 8",
"src": "resources/Blue_pointer.png",
"category": "cat2"
},
"geometry": {
"type": "Point",
"coordinates": [-3.12755, 51.907222]
}
},
{
"type": "Feature",
"properties": {
"name": "Missing 18",
"src": "resources/Blue_pointer.png",
"category": "cat2"
},
"geometry": {
"type": "Point",
"coordinates": [-4.12755, 51.907222]
}
}
]
}
Openlayer code
var styleFunction1 = function(feature) {
var styles = {
'Point': [
new ol.style.Style({
image: new ol.style.Icon({
src: feature.get('src'),
anchor: [0.5, 1]
})
})],
'LineString': [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'gray',
width: 5
})
})]
};
return styles[feature.getGeometry().getType()];
};
vector = new ol.layer.Vector({
source: new ol.source.Vector({
projection : 'EPSG:4326',
format: new ol.format.GeoJSON(),
url: 'resources/multipoint.geojson'
}),
style: styleFunction1
});
map = new ol.Map({
target: target,
layers: [bingMapsRoad,myPetrolPlan,vector],
view: new ol.View({
center: ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326', 'EPSG:3857'),
loadTilesWhileAnimating: true,
loadTilesWhileInteracting: true,
zoom: 6
}),
controls: ol.control.defaults({ attribution: false }),
loadTilesWhileInteracting: true
});
To Hide I am trying something like
hideVectorLayer: function () {
var abc = ConnectWebMap;
var featureCount = vector.getSource().getFeatures();
var featureCat = feature.get('category');
console.log(featureCat);
featureCount.forEach(function(feature) {
if(feature){
if(featureCat == 'cat1'){
console.log('a');
}
}
});
}
You can remove from the VectorSource using removeFeature method
you can make another layer ( a temporary one ) where you copy the features from the desired category and display it while setting the visibility of your main layer to false:
var tmp=new ol.layer.vector({ source : new ol.source.Vector()});
hideVectorLayer: function () {
var abc = ConnectWebMap;
var featureCount = vector.getSource().getFeatures();
var featureCat = feature.get('category');
console.log(featureCat);
featureCount.forEach(function(feature) {
if(feature){
if(featureCat == 'cat1'){
tmp.getSource().getFeatures().push(feature);
}
}
});
tmp.setStyle(vector.getStyle()); // set the same style to the tmp layer
map.addLayer(tmp);// add it to the map
vector.setVisible(false); // set the vector layer visibility to false
}

Resources