OpenLayers, styling order of your features

When working with maps and geographical information systems styling features is very important, on one hand it can make your map more flashy and on the other it can help to classify or organize your features visually.For example, in a map where you show the most populated cities of the world you can use circles with different color and radius.

OpenLayers offers the option to style our features in different ways:

  • using a style structure for the whole layer
  • styling a concrete feature

The order applying these style go from "out" to "in", that is, given a feature first is applied the layer style and later the concrete style the feature could have. And to show this nothing better than an example.

Supposing we have a Vector layer with some circles:

var vectorLayer = new OpenLayers.Layer.Vector("Vector"); // Create 50 random features, and give them a "type" attribute that // will be used to style them by size. var features = new Array(50); for (var i=0; i<features.length; i++) { features[i] = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point( (360 * Math.random()) - 180, (180 * Math.random()) - 90 ), { type: 5 + parseInt(5 * Math.random()) } ); } vectorLayer.addFeatures(features);

Now we define a layer style which applied to the layer and a feature style applied directly to a concrete feature:

var myStyles = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ pointRadius: 3, // sized according to type attribute fillColor: "#ff5566", strokeColor: "#ff9933", strokeWidth: 2, graphicZIndex: 1 }) }); vectorLayer.styleMap = myStyles; features[0].style = { pointRadius: 9, // sized according to type attribute fillColor: "#225566", strokeColor: "#ff9933", strokeWidth: 4, graphicZIndex: 1 };

As we expect the result is:

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.