Вы находитесь на странице: 1из 32

Sample code that demonstrates how to get the value of a single cell in an attribute table.

using DotSpatial.Data;

private void btnBuffer_Click(object sender, EventArgs e) { FeatureSet fs = new FeatureSet(); fs.FillAttributes(); fs.Open("C:\\Temp\\roads.shp"); DataTable dt = fs.DataTable; for (int row = 0; row < dt.Rows.Count; row++) { object val = dtOriginal.Rows[row]["LENGTH"]; } }

Sample code for loop through a Feature Set's attribute table and get all the values
using System.Windows.Forms; using DotSpatial.Topology; using DotSpatial.Data;

private void btnBuffer_Click(object sender, EventArgs e) { FeatureSet fs = new FeatureSet(); fs.FillAttributes(); fs.Open("C:\\Temp\\roads.shp"); DataTable dtOriginal = fs.DataTable; for (int row = 0; row < dtOriginal.Rows.Count; row++) { object[] original = dtOriginal.Rows[row].ItemArray; } }

This code demonstrates how to open an existing shapefile as a new feature set using the System.Spatial.Desktop library.
using DotSpatial.Data;

public void OpeningFS() { //Declare a new feature set FeatureSet fs = new FeatureSet(); //Pass in the file path for the standard shapefile that will be opened fs.Open("C:\\Temp\\roads.shp");

} // create a new shape file Shapefile s = new Shapefile();

// define the feature type for this file FeatureSet fs = new FeatureSet( FeatureType.Polygon );

// Add Some Columns fs.DataTable.Columns.Add( new DataColumn( "ID", typeof( int ))); fs.DataTable.Columns.Add( new DataColumn( "Text", typeof( string )));

// create a geometry (square polycon) List vertices = new List(); vertices.Add(new Coordinate(0, 0)); vertices.Add( new Coordinate( 0,100 )); vertices.Add(new Coordinate(100, 100)); vertices.Add(new Coordinate(100, 0)); Polygon geom = new Polygon( vertices );

// add the geometry to the featureset. IFeature feature = fs.AddFeature(geom);

// now the resulting features knows what columns it has

// add values for the columns feature.DataRow.BeginEdit(); feature.DataRow"ID" = 1; feature.DataRow"Text" = "Hello World"; feature.DataRow.EndEdit();

// save the feature set fs.SaveAs("d:\\test.shp", true);

This code generates a random linestring from a coordinate array using the Geometry library then creates a line feature using the desktop library.
using DotSpatial.Data; using DotSpatial.Geometries;

