Place label on created polygon

Topics: SharpMap v0.9 / v1.x
Oct 8, 2012 at 4:47 PM

This simple code bellow draws polygon

Collection<SharpMap.Geometries.Point> vertices = new Collection<SharpMap.Geometries.Point>();
SharpMap.Geometries.Point currentPoint = _sharpMap.ImageToWorld(p1);
vertices.Add(currentPoint);

currentPoint = _sharpMap.ImageToWorld(p2);
vertices.Add(currentPoint);

currentPoint = _sharpMap.ImageToWorld(p3);
vertices.Add(currentPoint);

currentPoint = _sharpMap.ImageToWorld(p4);
vertices.Add(currentPoint);

currentPoint = _sharpMap.ImageToWorld(p1);
vertices.Add(currentPoint);

SharpMap.Geometries.LinearRing linRing = new SharpMap.Geometries.LinearRing(vertices);
SharpMap.Geometries.Polygon poly = new SharpMap.Geometries.Polygon(linRing);

VectorLayer region = new VectorLayer("reg");
region.DataSource = new SharpMap.Data.Providers.GeometryProvider(poly);
_sharpMap.Layers.Add(region);

 

Is there a way to place a custom label inside polygon created like this? How to set dataSource for this layer to be drawn w.r.t. polygon's coordinates?

Coordinator
Oct 9, 2012 at 8:36 AM

If you want to do labeling, you need to use GeometryFeatureProvider. To use that, you need to first create a FeatureDataTable

var fdt = new SharpMap.Data.FeatureDataTable();
fdt.Columns.Add(new System.Data.DataColumn("id", typeof(uint));
fdt.Columns.Add(new System.Data.DataColumn("label", typeof(string), 50));

After that you need to add/load a FeatureDataRow

var fdr = (SharpMap.Data.FeatureDataRow)fdt.NewRow();
fdr.ItemsArray = new object[] { 1, "Beautiful polygon" };
fdr.Geoometry = ;
fdt.AddRow(fdr);

Now you can create the provider, setup layers and add them to the map

var p = new SharpMap.Data.Providers.GeometryFeatureProvider(fdt);
var vl = new SharpMap.Layers.VectorLayer("vlayer", p);
var ll = new SharpMap.Layers.LabelLayer("llayer");
ll.DataSource = p;
ll.LabelColumn = "label";

//Apply some styling here!
//...
_sharpMap.Layers.Add(vl);
_sharpMap.Layers.Add(ll);

Note: there may be typos, the code has not seen a compiler

Hth FObermaier

Oct 9, 2012 at 11:12 AM

Thanks FObermaier, it worked :)