DotSpatial Tutorials DotSpatial Tutorial 4
DotSpatial Tutorials DotSpatial Tutorial 4
Purpose of this tutorial: Become familiar with the following operations in DotSpatial:
1.1) Creating the following types of shape files: Point, Polyline, Polygon
3.2) Set a print document properties. (North Arrow, Legend, Scale bar, Title)
Step 2: Add the DotSpatial reference and change the compile option.
Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox.
Step 2: Add the DotSpatial reference and change the compile option.
2.1) Add the required DotSpatial reference in the visual studio development environment.
Create a new VB or C# application and right click over the project on the solution explorer. On the
context menu select the add reference and add the following reference from the DotSpatial folder.
2.2) Change the compile option from .Net FrameWork 4 Client Profile to .Net FrameWork 4
Step 3: Add the DotSpatial Controls into the Visual Studio Toolbox.
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
Under File menu item create 3 sub menu items as follows: Load, Clear, Exit
Under the Shapefile Operations create the following sub menu items : Point , Polyline, Polygon
Under the Point sub menu item create the following Sub menu items: Create Point Shapefile, Save Point
Shapefile.
Under the Polyline sub menu item create the following Sub menu items: Create Polyline Shapefile, Save
Polyline Shapefile.
Under the Polygon sub menu item create the following Sub menu items: Create Polygon Shapefile, Save
Polygon Shapefile.
Under the Map Options menu item create the following sub menu items: Default, Information,
Measurement, Zoom In, Zoom Out, Zoom to Extent, Pan, and Print Map
Under the Attribute Table Operations menu item create the following sub menu items: View Attribute
table, Add a column in the attribute table, Save the colum in ShapeFile, Delete a column in the attribute
table, Update attribute table in Shapefile, Export Attribute table to Excel.
3.1 ) Add the map control on the pnlMap control and add legend control on the pnlLegend.
Map and Legend control are located on the Toolbox under DotSpatial controls.
VB
Imports DotSpatial.Controls
Imports DotSpatial.Data
Imports DotSpatial.Symbology
Imports DotSpatial.Topology
C#
using DotSpatial.Controls;
using DotSpatial.Data;
using DotSpatial.Symbology;
using DotSpatial.Topology;
VB
'the id of point
Dim pointID As Integer = 0
#End Region
C#
//the id of point
int pointID = 0;
#endregion
VB
Private Sub CreatePointShapeFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles CreatePointShapeFileToolStripMenuItem.Click
'Change the cursor style
Map1.Cursor = Cursors.Cross
'set the shape type to the classlevel string variable
C#
Generate the Map1 mouse down event. : Select the map control and press the F4 key for getting
its properties window. On the properties window select the event tab and on the event tab double click
over the Mouse down.
VB
Case "Point"
If e.Button = MouseButtons.Left Then
If (pointmouseClick) Then
'This method is used to convert the screen coordinate 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)
'Add the point into the Point Feature
'assigning the point feature to IFeature because via it only we can set the attributes.
Dim currentFeature As IFeature = pointF.AddFeature(point)
'increase the point id
pointID = pointID + 1
'set the ID attribute
currentFeature.DataRow("PointID") = pointID
'refresh the map
Map1.ResetBuffer()
End If
Else
Map1.Cursor = Cursors.Default
pointmouseClick = False
End If
End Select
C#
switch (shapeType)
{
case "Point" :
if (e.Button == MouseButtons.Left)
{
if ((pointmouseClick))
{
//This method is used to convert the screen cordinate to map coordinate
//e.location is the mouse click point on the map control
Coordinate coord = map1.PixelToProj(e.Location);
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
C#
private void SavePointShapeFileToolStripMenuItem_Click(object sender, EventArgs e)
{
pointF.SaveAs("point.shp", true);
MessageBox.Show("The point shapefile has been saved.");
map1.Cursor = Cursors.Arrow;
}
VB
'It controls the drawing the polyline after the polyline saved operation.
Dim linemouseClick As Boolean = False
#End Region
C#
int lineID = 0;
//It controls the drawing the polyline after the polyline saved operation.
bool linemouseClick = false;
#endregion
VB
'set projection
lineF.Projection = Map1.Projection
firstClick = True
linemouseClick = true;
End Sub
C#
//set projection
lineF.Projection = map1.Projection;
if (!lineF.DataTable.Columns.Contains("LineID"))
{
lineF.DataTable.Columns.Add(column);
}
firstClick = true;
linemouseClick = true;
}
VB
Case "line"
If e.Button = MouseButtons.Left Then
'left click - fill array of coordinates
'coordinate of clicked point
Dim coord As Coordinate = Map1.PixelToProj(e.Location)
If (linemouseClick) Then
'first time left click - create empty line feature
If firstClick Then
'Create a new List called lineArray.
'In List we need not define the size and also
'Here this list will store the Coordinates
'We are going to store the mouse click coordinates into this array.
Dim lineArray As New List(Of Coordinate)
'Create an instance for LineString class.
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>();
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#
VB
C#
#endregion
VB
'set projection
polygonF.Projection = Map1.Projection
'set a symbology
Dim symbol As New PolygonSymbolizer(Color.Green)
polygonLayer.Symbolizer = symbol
firstClick = True
polygonmouseClick = True
End Sub
C#
//set projection
polygonF.Projection = map1.Projection;
if (!polygonF.DataTable.Columns.Contains("PolygonID"))
{
polygonF.DataTable.Columns.Add(column);
}
polygonLayer.Symbolizer = symbol;
polygonLayer.LegendText = "polygon";
firstClick = true;
polygonmouseClick = true;
VB
Case "polygon"
If e.Button = MouseButtons.Left Then
'left click - fill array of coordinates
Dim coord As Coordinate = Map1.PixelToProj(e.Location)
If (polygonmouseClick) Then
'first time left click - create empty line feature
If firstClick Then
'Create a new List called polygonArray.
'Here this list will store the Coordinates
'We are going to store the mouse click coordinates into this array.
Dim polygonArray As New List(Of Coordinate)
'Create an instance for LinearRing class.
'We pass the polygon List to the constructor of this class
Dim polygonGeometry As New LinearRing(polygonArray)
'Add the polygonGeometry instance to PolygonFeature
Dim polygonFeature As IFeature = 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
Dim existingFeature As IFeature = polygonF.Features(polygonF.Features.Count - 1)
existingFeature.Coordinates.Add(coord)
'refresh the map if line has 2 or more points
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.
existingFeature.Coordinates.Add(coord);
VB
C#
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
End If
Else
'mouse right click
Map1.Cursor = Cursors.Default
pointmouseClick = False
End If
Case "line"
If e.Button = MouseButtons.Left Then
'left click - fill array of coordinates
'coordinate of clicked point
Dim coord As Coordinate = Map1.PixelToProj(e.Location)
If (linemouseClick) Then
'first time left click - create empty line feature
If firstClick Then
'Create a new List called lineArray.
'In List we need not define the size and also
'Here this list will store the Coordinates
'We are going to store the mouse click coordinates into this array.
Dim lineArray As New List(Of Coordinate)
'Create an instance for LineString class.
'We need to pass collection of list coordinates
Dim lineGeometry As New LineString(lineArray)
'Add the linegeometry to line feature
Dim lineFeature As IFeature = lineF.AddFeature(lineGeometry)
'add first coordinate to the line feature
lineFeature.Coordinates.Add(coord)
'set the line feature attribute
lineID = lineID + 1
lineFeature.DataRow("LineID") = lineID
firstClick = False
Else
'second or more clicks - add points to the existing feature
Dim existingFeature As IFeature = lineF.Features(lineF.Features.Count - 1)
existingFeature.Coordinates.Add(coord)
'refresh the map if line has 2 or more points
If existingFeature.Coordinates.Count >= 2 Then
lineF.InitializeVertices()
Map1.ResetBuffer()
End If
End If
End If
Else
'right click - reset first mouse click
firstClick = True
Map1.ResetBuffer()
End If
Case "polygon"
If e.Button = MouseButtons.Left Then
'left click - fill array of coordinates
Dim coord As Coordinate = Map1.PixelToProj(e.Location)
If (polygonmouseClick) Then
'first time left click - create empty line feature
If firstClick Then
'Create a new List called polygonArray.
'Here this list will store the Coordinates
'We are going to store the mouse click coordinates into this array.
Dim polygonArray As New List(Of Coordinate)
'Create an instance for LinearRing class.
'We pass the polygon List to the constructor of this class
Dim polygonGeometry As New LinearRing(polygonArray)
'Add the polygonGeometry instance to PolygonFeature
Dim polygonFeature As IFeature = 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
Dim existingFeature As 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 Then
'refresh the map
polygonF.InitializeVertices()
Map1.ResetBuffer()
End If
End If
End If
Else
'right click - reset first mouse click
firstClick = True
Map1.Cursor = Cursors.Arrow
End If
End Select
End Sub
C#
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.
List<Coordinate> lineArray = new List<Coordinate>();
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.
existingFeature.Coordinates.Add(coord);
VB
C#
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
{
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
C#
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;
//calculate values
foreach (DataRow row in dt.Rows)
{
}
else
{
MessageBox.Show("Please add a layer to the map.");
}
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#
Delete the attribute column from the attribute table. In the following example "PercentMales" column will
be deleted.
VB
C#
{
//Declare a datatable
System.Data.DataTable dt = null;
if (map1.Layers.Count > 0)
{
MapPolygonLayer stateLayer = default(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;
//Remove a column
dt.Columns.Remove("PercentMales");
Right click over the project on the solution explorer. On the context menu select the add reference and
add the .NET reference: Microsoft.Office.Interop.Excel
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
C#
if (map1.Layers.Count > 0)
{
MapPolygonLayer stateLayer = default(MapPolygonLayer);
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;
//Call the sub ExportToExcel
//This sub procedure expects a datatable as an input
ExportToExcel(dt);
}
}
else
{
MessageBox.Show("Please add a layer to the map.");
}
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)
'Add the column names from the attribute table to excel worksheet
Dim intI As Integer = 1
For intCol = 0 To objDT.Columns.Count - 1
.cells(2, intI).value = objDT.Columns(intCol).ColumnName
.cells(2, intI).EntireRow.Font.Bold = True
intI += 1
Next
'Add the data row values from the attribute table to ecxel worksheet
intI = 3
Dim intK As Integer = 1
For intCol = 0 To objDT.Columns.Count - 1
intI = 3
For intRow = 0 To objDT.Rows.Count - 1
.Cells(intI, intK).Value = objDT.Rows(intRow).ItemArray(intCol)
intI += 1
Next
intK += 1
Next
.ActiveCell.Worksheet.SaveAs(strFilename)
End With
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Excel = Nothing
MsgBox("Data's are exported to Excel Succesfully in '" & strFilename & "'",
MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message)
End Try
' The excel is created and opened for insert value. We most close this excel using this system
Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL")
For Each i As Process In pro
i.Kill()
Next
End Sub
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>
if (xlApp == null)
{
MessageBox.Show("It appears that Excel is not installed on this machine. This operation requires MS
Excel to be installed on this machine.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
try
{
//var _with1 = Microsoft.Office.Interop.Excel.Application();
xlApp.SheetsInNewWorkbook = 1;
xlApp.Workbooks.Add();
xlApp.Worksheets[1].Select();
//Add the column names from the attribute table to excel worksheet
int intI = 1;
for (intCol = 0; intCol <= objDT.Columns.Count - 1; intCol++)
{
xlApp.Cells[2, intI].value = objDT.Columns[intCol].ColumnName;
xlApp.Cells[2, intI].EntireRow.Font.Bold = true;
intI += 1;
}
//Add the data row values from the attribute table to ecxel worksheet
intI = 3;
int intK = 1;
for (intCol = 0; intCol <= objDT.Columns.Count - 1; intCol++)
{
intI = 3;
for (intRow = 0; intRow <= objDT.Rows.Count - 1; intRow++)
{
xlApp.Cells[intI, intK].Value = objDT.Rows[intRow].ItemArray[intCol];
intI += 1;
}
intK += 1;
}
if (strPath.Substring(strPath.Length - 1, 1) != "\\")
{
strPath = strPath + "\\";
}
xlApp.ActiveCell.Worksheet.SaveAs(strFilename);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
MessageBox.Show("Data's are exported to Excel Succesfully in '" + strFilename + "'", "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// The excel is created and opened for insert value. We most close this excel using this system
System.Diagnostics.Process[] pro =
(System.Diagnostics.Process[])System.Diagnostics.Process.GetProcessesByName("EXCEL");
foreach (System.Diagnostics.Process i in pro)
{
i.Kill();
}
}
VB
C#