Using SharpMap (2)

October 20th, 2007

Our previous post introduced SharpMap and how to use it in a C# program. We built a form and used a PictureBox control to display maps generated by SharpMap. We left off with a rather bland looking map of the world:

SharpMap Program

Adding Layer Styles

Adding colors to our countries layer is straightforward. In our form’s constructor, we simply define colors using the Style class:

 

countriesLayer.Style.Fill = Brushes.LightGreen;
countriesLayer.Style.EnableOutline = true;
countriesLayer.Style.Outline = Pens.DarkGreen;

 

We also switched the map’s background color:

 

_sharpMap.BackColor = Color.LightBlue;

 

Running the program now produces a better looking map:

SharpMap with Coloring

Adding Labels

SharpMap also allows for creating label layers to add to the map that display text from another layer’s attributes. In our example, we can display the names of the countries on the map using the following code:

 

SharpMap.Layers.LabelLayer labelLayer =
     new SharpMap.Layers.LabelLayer("Country Names");
labelLayer.DataSource = countriesLayer.DataSource;
labelLayer.LabelColumn = "NAME";
labelLayer.Style.CollisionDetection = true;
labelLayer.Style.CollisionBuffer = new SizeF(10, 10);
labelLayer.MultipartGeometryBehaviour =
     SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest;
labelLayer.Style.Font = new Font(FontFamily.GenericSansSerif, 8);
_sharpMap.Layers.Add(labelLayer);

 

In the code, we create a LabelLayer, assign it to the same data source as our countries layer, choose the field that contains the country names (“NAME”), and then define some additional properties. Enabling collision detection avoids some overlapping labels while the multi-part geometry behavior instructs SharpMap to label the largest polygon if a country has multiple shapes.

The final result is not perfect because there are just too many country names to display at once. Setting the collision buffer to 10,10 reduces the number of labels drawn but which country names are displayed is completely arbitrary.

SharpMap with Labels

When we add code to the zoom in button in the next post, overlapping labels will become less of an issue:

SharpMap with Labels

Continue to part 3