Skip to content

Instantly share code, notes, and snippets.

@pagameba
Created October 8, 2014 12:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pagameba/671d63f7ee95e4ebe44b to your computer and use it in GitHub Desktop.
Save pagameba/671d63f7ee95e4ebe44b to your computer and use it in GitHub Desktop.
Create OL3 Style object(s) from object literals.
var styleMap = {
fill: function(obj) {
if (typeof obj == 'string' || Array.isArray(obj)) {
obj = { color: obj };
}
return new ol.style.Fill(obj);
},
stroke: function(obj) {
if (typeof obj == 'string' || Array.isArray(obj)) {
obj = { color: obj };
} else if (typeof obj == 'number') {
obj = { width: obj };
}
return new ol.style.Stroke(obj);
},
text: function(obj) {
if (typeof obj == 'string') {
obj = { text: obj };
}
if (obj.fill) {
obj.fill = styleMap.fill(obj.fill);
}
if (obj.stroke) {
obj.stroke = styleMap.stroke(obj.stroke);
}
return new ol.style.Text(obj);
},
circle: function(obj) {
if (obj.fill) {
obj.fill = styleMap.fill(obj.fill);
}
if (obj.stroke) {
obj.stroke = styleMap.stroke(obj.stroke);
}
return new ol.style.Circle(obj);
},
icon: function(obj) {
return new ol.style.Icon(obj);
},
image: function(obj) {
if (typeof obj.radius !== 'undefined') {
return styleMap.circle(obj);
}
return styleMap.icon(obj);
}
};
function makeStyle(styleSpec) {
if (Array.isArray(styleSpec)) {
return styleSpec.map(function(oneSpec) {
return makeStyle(oneSpec);
});
}
var obj = {};
Object.keys(styleSpec).forEach(function(key) {
var val = styleSpec[key];
if (styleMap[key]) {
obj[key] = new styleMap[key](val);
} else {
obj[key] = val;
}
});
return new ol.style.Style(obj);
}
var compoundStyle = makeStyle([{
stroke: {
color: [0, 0, 127, 0.15],
width: 8
},
zIndex: 1
}, {
fill: [203, 194, 185, 1],
stroke: [101, 95, 90, 1],
zIndex: 2
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment