DotSpatial Tutorial 4
DotSpatial Tutorial 4
Teva ~ Veluppillai
Page 1
Teva ~ Veluppillai
Page 2
2.2) Change the compile option from .Net FrameWork 4 Client Profile to .Net FrameWork 4
This step is as same as the Tutorial # 1 step 2.2.
Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox.
This step is as same as the Tutorial # 1 step 3.
Step 4: Design the GUI. (Graphical User Interface)
Design the GUI as follows:
Teva ~ Veluppillai
Page 3
Panel1
Panel2
Panel3
Panel4
pnlOperation pnlLegend
pnlMap
pnlAttribut
s
e
Dock
Top
Left
Fill
Bottom
Note: Set the border style of the panels to Fixed Single (Optional)
2. Add a menu strip control on the pnlOperations. Menu should be contains the following menu items.
2.1) Main menu item: File, Shapefile Operations, Map Options, and Attribute Table Operations
2.2) Sub menu items:
Under File menu item create 3 sub menu items as follows: Load, Clear, Exit
Those implementations can be found in Tutorial 2.
Under the Shapefile Operations create the following sub menu items : Point , Polyline, Polygon
Teva ~ Veluppillai
Page 4
DotSpatial.Controls
DotSpatial.Data
DotSpatial.Symbology
DotSpatial.Topology
Teva ~ Veluppillai
Page 5
DotSpatial.Controls;
DotSpatial.Data;
DotSpatial.Symbology;
DotSpatial.Topology;
C#
//which type of shapefile is created
string shapeType;
#region Point ShapeFile class level variable
//the new point feature set
FeatureSet pointF = new FeatureSet(FeatureType.Point);
//the id of point
int pointID = 0;
//to differentiate the right and left mouse click
bool pointmouseClick = false;
#endregion
Teva ~ Veluppillai
Page 6
C#
private void createPointShapefileToolStripMenuItem_Click(object sender, EventArgs e)
{
//Change the cursor style
map1.Cursor = Cursors.Cross;
//set the shape type to the classlevel string variable
//we are going to use this variable in select case statement
shapeType = "Point";
//set projection
pointF.Projection = map1.Projection;
//initialize the featureSet attribute table
DataColumn column = new DataColumn("PointID");
pointF.DataTable.Columns.Add(column);
//add the featureSet as map layer
MapPointLayer pointLayer = (MapPointLayer)map1.Layers.Add(pointF);
//Create a new symbolizer
PointSymbolizer symbol = new PointSymbolizer(Color.Red,
DotSpatial.Symbology.PointShape.Ellipse, 3);
//Set the symbolizer to the point layer
pointLayer.Symbolizer = symbol;
//Set the legentText as point
pointLayer.LegendText = "point";
//Set left mouse click as true
pointmouseClick = true;
}
Teva ~ Veluppillai
Page 7
Teva ~ Veluppillai
Page 8
attributes.
else
{
//mouse right click
map1.Cursor = Cursors.Default;
pointmouseClick = false;
}
break;
Save a point shape file: Write the following code into SavePointShapeFileToolStripMenuItem_Click
event.
VB
Private Sub SavePointShapeFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles SavePointShapeFileToolStripMenuItem.Click
pointF.SaveAs("point.shp", True)
MsgBox("The point shapefile has been saved.")
Map1.Cursor = Cursors.Arrow
End Sub
C#
private void SavePointShapeFileToolStripMenuItem_Click(object sender, EventArgs e)
{
pointF.SaveAs("point.shp", true);
Teva ~ Veluppillai
Page 9
C#
Teva ~ Veluppillai
Page 10
C#
Teva ~ Veluppillai
Page 11
linemouseClick = true;
Teva ~ Veluppillai
Page 12
C#
case "line":
if (e.Button == MouseButtons.Left)
{
//left click - fill array of coordinates
//coordinate of clicked point
Coordinate coord = map1.PixelToProj(e.Location);
if (linemouseClick)
{
//first time left click - create empty line feature
if (firstClick)
{
//Create a new List called lineArray.
//This list will store the Coordinates
//We are going to store the mouse click coordinates into this array.
List<Coordinate> lineArray = new List<Coordinate>();
//Create an instance for LineString class.
//We need to pass collection of list coordinates
LineString lineGeometry = new LineString(lineArray);
//Add the linegeometry to line feature
IFeature lineFeature = lineF.AddFeature(lineGeometry);
//add first coordinate to the line feature
lineFeature.Coordinates.Add(coord);
//set the line feature attribute
Teva ~ Veluppillai
Page 13
}
else
{
//right click - reset first mouse click
firstClick = true;
map1.ResetBuffer();
}
break;
VB
Private Sub SavePolylineShapeFileToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles SavePolylineShapeFileToolStripMenuItem.Click
lineF.SaveAs("c:\MW\line.shp", True)
MsgBox("The line shapefile has been saved in C:\MW\")
Map1.Cursor = Cursors.Arrow
linemouseClick = False;
End Sub
C#
private void savePolylineShapefileToolStripMenuItem_Click(object sender, EventArgs e)
{
lineF.SaveAs("c:\\MW\\line.shp", true);
MessageBox.Show("The line shapefile has been saved in C:\\MW\\");
map1.Cursor = Cursors.Arrow;
linemouseClick = false;
} }
Teva ~ Veluppillai
Page 14
VB
#Region "Polygon shapefile class level variables"
'the polygon feature set
Dim polygonF As New FeatureSet(FeatureType.Polygon)
Dim polygonID As Integer = 0
Dim polygonmouseClick As Boolean = False
#End Region
C#
#region Polygon ShapeFile class level variables
FeatureSet polygonF = new FeatureSet(FeatureType.Polygon);
int polygonID = 0;
bool polygonmouseClick = false;
#endregion
Teva ~ Veluppillai
Page 15
C#
private void CreatePolygonShapeFileToolStripMenuItem_Click(object sender, EventArgs e)
{
//initialize polyline feature set
map1.Cursor = Cursors.Cross;
//set shape type
shapeType = "polygon";
//set projection
polygonF.Projection = map1.Projection;
//initialize the featureSet attribute table
DataColumn column = new DataColumn("PolygonID");
if (!polygonF.DataTable.Columns.Contains("PolygonID"))
{
Teva ~ Veluppillai
Page 16
Teva ~ Veluppillai
Page 17
C#
case "polygon":
if (e.Button == MouseButtons.Left)
{
//left click - fill array of coordinates
Coordinate coord = map1.PixelToProj(e.Location);
if (polygonmouseClick)
{
//first time left click - create empty line feature
if (firstClick)
{
//Create a new List called polygonArray.
//this list will store the Coordinates
//We are going to store the mouse click coordinates into this array.
List<Coordinate> polygonArray = new List<Coordinate>();
//Create an instance for LinearRing class.
//We pass the polygon List to the constructor of this class
LinearRing polygonGeometry = new LinearRing(polygonArray);
//Add the polygonGeometry instance to PolygonFeature
IFeature polygonFeature = polygonF.AddFeature(polygonGeometry);
//add first coordinate to the polygon feature
polygonFeature.Coordinates.Add(coord);
//set the polygon feature attribute
polygonID = polygonID + 1;
polygonFeature.DataRow["PolygonID"] = polygonID;
firstClick = false;
}
else
{
//second or more clicks - add points to the existing feature
IFeature existingFeature =
(IFeature)polygonF.Features[polygonF.Features.Count - 1];
existingFeature.Coordinates.Add(coord);
//refresh the map if line has 2 or more points
if (existingFeature.Coordinates.Count >= 3)
{
//refresh the map
Teva ~ Veluppillai
Page 18
polygonF.InitializeVertices();
map1.ResetBuffer();
}
}
else
{
//right click - reset first mouse click
firstClick = true;
}
break;
C#
private void SavePolygonShapeFileToolStripMenuItem_Click(object sender, EventArgs e)
{
polygonF.SaveAs("c:\\MW\\polygon.shp", true);
MessageBox.Show("The polygon shapefile has been saved.");
map1.Cursor = Cursors.Arrow;
polygonmouseClick = false;
}
Teva ~ Veluppillai
Page 19
Map1 mouse down event complete code: In the above examples the same event is used to implement
different shape functionalities. So, the following code is the complete code for Map1 mouse down event.
The following code shows the all different shape operations.
VB
Private Sub Map1_MouseDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles Map1.MouseDown
Select Case shapeType
Case "Point"
If e.Button = MouseButtons.Left Then
If (pointmouseClick) Then
'This method is used to convert the screen cordinate to map coordinate
'e.location is the mouse click point on the map control
Dim coord As Coordinate = Map1.PixelToProj(e.Location)
'Create a new point
'Input parameter is clicked point coordinate
Dim point As New DotSpatial.Topology.Point(coord)
attributes.)
Teva ~ Veluppillai
Page 20
Teva ~ Veluppillai
Page 21
C#
Teva ~ Veluppillai
Page 22
}
else
{
//mouse right click
map1.Cursor = Cursors.Default;
pointmouseClick = false;
}
break;
case "line":
if (e.Button == MouseButtons.Left)
{
//left click - fill array of coordinates
//coordinate of clicked point
Coordinate coord = map1.PixelToProj(e.Location);
if (linemouseClick)
{
//first time left click - create empty line feature
if (firstClick)
{
//Create a new List called lineArray.
//This list will store the Coordinates
//We are going to store the mouse click coordinates into this array.
Teva ~ Veluppillai
Page 23
}
else
{
//right click - reset first mouse click
firstClick = true;
map1.ResetBuffer();
}
break;
case "polygon":
if (e.Button == MouseButtons.Left)
{
//left click - fill array of coordinates
Coordinate coord = map1.PixelToProj(e.Location);
if (polygonmouseClick)
{
//first time left click - create empty line feature
if (firstClick)
{
//Create a new List called polygonArray.
//this list will store the Coordinates
//We are going to store the mouse click coordinates into this array.
Teva ~ Veluppillai
Page 24
}
else
{
//right click - reset first mouse click
firstClick = true;
}
break;
Teva ~ Veluppillai
Page 25
C#
private void ViewAttrbuteTableToolStripMenuItem_Click(object sender, EventArgs e)
{
//Declare a datatable
System.Data.DataTable dt = null;
if (map1.Layers.Count > 0)
{
MapPolygonLayer stateLayer = default(MapPolygonLayer);
stateLayer = (MapPolygonLayer)map1.Layers[0];
if (stateLayer == null)
{
MessageBox.Show("The layer is not a polygon layer.");
}
else
{
//Get the shapefile's attribute table to our datatable dt
dt = stateLayer.DataSet.DataTable;
//Set the datagridview datasource from datatable dt
dgvAttributeTable.DataSource = dt;
}
}
else
{
MessageBox.Show("Please add a layer to the map.");
}
}
Teva ~ Veluppillai
Page 26
Add a new column into the attribute table. In the following example the new column name is
"PercentMales"
VB
Private Sub CreateAColumInAttributeTableToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CreateAColumInAttributeTableToolStripMenuItem.Click
'Declare a datatable
Dim dt As DataTable
If Map1.Layers.Count > 0 Then
Dim stateLayer As MapPolygonLayer
stateLayer = TryCast(Map1.Layers(0), MapPolygonLayer)
If stateLayer Is Nothing Then
MessageBox.Show("The layer is not a polygon layer.")
Else
'Get the shapefile's attribute table to our datatable dt
dt = stateLayer.DataSet.DataTable
'Add new column
Dim column As New DataColumn("PercentMales")
dt.Columns.Add(column)
'calculate values
For Each row As DataRow In dt.Rows
Dim males As Double = row("males")
Dim females As Double = row("females")
Dim malesPercentage As Double = (males / (males + females)) * 100
row("PercentMales") = malesPercentage
Teva ~ Veluppillai
Page 27
C#
private void CreateAColumInAttributeTableToolStripMenuItem_Click(object sender, EventArgs e)
{
//Declare a datatable
System.Data.DataTable dt = null;
//check the layers
if (map1.Layers.Count > 0)
{
//Declare a mappolygon layer
MapPolygonLayer stateLayer = default(MapPolygonLayer);
//Assign the mappolygon layer from the map
stateLayer = map1.Layers[0] as MapPolygonLayer;
if (stateLayer == null)
{
MessageBox.Show("The layer is not a polygon layer.");
}
else
{
//Get the shapefile's attribute table to our datatable dt
dt = stateLayer.DataSet.DataTable;
//Add new column
DataColumn column = new DataColumn("PercentMales");
dt.Columns.Add(column);
//calculate values
foreach (DataRow row in dt.Rows)
{
double males = Convert.ToDouble(row["males"]);
double females = Convert.ToDouble(row["females"]);
double malesPercentage = (males / (males + females)) * 100;
row["PercentMales"] = malesPercentage;
}
//Set the datagridview datasource from datatable dt
dgvAttributeTable.DataSource = dt;
}
}
else
{
MessageBox.Show("Please add a layer to the map.");
}
}
Page 28
VB
Private Sub SaveTheColumInShapeFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles SaveTheColumInShapeFileToolStripMenuItem.Click
If Map1.Layers.Count > 0 Then
Dim stateLayer As MapPolygonLayer
stateLayer = TryCast(Map1.Layers(0), MapPolygonLayer)
If stateLayer Is Nothing Then
MessageBox.Show("The layer is not a polygon layer.")
Else
stateLayer.DataSet.Save()
End If
Else
MessageBox.Show("Please add a layer to the map.")
End If
End Sub
C#
private void SaveTheColumInShapeFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (map1.Layers.Count > 0)
{
Teva ~ Veluppillai
Page 29
Delete the attribute column from the attribute table. In the following example "PercentMales" column will
be deleted.
VB
Private Sub DeleteColumnInAttributeTableToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles DeleteColumnInAttributeTableToolStripMenuItem.Click
'Declare a datatable
Dim dt As DataTable
If Map1.Layers.Count > 0 Then
Dim stateLayer As MapPolygonLayer
stateLayer = TryCast(Map1.Layers(0), MapPolygonLayer)
If stateLayer Is Nothing Then
MessageBox.Show("The layer is not a polygon layer.")
Else
'Get the shapefile's attribute table to our datatable dt
dt = stateLayer.DataSet.DataTable
'Remove a column
dt.Columns.Remove("PercentMales")
'Set the datagridview datasource from datatable dt
dgvAttributeTable.DataSource = dt
End If
Else
MessageBox.Show("Please add a layer to the map.")
End If
End Sub
C#
private void DeleteColumnInAttributeTableToolStripMenuItem_Click(object sender, EventArgs e)
{
//Declare a datatable
System.Data.DataTable dt = null;
if (map1.Layers.Count > 0)
{
MapPolygonLayer stateLayer = default(MapPolygonLayer);
stateLayer = map1.Layers[0] as MapPolygonLayer;
Teva ~ Veluppillai
Page 30
VB
Private Sub ExportAttributeTableToExcelToolStripMenuItem_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ExportAttributeTableToExcelToolStripMenuItem.Click
'Declare a datatable
Dim dt As DataTable
If Map1.Layers.Count > 0 Then
Dim stateLayer As MapPolygonLayer
stateLayer = TryCast(Map1.Layers(0), MapPolygonLayer)
If stateLayer Is Nothing Then
MessageBox.Show("The layer is not a polygon layer.")
Else
'Get the shapefile's attribute table to our datatable dt
dt = stateLayer.DataSet.DataTable
'Call the sub ExportToExcel
'This sub procedure expects a datatable as an input
ExportToExcel(dt)
End If
Else
MessageBox.Show("Please add a layer to the map.")
End If
End Sub
C#
Teva ~ Veluppillai
Page 31
Write the following sub method for getting an excel datasheet output from an attribute table.
VB
''' <summary>
''' This sub method is used to create an excel worksheet from the attribute table
''' </summary>
''' <param name="objDT">attribute table as a datatable input</param>
''' <remarks> Click the COM tab of the Add Reference dialog box, and find Microsoft Excel 14 Object
Library.</remarks>
Private Sub ExportToExcel(ByVal objDT As DataTable)
Dim Excel As Object = CreateObject("Excel.Application")
Dim strFilename As String
Dim intCol, intRow As Integer
'path for storing excel datasheet
Dim strPath As String = "C:\2009 Falls\"
If Excel Is Nothing Then
MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel
to be installed on this machine.", MsgBoxStyle.Critical)
Return
End If
Try
With Excel
.SheetsInNewWorkbook = 1
.Workbooks.Add()
.Worksheets(1).Select()
Teva ~ Veluppillai
Page 32
C#
/// <summary>
/// This sub method is used to create an excel worksheet from the attribute table
/// </summary>
/// <param name="objDT">attribute table as a datatable input</param>
/// <remarks>Click the COM tab of the Add Reference dialog box, and find Microsoft Excel 14
Object Library.</remarks>
Teva ~ Veluppillai
Page 33
Teva ~ Veluppillai
Page 34
C#
private void PrintMapToolStripMenuItem_Click(object sender, EventArgs e)
{
DotSpatial.Controls.LayoutForm frm = new DotSpatial.Controls.LayoutForm();
frm.MapControl = map1;
frm.Show();
}
Teva ~ Veluppillai
Page 35
Teva ~ Veluppillai
Page 36