I'm reading a GML file from an URL. This file contains polygons. I would like to draw the polygons on a map, where each should have a different color. But all examples I found on the web so far seemed to be outdated and didn't work. Any Hints?

Here the parsing (that's the part that already works):

    var theParser = new OpenLayers.Format.GML();
    theParser.internalProjection = null;
    theParser.externalProjection = null;
    theParser.extractStyles      = false;
    theParser.extractAttributes  = true;
    var features = theParser.read(response.responseText);
         for(var i=0;i<features.length;i++)
            var feature = features[i]
       //Each feature is an instance of OpenLayers.Feature.Vector
           //Each has an attribte geometry, which is of type 
           //OpenLayers.Geometry.MultiPolygon and which contains an

Basically you need to specify the feature namespace or else OpenLayers cannot deserialize your GML. And use the appropriate version of GML Parser.

Here's a working Example

This is they important part:

var gmlOptions = {
    featureType: "feature",
    featureNS: "http://example.com/feature"
var gmlOptionsIn = OpenLayers.Util.extend(
    OpenLayers.Util.extend({}, gmlOptions)

var format = new OpenLayers.Format.GML.v3(gmlOptionsIn);

var features = format.read(strGML);

I'm still working on changing colors for each feature. Will update when i figure that one out.

UPDATE #2: Give each feature a different color:

Here's a way you can give them a different color:

Updated Working Example

var style = $.extend(true, {}, OpenLayers.Feature.Vector.style['default']); // get a copy of the default style
style.fillColor = "${getFillColor}";

var getRandomColor = function () {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 15)];
    return color;

var myStyleMap = new OpenLayers.StyleMap({
    "default": new OpenLayers.Style(style, {
        context: {
            getFillColor: function (feature) {
                return getRandomColor();

var gmlLayer = new OpenLayers.Layer.Vector("MyGMLLayer", {
    styleMap: myStyleMap

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.