I try to make a choropleth map with OpenLayers3 and a GeoJson generate in a javascript .
I want to use the properties of my GeoJson for make this map.
For Example, if I've a city with properties ["name"='1']
and a city with properties ["name"='2']
I want to have blue color for the '1' and red color for the '2'.
I found on the internet, how to make this map with OpenLayers2 ([Example for make a choropleth map with OL2][1])
but I don't find the equivalence in OL3 . The code with OL2 look like :
var subteStyleMap = new OpenLayers.StyleMap({
'strokeWidth': 4
});
var lookup = {
"1": {strokeColor: "#46C7FA"},
"2": {strokeColor: "#E81D1A"}
}
subteStyleMap.addUniqueValueRules("default", "number", lookup);
var geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
projection: new OpenLayers.Projection("EPSG:4326"),
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "generation_geojson2.php",
format: new OpenLayers.Format.GeoJSON()
}),
styleMap: subteStyleMap
});
I started the adaptation but I don't find the equivalence for 'addUniqueValueRules'
var lookup = {
"1": {strokeColor: "#46C7FA"},
"2": {strokeColor: "#E81D1A"}
}
subteStyleMap.addUniqueValueRules("default", "number", lookup);
var vector_arret_tad = new ol.layer.Vector
({
source: new ol.source.GeoJSON({ url: 'generation_geojson2.php',defaultProjection :'EPSG:4326', projection: 'EPSG:3857'}),
name: 'City',
style: subteStyleMap
});
What is the OL3 equivalence of this code, or another solution for this problem?
You need to use a style function. A style function is a function that takes a feature as an argument and returns an array of style object.
In your case, it will look like this:
var lookup = {
"1": [new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#46C7FA"
})
})],
"2": [new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#E81D1A"
})
})]
};
var vectorLayer = new ol.layer.Vector({
// …
style: function(feature, resolution) {
return lookup[feature.get('number')];
}
});
See http://openlayers.org/en/master/examples/vector-layer.html for an example that uses a style function to add labels to polygons.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.