[OpenLayers-Dev] Random Colors on Vector Features?

Tim Schaub tschaub at openplans.org
Mon Mar 3 00:44:24 EST 2008


Hey-

Christopher Schmidt wrote:
> I have a set of vector features. Each time I create a new feature, I
> want that feature to be styled such that it has a random color, chosen
> from a list of colors supplied by me. 
> 
> I see a couple of examples for 'unique style value' stuff, but that
> requires some unique attribute on my feature; I want to serialize the
> features later, so I don't want bogus attributes attached to them.
> 
> Can I set a Style() object directly on the feature with my fillColor
> specified? Do I have to do something else? 

     var colors = ["red", "orange", "yellow", "green", "blue", "purple"];
     var features = new Array(20);
     var x, y, fill;
     for(var i=0; i<20; i++) {
         x = Math.random() * 360 - 180;
         y = Math.random() * 180 - 90;
         fill = colors[Math.round((colors.length - 1) * Math.random())];
         features[i] = new OpenLayers.Feature.Vector(
             new OpenLayers.Geometry.Point(x, y), null,
             {fillColor: fill, pointRadius: 5}
         );
     }

Setting a symbolizer directly on a feature still works.

In the future, I think it would be good to encourage the use of 
FeatureId rules.  This could be facilitated by having layer.addFeature 
(to be written) optionally take a symbolizer.  If you specify a 
symbolizer when adding a feature to the layer, the layer would create a 
FeatureId rule for the corresponding feature (and add that rule to its 
styleMap).

It might also make sense to have destroyFeatures remove the FeatureId 
rules for the given features from its styleMap.

I'm curious about your use case.  I don't have a good idea how common it 
is to want to style a feature in a way that has nothing to do with its 
attributes.

Tim

> 
> Regards,




More information about the Dev mailing list