namespace SampleCode { public partial class Form1 : Form { public Form1() { InitializeComponent();

private void button1_Click(object sender, EventArgs e) { //Creates a random number generator Random rnd = new Random(); //creates a new coordiante array Coordinate[] c = new Coordinate[36]; //for loop that will generate 36 random numbers for (int i = 0; i < 36; i++) { c[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);

} //creates a linestring from the coordinate array LineString ls = new LineString(c); //creates a feature from the linestring Feature f = new Feature(ls); FeatureSet fs = new FeatureSet(f.FeatureType); fs.Features.Add(f);

} }

This code demonstrates how to open an existing shapefile as a new feature set using the System.Spatial.Desktop library and then buffer the feature set.
using System.Spatial.Data;

private void button1_Click(object sender, EventArgs e) { //Declare a new feature set FeatureSet fs = new FeatureSet(); fs.FillAttributes(); //Pass in the file path for the standard shapefile that will be opened fs.Open("C:\\Temp\\roads.shp"); //An IFeatureSet that contains the factory that will buffer the feature set IFeatureSet iF = fs.Buffer(10, true); //Saves the buffered feature set as a new file. iF.SaveAs("C:\\Temp\roads_buffer.shp", true); }

Sample code that demonstrates how to get the number of rows in a feature set.

using System.Windows.Forms; using DotSpatial.Data;

private void btnBuffer_Click(object sender, EventArgs e) { FeatureSet fs = new FeatureSet(); fs.FillAttributes(); fs.Open("C:\\Temp\\roads.shp"); double numRows = fs.NumRows(); }

Create random points, then move them around.


This example was a test case for a bug fix on 11/7/2010. Make sure you have downloaded something more recent than changeset e91fbe2d79ca or else the "move" operation listed here will not work. To run this, create two buttons. The first button adds the points. The second button moves the points to a slightly different random location. Pressing the move button sequentially should cause the points to appear to move around randomly. This sample is also part of the "TestViewer" application that is in the "Demo Projects" folder of the source code repository.

//using DotSpatial.Data; //using DotSpatial.Symbology; //using DotSpatial.Topology; //using System.Drawing; private void AddPoints() { // Create the featureset if one hasn't been created yet. if (_myPoints == null) _myPoints = new FeatureSet(FeatureType.Point);

// Assume background layers have been added, and get the current map extents.

double xmin = map1.Extents.Minimum.X; double xmax = map1.Extents.Maximum.X; double ymin = map1.Extents.Minimum.Y; double ymax = map1.Extents.Maximum.Y;

// Randomly generate 10 points that are in the map extent Random rnd = new Random(); for(int i = 0; i < 10; i++) { double x = xmin + rnd.NextDouble() * (xmax - xmin); double y = ymin + rnd.NextDouble() * (ymax - ymin); Coordinate c = new Coordinate(x, y); _myPoints.Features.Add(c); }

// Add a layer to the map, and we know it is a point layer so cast it specifically. IMapPointLayer pointLayer = map1.Layers.Add(_myPoints) as IMapPointLayer;

// Control what the points look like through a symbolizer (or pointLayer.Symbology for categories) if(pointLayer != null) { pointLayer.LegendText = "MovingPoints"; pointLayer.Symbolizer = new PointSymbolizer(Color.Blue, PointShape.Ellipse, 7); }

private void MovePoints() { Random rnd = new Random();

foreach(IFeature feature in _myPoints.Features) { // Coordinates can be updated geographically like // feature.Coordinates[0].X += (rnd.NextDouble() - .5); // feature.Coordinates[0].Y += (rnd.NextDouble() - .5);

// Or controled in pixels with the help of the map Point pixelLocation = map1.ProjToPixel(feature.Coordinates[0]);

// Control movement in terms of pixels int dx = Convert.ToInt32((rnd.NextDouble() - .5) * 50); // shift left or right 5 pixels int dy = Convert.ToInt32((rnd.NextDouble() - .5) * 50); // shift up or down 5 pixels pixelLocation.X = pixelLocation.X + dx; pixelLocation.Y = pixelLocation.Y + dy;

// Convert the pixel motions back to geographic motions. Coordinate c = map1.PixelToProj(pixelLocation); feature.Coordinates[0] = c; }

// Refresh the cached representation because we moved points around. map1.MapFrame.Invalidate(); map1.Invalidate();

Sample code that demonstrates how to create a Multi Polygon Feature Set

using DotSpatial.Data; using DotSpatial.Geometries;

private void button1_Click(object sender, EventArgs e) { Random rnd = new Random(); Polygon[] pg = new Polygon[100]; Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); for (int i = 0; i < 100; i++) { Coordinate center = new Coordinate((rnd.Next(50) * 360) - 180, (rnd.Next(60) * 180) - 90); Coordinate[] coord = new Coordinate[50]; for (int ii = 0; ii < 50; ii++) { coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10); } coord[35] = new Coordinate(coord[0].X, coord[0].Y); pg[i] = new Polygon(coord); fs.Features.Add(pg[i]); } fs.SaveAs("C:\\Temp\\test.shp", true);

Sample code that demonstrates how to create a new Multi Point Feature Set
using DotSpatial.Data; using DotSpatial.Geometries;

private void button1_Click(object sender, EventArgs e) { Coordinate[] c = new Coordinate[50]; Random rnd = new Random(); Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); for (int i = 0; i < 50; i++) { c[i] = new Coordinate((rnd.Next(0, 50) + 360) - 90, (rnd.NextDouble() * 360) - 180); fs.Features.Add(c[i]); } fs.SaveAs("C:\\Temp\\test.shp", true); }

Union Intersecting Shapes in a FeatureSet


This example shows how to use a newly added extension method that allows for intersecting shapes in the same Shapefile

to be Unioned, but leaving shapes that don't overlap unchanged.

public void UnionShapes() { FeatureSet fs = new FeatureSet(); fs.Open(); IFeatureSet result = fs.UnionShapes(ShapeRelateType.Intersecting); SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "*Shapefiles (*.shp)|*.shp"; if (sfd.ShowDialog() != DialogResult.OK) return; result.SaveAs(sfd.FileName, true); }

Sample code that demonstrates how to open an existing shapefile and save that shapefile with a new file name.
using DotSpatial.Data;

private void button1_Click(object sender, EventArgs e) { //Declare a new feature set FeatureSet fs = new FeatureSet(); //Pass in the file path for the standard shapefile that will be opened fs.Open("C:\\Temp\\roads.shp"); //Saves the open shapefile fs.SaveAs("C:\\Temp\\roads_test.shp", true); }

Sample code that demonstrates how to create a Multi Line Feature Set
using DotSpatial.Data; using DotSpatial.Geometries;

private void button1_Click(object sender, EventArgs e) { Random rnd = new Random(); Feature f = new Feature(); FeatureSet fs = new FeatureSet(f.FeatureType); for (int ii = 0; ii < 40; ii++) { Coordinate[] coord = new Coordinate[36]; for (int i = 0; i < 36; i++) { coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); } LineString ls = new LineString(coord); f = new Feature(ls); fs.Features.Add(f); } fs.SaveAs("C:\\Temp\\test.shp", true); } Sample code to project a point using the ESRI Projection File

VB.Net Sample Code Imports DotSpatial.Projections

'Sample code that will conduct a reprojection by reading in the ESRI.prj file Private Sub btnProjection_Click(sender As Object, e As EventArgs) 'declares a new ProjectionInfo for the startind and ending coordinate systems 'sets the start GCS to WGS_1984 Dim pStart As ProjectionInfo = KnownCoordinateSystems.Geographic.World.WGS1984 Dim pESRIEnd As New ProjectionInfo() 'declares the point(s) that will be reprojected Dim xy As Double() = New Double(1) {} Dim z As Double() = New Double(0) {} 'initiates a StreamReader to read the ESRI .prj file Dim re As StreamReader = File.OpenText("C:\Program Files\ArcGIS\Coordinate Systems\Projected Coordinate Systems\UTM\WGS 1984\WGS 1984 UTM Zone 1N.prj") 'sets the ending PCS to the ESRI .prj file pESRIEnd.ReadEsriString(re.ReadLine()) 'calls the reprojection function Reproject.ReprojectPoints(xy, z, pStart, pESRIEnd, 0, 1) MessageBox.Show("Points have been projected successfully.") End Sub

Sample code that demonstrates how to read a prog4 string and then project a point

C# Code using DotSpatial.Projections;

//Code that allows the user to input a Proj4 string and reproject a WGS 1984 GCS to a Proj4 PCS private void btnProjection_Click(object sender, EventArgs e) { //Declares a new ProjectionInfo and sets it to GCS_WGS_1984 ProjectionInfo pStart = new ProjectionInfo(); pStart = KnownCoordinateSystems.Geographic.World.WGS1984; //Declares a new ProjectionInfo and allows the user to directly input a Proj4 sring ProjectionInfo pEnd = new ProjectionInfo("+proj=aea +lat_1=20 +lat_2=-23 +lat_0=0 +lon_0=25 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs "); //Declares the point to be project, starts out as 0,0 double[] xy = new double[2]; double[] z = new double[1]; //calls the reproject function and reprojects the points Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 1); MessageBox.Show("Reprojection is compelte."); }

VB.net Code

Imports DotSpatial.Projections

'Code that allows the user to input a Proj4 string and reproject a WGS 1984 GCS to a Proj4 PCS Private Sub btnProjection_Click(sender As Object, e As EventArgs) 'Declares a new ProjectionInfo and sets it to GCS_WGS_1984 Dim pStart As New ProjectionInfo() pStart = KnownCoordinateSystems.Geographic.World.WGS1984 'Declares a new ProjectionInfo and allows the user to directly input a Proj4 sring Dim pEnd As New ProjectionInfo("+proj=aea +lat_1=20 +lat_2=-23 +lat_0=0 +lon_0=25 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs ") 'Declares the point to be project, starts out as 0,0 Dim xy As Double() = New Double(1) {} Dim z As Double() = New Double(0) {} 'calls the reproject function and reprojects the points Reproject.ReprojectPoints(xy, z, pStart, pEnd, 0, 1) MessageBox.Show("Reprojection is compelte.") End Sub This code will add a geographic coordinate system (GCS) to a feature set that does not contain a GCS.

VB Sample Code: Imports System.Spatial.Projections

'Code for defining a geographic coordinate system for a feature set Private Sub BbtnDefineGeographicProjection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BbtnDefineGeographicProjection.Click Dim fs As New FeatureSet Dim CopyFS As New FeatureSet Dim dest As ProjectionInfo

'Get's the first layer in the Table of Contents fs = MapControl.Layers.Item(0).DataSet

'Copies the selected layer to a new feature set 'Prevents the original file from being edited CopyFS.CopyFeatures(fs, True)

dest = KnownCoordinateSystems.Geographic.World.WGS1984 'Adds the geographic coordinate system to the feature set CopyFS.Projection = dest 'Saves the feature set CopyFS.SaveAs("C:\Temp\US_Cities_GCS_WGS1984.shp", True)

MessageBox.Show("The feature was successfully been projected.")

End Sub

C# Sample Code: //Code for defining a geographic coordinate system for a feature set private void BbtnDefineGeographicProjection_Click(System.Object sender, System.EventArgs e) { FeatureSet fs = new FeatureSet(); FeatureSet CopyFS = new FeatureSet(); ProjectionInfo dest = default(ProjectionInfo);

//Get's the first layer in the Table of Contents fs = MapControl.Layers.Item(0).DataSet;

//Copies the selected layer to a new feature set //Prevents the original file from being edited CopyFS.CopyFeatures(fs, true);

dest = KnownCoordinateSystems.Geographic.World.WGS1984; //Adds the geographic coordinate system to the feature set CopyFS.Projection = dest; //Saves the feature set CopyFS.SaveAs("C:\\Temp\\US_Cities_GCS_WGS1984.shp", true);

MessageBox.Show("The feature was successfully been projected.");

} This code demonstrates the method for declaring a new coordinate and creating a point from that coordinate. using DotSpatial.Topology; using DotSpatial.Common;

private void btnCoord_Click(object sender, EventArgs e) { //creates a new coordinate Coordinate c = new Coordinate(2.4, 2.4); //passes the coordinate to a new point Point p = new Point(c); //displayes the new point's x and y coordiantes MessageBox.Show("Point p is: x= " + p.X + " & y= " } Creating a new linestring and calculating the length using DotSpatial.Topology; using DotSpatial.Common; + p.Y);

private void btnLineString_Click(object sender, EventArgs e) {

//creates a new coordinate array Coordinate[] coords = new Coordinate[36]; //creates a random point variable Random rnd = new Random(); //a for loop that generates a new random X and Y value and feeds those values into the coordinate array for (int i = 0; i < 36; i++) { coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); } //creates a new linstring from the array of coordinates LineString ls = new LineString(coords); //new variable for the length of the linstring Double length; length = ls.Length; //Displays the length of the linstring MessageBox.Show("The length of the linstring is: " + length); } Sample code that demonstrates the creation of a new polygon from random points and calculating the area using DotSpatial.Topology; using DotSpatial.Common;

private void btnPolygon_Click(object sender, EventArgs e) { //creates a new coordinate array Coordinate[] coords = new Coordinate[10]; //creates a random point variable Random rnd = new Random(); //Creates the center coordiante for the new polygon Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); //a for loop that generates a new random X and Y value and feeds those values into the coordinate array for (int i = 0; i < 10; i++) { coords[i] = new Coordinate(center.X + Math.Cos((i * 2) * Math.PI / 18), center.Y + (i * 2) * Math.PI / 18); } //creates a new polygon from the coordinate array Polygon pg = new Polygon(coords); //new variable for the area of the polgyon Double area; area = pg.Area; //displays the area of the polygon MessageBox.Show("The Area of the polygon is: " + area); }

Sample code showing how to generate a polygon from random points that contains a hole. using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

public void PolgygonHolesSC() { //Defines a new coordinate array Coordinate[] coords = new Coordinate[20]; //Defines a new random number generator Random rnd = new Random(); //defines a randomly generated center for teh polygon Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); for (int i = 0; i < 19; i++) { //generates random coordinates and adds those coordinates to the array coords[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 10), center.Y + (i * 10) * Math.PI / 10); } //sets the last coordinate equal to the first, this 'closes' the polygon coords[19] = new Coordinate(coords[0].X, coords[0].Y); //defines a new LingRing from the coordinates LinearRing Ring = new LinearRing(coords);

//Repeates the process, but generates a LinearRing with a smaller area, this will be the hole in the polgyon Coordinate[] coordshole = new Coordinate[20]; for (int i = 0; i < 20; i++) { coordshole[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 20), center.Y + (i * 10) * Math.PI / 20); } coordshole[19] = new Coordinate(coordshole[0].X, coordshole[0].Y); LinearRing Hole = new LinearRing(coordshole); //This steps addes the hole LinerRing to a ILinearRing Array //A Polgyon can contain multiple holes, thus a Array of Hole is required ILinearRing[] Holes = new ILinearRing[1]; Holes[0] = Hole; //This passes the Ring, the polygon shell, and the Holes Array, the holes Polygon pg = new Polygon(Ring, Holes); } Sample code that demonstrates how to create a new mulitpolygon from randomly generated coordinates using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

private void button1_Click(object sender, EventArgs e) {

Random rnd = new Random(); Polygon[] pg = new Polygon[50]; for (int i = 0; i < 50; i++) { Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); Coordinate[] coord = new Coordinate[36]; for (int ii = 0; ii < 36; ii++) { coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10); } coord[35] = new Coordinate(coord[0].X, coord[0].Y); pg[i] = new Polygon(coord); } MultiPolygon mpg = new MultiPolygon(pg); } Sample code that demonstrates how to create a multilinestring from randomly generated coordinates. using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

public void samplecode() {

Random rnd = new Random(); MultiLineString Mls = new MultiLineString(); LineString[] ls = new LineString[40]; for (int ii = 0; ii < 40; ii++) { Coordinate[] coord = new Coordinate[36]; for (int i = 0; i < 36; i++) { coord[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); } ls[ii] = new LineString(coord); } Mls = new MultiLineString(ls); } Sample code that demonstrates how to buffer a randomly generated point. using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

private void button1_Click(object sender, EventArgs e) { Coordinate coords = new Coordinate(); Random rnd = new Random();

coords = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); Point p = new Point(coords); //This will get the area of the buffer. double area = p.Buffer(500).Area; } Sample that demonstrates how to create a multipoint from randomly generated coordinates using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

private void button1_Click(object sender, EventArgs e) { Coordinate[] c = new Coordinate[36]; Random rnd = new Random(); for (int i = 0; i < 36; i++) { c[i] = new Coordinate((rnd.NextDouble() + 360) - 180, (rnd.NextDouble() * 180) - 90); } MultiPoint Mps = new MultiPoint(c); } Sample code that will generate random an array of coordinates, creates a linestring from the array of coordinates, and calculates the length of the linestring.

using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

public void PolgygonHolesSC() { //Creates a coordinate arrary Coordinate[] coords = new Coordinate[36]; //Creates a random number generator Random rnd = new Random(); //A for loop that will generate random coordinate's and add those coordinates to the array for (int i = 0; i < 36; i++) { coords[i] = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);

} //Creates a linestring from the array of coordinates LineString ls = new LineString(coords); //Calculates the length of the linestring Double length; length = ls.Length;

Sample code that will generate a coordinate array, create a polygon from the coordinate array, and calculate the area of the polygon. using DotSpatial.Geometries; using DotSpatial.Topology.Geometries;

{ //Creates a new array of coordinates Coordinate[] coords = new Coordinate[20]; //Creates a random number generator Random rnd = new Random(); //Createa a center point for the polygon Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90); //A For Loop that will randomly create coordinates and feeds the coordinates into the array of coordiantes for (int i = 0; i < 19; i++) { coords[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 10), center.Y + (i * 10) * Math.PI / 10); } //Set the last coordinate equal to the first coordinate in the array, thus 'closing' the polygon coords[19] = new Coordinate(coords[0].X, coords[0].Y); //Creates a new polygon from the coordinate array

Polygon pg = new Polygon(coords); //Determines that area of the polygon Double area = pg.Area; }

Вам также может понравиться