Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 =;
         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
share|improve this question
up vote 8 down vote accepted

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: ""
var gmlOptionsIn = OpenLayers.Util.extend(
    OpenLayers.Util.extend({}, gmlOptions)

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

var features =;

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, {},['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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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