public static void Main(string[] args) { //Create new shapefile Shapefile myShapefile = new Shapefile(); //Define the path of the new shapefile and geometry type myShapefile.CreateNew(@"D:\GISLesson04\road.shp", ShpfileType.SHP_POINT); //Create new field MapWinGIS.Field myField = new Field(); //Set the field properties myField.Name = "ID"; myField.Type = FieldType.INTEGER_FIELD; myField.Width = 10; //Add the filed for the shapefile table int intFieldIndex = 0; myShapefile.EditInsertField(myField, ref intFieldIndex, null); int myCounter = 0; int myShapeIndex = 0; string myLine; // Read the file and display it line by line. System.IO.StreamReader myFile = new System.IO.StreamReader(@"D:\GISLesson04\road.csv"); // Using while loop to read csv file line by line while ((myLine = myFile.ReadLine()) != null) { if (myCounter > 0) { MapWinGIS.Shape myShape = new Shape(); myShape.Create(ShpfileType.SHP_POINT); MapWinGIS.Point myPoint = new Point(); myPoint.x = GetX(myLine); myPoint.y = GetY(myLine); int myPointIndex = 0; myShape.InsertPoint(myPoint, ref myPointIndex); myShapefile.EditInsertShape(myShape, ref myShapeIndex); myShapeIndex++; } myCounter++; } myShapefile.StopEditingShapes(true, true, null); myFile.Close(); Console.ReadKey(); }
/// <summary> /// 根据坐标在地图上划线 /// </summary> /// <param name="Xstart"></param> /// <param name="Ystart"></param> /// <param name="Xend"></param> /// <param name="Yend"></param> public int WriteLine(ClassLine line, LineSet lineSet) { Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POLYLINE); Point pnt = new Point(); pnt.x = line.startX; pnt.y = line.startY; int index = shp.numPoints; shp.InsertPoint(pnt, ref index); pnt = new Point(); pnt.x = line.endX; pnt.y = line.endY; index = shp.numPoints; shp.InsertPoint(pnt, ref index); index = sf.NumShapes; sf.EditInsertShape(shp, ref index); //var utils = new Utils(); //LinePattern pattern = new LinePattern(); //pattern.AddLine(utils.ColorByName(lineSet.color), lineSet.Width, lineSet.style); //ShapefileCategory ct = sf.Categories.Add("Railroad"); //ct.DrawingOptions.LinePattern = pattern; //ct.DrawingOptions.UseLinePattern = true; //sf.set_ShapeCategory(0, 0); var utils = new Utils(); LinePattern pattern = new LinePattern(); pattern.AddLine(utils.ColorByName(lineSet.color), lineSet.Width, lineSet.style); sf.DefaultDrawingOptions.LinePattern = pattern; sf.DefaultDrawingOptions.UseLinePattern = true; layerHandle = map.AddLayer(sf, true); return(layerHandle); }
private void axMap1_MouseDownEvent(object sender, AxMapWinGIS._DMapEvents_MouseDownEvent e) { if (PointF == 1 || PointF == 3) { double xP = 0; double yP = 0; Shapefile sf = new Shapefile(); bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT); MapWinGIS.Point pt = new MapWinGIS.Point(); axMap1.PixelToProj(e.x, e.y, ref xP, ref yP); pt.x = xP; pt.y = yP; comboBox1.Text = FindMinStop(xP, yP); Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POINT); shp.InsertPoint(pt, 0); sf.EditInsertShape(shp, 0); sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsStar); axMap1.AddLayer(sf, true); axMap1.SendMouseDown = false; } if (PointF == 2 || PointF == 4) { double xP = 0; double yP = 0; Shapefile sf = new Shapefile(); bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT); MapWinGIS.Point pt = new MapWinGIS.Point(); axMap1.PixelToProj(e.x, e.y, ref xP, ref yP); pt.x = xP; pt.y = yP; comboBox2.Text = FindMinStop(xP, yP); Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POINT); shp.InsertPoint(pt, 0); sf.EditInsertShape(shp, 0); sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsStar); axMap1.AddLayer(sf, true); axMap1.SendMouseDown = false; } }
// <summary> // Creates a point shapefile by placing 1000 points randomly // </summary> public void CreatePointShapefile(AxMap axMap1) { axMap1.Projection = tkMapProjection.PROJECTION_NONE; var sf = new Shapefile(); // MWShapeId field will be added to attribute table bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT); // bounding box for the new shapefile double xMin = 0.0; double yMin = 0.0; double xMax = 1000.0; double yMax = 1000.0; // the location of points will be random Random rnd = new Random(DateTime.Now.Millisecond); // creating points and inserting them in the shape for (int i = 0; i < 1000; i++) { var pnt = new Point(); pnt.x = xMin + (xMax - xMin) * rnd.NextDouble(); pnt.y = yMin + (yMax - yMin) * rnd.NextDouble(); Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POINT); int index = 0; shp.InsertPoint(pnt, ref index); sf.EditInsertShape(shp, ref i); } sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsStar); // adds shapefile to the map axMap1.AddLayer(sf, true); // save if needed //sf.SaveAs(@"c:\points.shp", null); }
/// <summary> /// Map a single fishing ground when coming from a selected sampling /// </summary> /// <param name="fishingGround"></param> /// <param name="utmZone"></param> /// <returns></returns> public bool MapFishingGround(string fishingGround, fadUTMZone utmZone, string layerName = "", bool testIfInland = false) { var sf = new Shapefile(); bool success = false; var fgLayerName = "Fishing ground"; if (layerName.Length > 0) { fgLayerName = layerName; } if (sf.CreateNew("", ShpfileType.SHP_POINT)) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { var iShp = 0; if (_geoProjection.IsGeographic) { var result = FishingGrid.Grid25ToLatLong(fishingGround, utmZone); iShp = shp.AddPoint(result.longitude, result.latitude); } else { FishingGrid.Grid25_to_UTM(fishingGround, out int x, out int y); iShp = shp.AddPoint(x, y); } if (iShp >= 0 && sf.EditInsertShape(shp, 0)) { MapLayersHandler.RemoveLayer(fgLayerName); sf.GeoProjection = _geoProjection; var ifldLabel = sf.EditAddField("Label", FieldType.STRING_FIELD, 1, 15); sf.EditCellValue(ifldLabel, iShp, fgLayerName); sf.CollisionMode = tkCollisionMode.AllowCollisions; SymbolizeFishingGround(sf, fgLayerName, testIfInland); success = MapLayersHandler.AddLayer(sf, fgLayerName, true, true) >= 0; } } } return(success); }
private void MainMap_MouseDownEvent(object sender, AxMapWinGIS._DMapEvents_MouseDownEvent e) { if (e.button == 1) // left button { Shapefile sf = MainMap.get_Shapefile(m_layerHandle); Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POINT); MapWinGIS.Point pnt = new MapWinGIS.Point(); double x = 0.0; double y = 0.0; MainMap.PixelToProj(e.x, e.y, ref x, ref y); pnt.x = x; pnt.y = y; int index = shp.numPoints; shp.InsertPoint(pnt, ref index); index = sf.NumShapes; if (!sf.EditInsertShape(shp, ref index)) { MessageBox.Show("Failed to insert shape: " + sf.ErrorMsg[sf.LastErrorCode]); return; } MainMap.Redraw(); } }
public void CreateShapefileTest() { var tempFolder = Path.GetTempPath(); var tempFilename = Path.Combine(tempFolder, "CreateShapefileTest.shp"); Helper.DeleteShapefile(tempFilename); bool result; // Create shapefile var sf = new Shapefile { GlobalCallback = this }; try { result = sf.CreateNewWithShapeID(tempFilename, ShpfileType.SHP_POINT); Assert.IsTrue(result, "Could not create shapefile"); Assert.IsTrue(sf.EditingShapes, "Shapefile is not in edit shapes mode"); Assert.IsTrue(sf.EditingTable, "Shapefile is not in edit table mode"); // Add fields: Assert.IsTrue(sf.Table.EditingTable, "Table is not in edit table mode"); var fieldIndex = sf.Table.EditAddField("date", FieldType.STRING_FIELD, 0, 50); Assert.AreEqual(1, fieldIndex, "Could not add field"); fieldIndex = sf.Table.EditAddField("remarks", FieldType.STRING_FIELD, 0, 100); Assert.AreEqual(2, fieldIndex, "Could not add field"); fieldIndex = sf.Table.EditAddField("amount", FieldType.INTEGER_FIELD, 0, 3); Assert.AreEqual(3, fieldIndex, "Could not add field"); Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect"); result = sf.Table.Save(); Assert.IsTrue(result, "Could not save table"); Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect"); // Create shape: var shp = new Shape(); result = shp.Create(sf.ShapefileType); Assert.IsTrue(result, "Could not create shape"); // Create point: var pnt = new Point { x = 200, y = 200 }; // Add point: var pointIndex = shp.numPoints; result = shp.InsertPoint(pnt, ref pointIndex); Assert.IsTrue(result, "Could not insert point"); var shapeIndex = sf.NumShapes; result = sf.EditInsertShape(shp, ref shapeIndex); Assert.IsTrue(result, "Could not insert shape"); // Update attributes: sf.EditCellValue(fieldIndex, shapeIndex, 3); result = sf.Save(); Assert.IsTrue(result, "Could not save shapefile"); // Check shapefile: Assert.AreEqual(shapeIndex + 1, sf.NumShapes, "Number of shapes are incorrect"); Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect"); // Close shapefile and re-open: result = sf.Close(); Assert.IsTrue(result, "Could not close shapefile"); result = sf.Open(tempFilename); Assert.IsTrue(result, "Could not open shapefile"); // Check shapefile: Assert.AreEqual(shapeIndex + 1, sf.NumShapes, "Number of shapes are incorrect"); Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect"); } finally { // Close the shapefile: result = sf.Close(); Assert.IsTrue(result, "Could not close shapefile"); } }
public void CheckNullValueTableData() { bool result; var sf = new Shapefile { GlobalCallback = this }; try { // Create in-memory shapefile result = sf.CreateNewWithShapeID(string.Empty, ShpfileType.SHP_POINT); Assert.IsTrue(result, "Could not create shapefile"); // Add fields: var fieldIndex = sf.Table.EditAddField("string", FieldType.STRING_FIELD, 0, 50); Assert.AreEqual(1, fieldIndex, "Could not add field"); fieldIndex = sf.Table.EditAddField("integer", FieldType.INTEGER_FIELD, 0, 50); Assert.AreEqual(2, fieldIndex, "Could not add field"); fieldIndex = sf.Table.EditAddField("double", FieldType.DOUBLE_FIELD, 2, 50); Assert.AreEqual(3, fieldIndex, "Could not add field"); fieldIndex = sf.Table.EditAddField("double", FieldType.DOUBLE_FIELD, 0, 50); Assert.AreEqual(-1, fieldIndex, "Field was added. This is not correct."); Assert.AreEqual(4, sf.NumFields, "Wrong number of fields"); // Create shape: var shp = new Shape(); result = shp.Create(ShpfileType.SHP_POINT); Assert.IsTrue(result, "Could not create point shape"); // Create point: var pnt = new Point { x = 200, y = 200 }; // Add point: var pointIndex = shp.numPoints; result = shp.InsertPoint(pnt, ref pointIndex); Assert.IsTrue(result, "Could not insert point"); var shapeIndex = sf.NumShapes; result = sf.EditInsertShape(shp, ref shapeIndex); Assert.IsTrue(result, "Could not insert shape"); // Read attribute data, skip the first because that is the ID which always has a value for (var i = 1; i < sf.NumFields; i++) { var value = sf.CellValue[i, 0]; var field = sf.Field[i]; Console.WriteLine($"Is the value of fieldId {i} NULL: {value == null} Type of field is {field.Type}"); // Assert.IsNull(value, $"Value with fieldId {i} is not null, but is '{value}'"); } } finally { // Close the shapefile: result = sf.Close(); Assert.IsTrue(result, "Could not close shapefile"); } }
/// <summary> /// Creates a polygon shapefile by placing 100 circles randomly. /// </summary> public void CreatePolygonShapefile(AxMap axMap1) { axMap1.Projection = tkMapProjection.PROJECTION_NONE; var sf = new Shapefile(); bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON); if (!result) { MessageBox.Show(sf.ErrorMsg[sf.LastErrorCode]); } else { double xMin = 0.0; double yMin = 0.0; double xMax = 1000.0; double yMax = 1000.0; var rnd = new Random(DateTime.Now.Millisecond); int fldX = sf.EditAddField("x", FieldType.DOUBLE_FIELD, 9, 12); int fldY = sf.EditAddField("y", FieldType.DOUBLE_FIELD, 9, 12); int fldArea = sf.EditAddField("area", FieldType.DOUBLE_FIELD, 9, 12); // In a loop we are creating 100 different points using the box established above. for (int i = 0; i < 100; i++) { double xCenter = xMin + (xMax - xMin) * rnd.NextDouble(); double yCenter = yMin + (yMax - yMin) * rnd.NextDouble(); // random radius from 10 to 100 double radius = 10 + rnd.NextDouble() * 90; // polygons must be clockwise Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POLYGON); for (int j = 0; j < 37; j++) { Point pnt = new Point(); pnt.x = xCenter + radius * Math.Cos(j * Math.PI / 18); pnt.y = yCenter - radius * Math.Sin(j * Math.PI / 18); shp.InsertPoint(pnt, ref j); } Debug.Print(shp.Extents.ToDebugString()); sf.EditInsertShape(shp, ref i); sf.EditCellValue(fldX, i, xCenter.ToString()); sf.EditCellValue(fldY, i, yCenter.ToString()); sf.EditCellValue(fldArea, i, Math.PI * radius * radius); } int handle = axMap1.AddLayer(sf, true); string extents = sf.Extents.ToDebugString(); axMap1.ZoomToLayer(handle); sf.Categories.Generate(fldArea, tkClassificationType.ctNaturalBreaks, 7); ColorScheme scheme = new ColorScheme(); scheme.SetColors2(tkMapColor.Wheat, tkMapColor.Salmon); sf.Categories.ApplyColorScheme(tkColorSchemeType.ctSchemeGraduated, scheme); axMap1.Redraw(); // save if needed //sf.SaveAs(@"c:\polygons.shp", null); } }
public bool EditInsert(IGeometry geometry, ref int index) { return(_shapefile.EditInsertShape(geometry.GetInternal(), ref index)); }
// <summary> // Creates several buffers around the waterways. // </summary> public void CreateBuffer(AxMap axMap1, string dataPath, System.Windows.Forms.ToolStripStatusLabel label) { axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR; string filename = dataPath + "waterways.shp"; if (!File.Exists(filename)) { MessageBox.Show("The shapefile with rivers wasn't found: " + filename); } else { var callback = new Callback(label); var sf = new Shapefile(); if (!sf.Open(filename, callback)) { MessageBox.Show(sf.ErrorMsg[sf.LastErrorCode]); } else { int layerHandle = axMap1.AddLayer(sf, true); sf = axMap1.get_Shapefile(layerHandle); // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding var utils = new Utils(); sf.DefaultDrawingOptions.LineWidth = 3.0f; sf.DefaultDrawingOptions.LineColor = utils.ColorByName(tkMapColor.Blue); const double distance = 150; // meters var buffers = new List <Shapefile>(); for (int i = 1; i < 5; i++) { Shapefile sfBuffer = sf.BufferByDistance(distance * i, 30, false, true); if (sfBuffer == null) { MessageBox.Show("Failed to calculate the buffer: " + sf.ErrorMsg[sf.LastErrorCode]); return; } else { sfBuffer.GlobalCallback = callback; buffers.Add(sfBuffer); } } // now subtract smaller buffers from larger ones for (int i = buffers.Count - 1; i > 0; i--) { Shapefile sfDiff = buffers[i].Difference(false, buffers[i - 1], false); if (sfDiff == null) { MessageBox.Show("Failed to calculate the difference: " + sf.ErrorMsg[sf.LastErrorCode]); return; } else { buffers[i] = sfDiff; } } // pass all the resulting shapes to a single shapefile and mark their distance Shapefile sfResult = buffers[0].Clone(); sfResult.GlobalCallback = callback; int fieldIndex = sfResult.EditAddField("Distance", FieldType.DOUBLE_FIELD, 10, 12); for (int i = 0; i < buffers.Count; i++) { Shapefile sfBuffer = buffers[i]; for (int j = 0; j < sfBuffer.NumShapes; j++) { int index = sfResult.NumShapes; sfResult.EditInsertShape(sfBuffer.Shape[j].Clone(), ref index); sfResult.EditCellValue(fieldIndex, index, distance * (i + 1)); } } // create visualization categories sfResult.DefaultDrawingOptions.FillType = tkFillType.ftStandard; sfResult.Categories.Generate(fieldIndex, tkClassificationType.ctUniqueValues, 0); sfResult.Categories.ApplyExpressions(); // apply color scheme var scheme = new ColorScheme(); scheme.SetColors2(tkMapColor.LightBlue, tkMapColor.LightYellow); sfResult.Categories.ApplyColorScheme(tkColorSchemeType.ctSchemeGraduated, scheme); layerHandle = axMap1.AddLayer(sfResult, true); axMap1.Redraw(); //sfResult.SaveAs(@"c:\buffers.shp", null); } } }
/// <summary> /// The test edit layer. /// </summary> /// <returns> /// The <see cref="bool" />. /// </returns> private static bool TestEditLayer() { var layer = new OgrLayer(); layer.GlobalCallback = form; if (!layer.OpenFromDatabase(CONNECTION_STRING, "buildings", true)) { Debug.Print("Failed to open layer: " + layer.get_ErrorMsg(layer.LastErrorCode)); return(false); } // check if editing is supported for driver Debug.Print("Driver supports editing: " + layer.TestCapability(tkOgrLayerCapability.olcRandomWrite)); // now check if we can actually do it, as there can be other limitations if (!layer.get_SupportsEditing(tkOgrSaveType.ostSaveAll)) { Debug.Print("Can't edit a layer: " + layer.get_ErrorMsg(layer.LastErrorCode)); layer.Close(); return(false); } Shapefile sf = layer.GetBuffer(); if (sf != null) { // possible types of editing bool editValue = true; bool addShape = true; bool editShape = true; bool removeShape = true; if (editValue) { int shapeIndex = 0; int fieldIndex = 2; object val = sf.get_CellValue(fieldIndex, shapeIndex); sf.EditCellValue(fieldIndex, shapeIndex, "test_writing"); // this flag will notify the driver that changes should saved back to source sf.ShapeModified[shapeIndex] = true; } if (addShape) { int shapeIndex = sf.NumShapes; Shape shp = sf.get_Shape(0); shp = shp.Buffer(1, 50); // modified flag is set automatically in this case bool result = sf.EditInsertShape(shp, ref shapeIndex); Debug.Print("Shape was inserted: " + result); } if (editShape) { // since shapefile is in in-memory mode, geometry of shapes can be changed directly; // bear in mind that this won't work for file-based shapefiles, in that case get_Shape will // populate Shape object which will have no futher link with parent shapefile Shape shp = sf.get_Shape(sf.NumShapes - 1); for (int i = 0; i < shp.numPoints; i++) { double x = 0.0, y = 0.0; if (shp.get_XY(i, ref x, ref y)) { shp.put_XY(i, x + 0.01, y + 0.01); // let's move it a little } } } if (removeShape) { bool result = sf.EditDeleteShape(sf.NumShapes - 1); Debug.Print("Shape was deleted: " + result); } // saving it int count; tkOgrSaveResult saveResults = layer.SaveChanges(out count); Debug.Print("Save result: " + saveResults); Debug.Print("Number of shapes saved: " + count); // displaying info on errors for (int i = 0; i < layer.UpdateSourceErrorCount; i++) { Debug.Print( "Error for shape id {0}: {1}", layer.UpdateSourceErrorShapeIndex[i], layer.UpdateSourceErrorMsg[i]); } return(true); } layer.Close(); return(false); }
private static Shapefile CreateBorder(double multiplier = 1d) { var sf = new Shapefile(); if (!sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON)) { Assert.Fail("Can't create shapefile Error: " + sf.ErrorMsg[sf.LastErrorCode]); } var geoProjection = new GeoProjection(); // WGS 84 / UTM zone 31N if (!geoProjection.ImportFromEPSG(32631)) { Assert.Fail("Can't ImportFromEPSG Error: " + geoProjection.ErrorMsg[geoProjection.LastErrorCode]); } sf.GeoProjection = geoProjection; const double startX = 693502.4; const double startY = 5841019.6; var shp = new Shape(); if (!shp.Create(ShpfileType.SHP_POLYGON)) { Assert.Fail("Can't create shape Error: " + shp.ErrorMsg[shp.LastErrorCode]); } var numPoints = 0; if (!shp.InsertPoint(new Point { x = startX, y = startY }, ref numPoints)) { Assert.Fail($"Can't insert point with id: {numPoints} Error: {shp.ErrorMsg[shp.LastErrorCode]}"); } if (!shp.InsertPoint(new Point { x = startX - 107 * multiplier, y = startY - 12 * multiplier }, ref numPoints)) { Assert.Fail($"Can't insert point with id: {numPoints} Error: {shp.ErrorMsg[shp.LastErrorCode]}"); } if (!shp.InsertPoint(new Point { x = startX - 9 * multiplier, y = startY - 99 * multiplier }, ref numPoints)) { Assert.Fail($"Can't insert point with id: {numPoints} Error: {shp.ErrorMsg[shp.LastErrorCode]}"); } if (!shp.InsertPoint(new Point { x = startX + 11 * multiplier, y = startY - 83 * multiplier }, ref numPoints)) { Assert.Fail($"Can't insert point with id: {numPoints} Error: {shp.ErrorMsg[shp.LastErrorCode]}"); } if (!shp.InsertPoint(new Point { x = startX, y = startY }, ref numPoints)) { Assert.Fail($"Can't insert point with id: {numPoints} Error: {shp.ErrorMsg[shp.LastErrorCode]}"); } if (!shp.IsValid) { Assert.Fail("Shape is invalid: " + shp.IsValidReason); } var numShapes = 0; if (!sf.EditInsertShape(shp, ref numShapes)) { Assert.Fail("Can't insert shape Error: " + sf.ErrorMsg[sf.LastErrorCode]); } Assert.IsFalse(sf.HasInvalidShapes(), "Created border file has invalid shapes"); return(sf); }
private void loadPolygonFromTextToolStripMenuItem_Click(object sender, EventArgs e) { if (openDialog.ShowDialog() != DialogResult.OK) { return; } List <MapWinGIS.Point> coords = new List <MapWinGIS.Point>(); string file_txt = openDialog.FileName; string[] lines = System.IO.File.ReadAllLines(file_txt); for (int i = 0; i < lines.Length; i++) { MapWinGIS.Point pTmp = new MapWinGIS.Point(); string line = lines[i]; if (line != "") { string[] arr_line = line.Split(' '); double latt = Convert.ToDouble(arr_line[1]); double longt = Convert.ToDouble(arr_line[2]); pTmp.x = latt; pTmp.y = longt; } else { pTmp.x = 0.0; pTmp.y = 0.0; } coords.Add(pTmp); } // Create Shaefile load Polygon var sfPoly = new Shapefile(); bool result = sfPoly.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON); if (!result) { MessageBox.Show(sfPoly.ErrorMsg[sfPoly.LastErrorCode]); } else { Shape shpPoly = new Shape(); shpPoly.Create(ShpfileType.SHP_POLYGON); int numberPoly = 0; int numPoint = 0; for (int i = 0; i < coords.Count; i++) { if (coords[i].x == 0.0) { if (i != 0) { sfPoly.EditInsertShape(shpPoly, ref numberPoly); numberPoly += 1; } numPoint = 0; shpPoly = new Shape(); shpPoly.Create(ShpfileType.SHP_POLYGON); } else { shpPoly.InsertPoint(coords[i], ref numPoint); numPoint += 1; } } sfPoly.EditInsertShape(shpPoly, ref numberPoly); } indexTxt = mapControl.AddLayer(sfPoly, true); // Add to Tree treeLayers.CheckBoxes = true; treeLayers.AfterCheck += treeLayer_AfterCheck; TreeNode layerNode = new TreeNode("Polygon from Text"); layerNode.Checked = true; treeLayers.Nodes[0].Nodes.Add(layerNode); layerNode.Parent.Checked = true; }
private void mapControl_MouseDownEvent(object sender, _DMapEvents_MouseDownEvent e) { if (e.button == 2 && listLabel.Visible) { ListViewItem x = listLabel.Items[listLabel.SelectedIndices[0]]; string type = x.SubItems[1].Text; FormEnterLabel enter = new FormEnterLabel(preSelectedShape.ToString(), type); enter.ShowDialog(); string str_ = enter.label; String[] rowData = new String[3]; rowData[0] = preSelectedShape.ToString(); rowData[1] = type; rowData[2] = str_; ListViewItem item = new ListViewItem(rowData); listLabel.Items.RemoveAt(preSelectedShape); listLabel.Items.Insert(preSelectedShape, item); } if (!toolGetValues.Checked) { return; } Shape shp = new Shape(); if (e.button == 1) // left button { Shapefile sf = mapControl.get_Shapefile(mapControl.NumLayers - 1); shp.Create(ShpfileType.SHP_POINT); MapWinGIS.Point pnt = new MapWinGIS.Point(); double x = 0.0; double y = 0.0; mapControl.PixelToProj(e.x, e.y, ref x, ref y); Console.WriteLine(x.ToString() + "," + y.ToString()); pnt.x = x; pnt.y = y; int index = shp.numPoints; shp.InsertPoint(pnt, ref index); index = sf.NumShapes; if (!sf.EditInsertShape(shp, ref index)) { MessageBox.Show("Failed to insert shape: " + sf.ErrorMsg[sf.LastErrorCode]); return; } mapControl.Redraw(); } else { return; } int row; int column; double X = 0; double Y = 0; mapControl.PixelToProj(e.x, e.y, ref X, ref Y); MapWinGIS.Image img = mapControl.get_Image(0); img.ProjectionToImage(X, Y, out column, out row); double[] vals = new double[img.NoBands]; for (int i = 1; i <= img.NoBands; i++) { GdalRasterBand rst = img.get_Band(i); double pVal; rst.get_Value(row, column, out pVal); vals[i - 1] = pVal; } FormRasterValue uiRasterValues = new FormRasterValue(vals); uiRasterValues.ShowDialog(); shp.Clear(); }
/// <summary> /// maps fishing grounds belonging to a target area, landing site, or type of gear gear /// </summary> /// <param name="aoiGUID"></param> /// <param name="samplingYears"></param> /// <param name="utmZone"></param> /// <param name="Aggregated"></param> /// <param name="notInclude1"></param> /// <param name="landingSiteGuid"></param> /// <param name="gearVariationGuid"></param> public void MapFishingGrounds(string aoiGUID, string samplingYears, fadUTMZone utmZone, bool Aggregated = true, bool notInclude1 = false, string landingSiteGuid = "", string gearVariationGuid = "") { var query = ""; var sf = new Shapefile(); var ifldAOI = 0; var ifldLS = 0; var ifldGear = 0; var ifldYear = 0; var ifldFG = 0; var ifldCount = 0; var ifldMaxWt = 0; var ifldMinWt = 0; var ifldAfgWt = 0; var ifldEnumerator = 0; var ifldGearClass = 0; var ifldNumberHauls = 0; var ifldNumberFisher = 0; var ifldDateSet = 0; var ifldTimeSet = 0; var ifldDateHauled = 0; var ifldTimeHauled = 0; var ifldVessel = 0; var ifldHP = 0; var ifldCatchWt = 0; if (aoiGUID.Length > 0 && samplingYears.Length > 0 && sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { ifldAOI = sf.EditAddField("AOIName", FieldType.STRING_FIELD, 1, 255); sf.Field[ifldAOI].Alias = "Target area name"; if (Aggregated) { if (landingSiteGuid.Length > 0) { ifldLS = sf.EditAddField("LSName", FieldType.STRING_FIELD, 1, 255); sf.Field[ifldLS].Alias = "Landing site name"; } if (gearVariationGuid.Length > 0) { ifldGear = sf.EditAddField("GearName", FieldType.STRING_FIELD, 1, 255); sf.Field[ifldGear].Alias = "Gear variation used"; } ifldYear = sf.EditAddField("Year", FieldType.INTEGER_FIELD, 1, 4); sf.Field[ifldYear].Alias = "Year sampled"; ifldFG = sf.EditAddField("fg", FieldType.STRING_FIELD, 1, 25); sf.Field[ifldFG].Alias = "Fishing ground"; ifldCount = sf.EditAddField("n", FieldType.INTEGER_FIELD, 1, 4); ifldMaxWt = sf.EditAddField("MaxWt", FieldType.DOUBLE_FIELD, 2, 8); sf.Field[ifldMaxWt].Alias = "Maximum catch weight"; ifldMinWt = sf.EditAddField("MinWt", FieldType.DOUBLE_FIELD, 2, 8); sf.Field[ifldMinWt].Alias = "Minimum catch weight"; ifldAfgWt = sf.EditAddField("AvgWt", FieldType.DOUBLE_FIELD, 2, 8); sf.Field[ifldAfgWt].Alias = "Average catch weight"; if (gearVariationGuid.Length > 0) { query = $@"SELECT tblAOI.AOIName, tblLandingSites.LSName, tblGearVariations.Variation, tblSampling.FishingGround, Year([SamplingDate]) AS samplingYear, Count(tblSampling.SamplingGUID) AS n, Max(tblSampling.WtCatch) AS MaxCatch, Min(tblSampling.WtCatch) AS MinCatch, Avg(tblSampling.WtCatch) AS AvgCatch FROM tblGearVariations INNER JOIN ((tblAOI INNER JOIN tblLandingSites ON tblAOI.AOIGuid = tblLandingSites.AOIGuid) INNER JOIN tblSampling ON tblLandingSites.LSGUID = tblSampling.LSGUID) ON tblGearVariations.GearVarGUID = tblSampling.GearVarGUID WHERE tblLandingSites.LSGUID={{{landingSiteGuid}}} AND tblSampling.GearVarGUID={{{gearVariationGuid}}} GROUP BY tblAOI.AOIName, tblLandingSites.LSName, tblGearVariations.Variation, tblSampling.FishingGround, Year([SamplingDate]) "; if (notInclude1) { query += $"HAVING Count(tblSampling.SamplingGUID)>1 AND Year([SamplingDate]) In ({samplingYears})"; } else { query += $"HAVING Year([SamplingDate]) In ({samplingYears})"; } } else if (landingSiteGuid.Length > 0) { query = $@"SELECT tblAOI.AOIName, tblLandingSites.LSName, tblSampling.FishingGround, Year([SamplingDate]) AS samplingYear, Count(tblSampling.SamplingGUID) AS n, Max(tblSampling.WtCatch) AS MaxCatch, Min(tblSampling.WtCatch) AS MinCatch, Avg(tblSampling.WtCatch) AS AvgCatch FROM (tblAOI INNER JOIN tblLandingSites ON tblAOI.AOIGuid = tblLandingSites.AOIGuid) INNER JOIN tblSampling ON tblLandingSites.LSGUID = tblSampling.LSGUID WHERE tblLandingSites.LSGUID={{{landingSiteGuid}}} GROUP BY tblAOI.AOIName, tblLandingSites.LSName, tblSampling.FishingGround, Year([SamplingDate]) "; if (notInclude1) { query += $"HAVING Count(tblSampling.SamplingGUID)>1 AND Year([SamplingDate]) In ({samplingYears})"; } else { query += $"HAVING Year([SamplingDate]) In ({samplingYears})"; } } else { query = $@"SELECT tblAOI.AOIName, tblSampling.FishingGround, Year([SamplingDate]) AS samplingYear, Count(tblSampling.SamplingGUID) AS n, Max(tblSampling.WtCatch) AS MaxCatch, Min(tblSampling.WtCatch) AS MinCatch, Avg(tblSampling.WtCatch) AS AvgCatch FROM tblAOI INNER JOIN tblSampling ON tblAOI.AOIGuid = tblSampling.AOI GROUP BY tblAOI.AOIName, tblSampling.FishingGround, tblSampling.AOI, Year([SamplingDate]) "; if (notInclude1) { query += $"HAVING tblSampling.AOI= {{{aoiGUID}}} AND Count(tblSampling.SamplingGUID)>1 AND Year([SamplingDate]) In ({samplingYears})"; } else { query += $"HAVING tblSampling.AOI= {{{aoiGUID}}} AND Year([SamplingDate]) In ({samplingYears})"; } } } else //not aggregated { ifldEnumerator = sf.EditAddField("Enumerat", FieldType.STRING_FIELD, 1, 100); sf.Field[ifldEnumerator].Alias = "Name of enumerator"; ifldLS = sf.EditAddField("LSName", FieldType.STRING_FIELD, 1, 255); sf.Field[ifldLS].Alias = "Landing site name"; ifldGearClass = sf.EditAddField("GearClass", FieldType.STRING_FIELD, 1, 100); sf.Field[ifldGearClass].Alias = "Gear class used"; ifldGear = sf.EditAddField("GearName", FieldType.STRING_FIELD, 1, 255); sf.Field[ifldGear].Alias = "Gear variation used"; ifldYear = sf.EditAddField("Year", FieldType.INTEGER_FIELD, 1, 4); sf.Field[ifldYear].Alias = "Year sampled"; ifldFG = sf.EditAddField("fg", FieldType.STRING_FIELD, 1, 25); sf.Field[ifldFG].Alias = "Fishing ground"; ifldNumberHauls = sf.EditAddField("NoHauls", FieldType.INTEGER_FIELD, 1, 2); sf.Field[ifldNumberHauls].Alias = "Number of hauls"; ifldNumberFisher = sf.EditAddField("NoFishers", FieldType.INTEGER_FIELD, 1, 2); sf.Field[ifldNumberFisher].Alias = "Number of fishers"; ifldDateSet = sf.EditAddField("DateSet", FieldType.DATE_FIELD, 1, 2); sf.Field[ifldDateSet].Alias = "Date gear set"; ifldTimeSet = sf.EditAddField("TimeSet", FieldType.DATE_FIELD, 1, 2); sf.Field[ifldTimeSet].Alias = "Time gear set"; ifldDateHauled = sf.EditAddField("DateHaul", FieldType.DATE_FIELD, 1, 2); sf.Field[ifldDateHauled].Alias = "Date gear hauled"; ifldTimeHauled = sf.EditAddField("TimeHaul", FieldType.DATE_FIELD, 1, 2); sf.Field[ifldTimeHauled].Alias = "Time gear hauled"; ifldVessel = sf.EditAddField("VesType", FieldType.STRING_FIELD, 1, 30); sf.Field[ifldVessel].Alias = "Type of vessel used"; ifldHP = sf.EditAddField("hp", FieldType.STRING_FIELD, 1, 2); sf.Field[ifldHP].Alias = "Engine hp"; ifldCatchWt = sf.EditAddField("CatchWt", FieldType.DOUBLE_FIELD, 2, 8); sf.Field[ifldCatchWt].Alias = "Catch weight"; query = @"SELECT tblAOI.AOIName, tblEnumerators.EnumeratorName, tblLandingSites.LSName, tblGearClass.GearClassName, tblGearVariations.Variation, Year([SamplingDate]) AS samplingYear, tblSampling.FishingGround, tblSampling.NoHauls, tblSampling.NoFishers, tblSampling.DateSet, tblSampling.TimeSet, tblSampling.DateHauled, tblSampling.TimeHauled, tblSampling.VesType, tblSampling.hp, tblSampling.WtCatch FROM (tblAOI INNER JOIN tblLandingSites ON tblAOI.AOIGuid = tblLandingSites.AOIGuid) INNER JOIN ((tblGearClass INNER JOIN tblGearVariations ON tblGearClass.GearClass = tblGearVariations.GearClass) INNER JOIN (tblEnumerators RIGHT JOIN tblSampling ON tblEnumerators.EnumeratorID = tblSampling.Enumerator) ON tblGearVariations.GearVarGUID = tblSampling.GearVarGUID) ON tblLandingSites.LSGUID = tblSampling.LSGUID "; if (gearVariationGuid.Length > 0) { query += $@"WHERE Year([SamplingDate]) In({samplingYears}) AND tblSampling.LSGUID ={{{landingSiteGuid}}} AND tblSampling.GearVarGUID ={{{gearVariationGuid}}}"; } else if (landingSiteGuid.Length > 0) { query += $"WHERE Year([SamplingDate]) In({samplingYears}) AND tblSampling.LSGUID ={{{landingSiteGuid}}}"; } else { query += $"WHERE Year([SamplingDate]) In({samplingYears}) AND tblSampling.AOI ={{{aoiGUID}}}"; } } using (var conection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + global.MDBPath)) { conection.Open(); using (var adapter = new OleDbDataAdapter(query, conection)) using (var myDT = new DataTable()) { adapter.Fill(myDT); //var n = 0; foreach (DataRow dr in myDT.Rows) { var fg = dr["FishingGround"].ToString(); if (fg.Length > 0) { var shp = new MapWinGIS.Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { var proceed = false; if (RemoveInland && !FishingGrid.MinorGridIsInland(fg)) { proceed = true; } else if (!RemoveInland) { proceed = true; } if (proceed) { var iShp = 0; if (_geoProjection.IsGeographic) { var result = FishingGrid.Grid25ToLatLong(fg, utmZone); iShp = shp.AddPoint(result.longitude, result.latitude); } else { FishingGrid.Grid25_to_UTM(fg, out int x, out int y); iShp = shp.AddPoint(x, y); } if (iShp >= 0 && sf.EditInsertShape(shp, 0)) { sf.EditCellValue(ifldAOI, iShp, dr["AOIName"].ToString()); sf.EditCellValue(ifldYear, iShp, int.Parse(dr["samplingYear"].ToString())); sf.EditCellValue(ifldFG, iShp, dr["FishingGround"].ToString()); //aggregated if (Aggregated) { if (landingSiteGuid.Length > 0) { sf.EditCellValue(ifldLS, iShp, dr["LSName"].ToString()); } if (gearVariationGuid.Length > 0) { sf.EditCellValue(ifldGear, iShp, dr["Variation"].ToString()); } sf.EditCellValue(ifldCount, iShp, int.Parse(dr["n"].ToString())); sf.EditCellValue(ifldMaxWt, iShp, double.Parse(dr["MaxCatch"].ToString())); sf.EditCellValue(ifldMinWt, iShp, double.Parse(dr["MinCatch"].ToString())); sf.EditCellValue(ifldAfgWt, iShp, double.Parse(dr["AvgCatch"].ToString())); Console.WriteLine($"n-{sf.CellValue[ifldCount, iShp]}, AvgCatch -{sf.CellValue[ifldAfgWt, iShp]}"); } //not aggregated else { sf.EditCellValue(ifldEnumerator, iShp, dr["EnumeratorName"].ToString()); sf.EditCellValue(ifldLS, iShp, dr["LSName"].ToString()); sf.EditCellValue(ifldGearClass, iShp, dr["GearClassName"].ToString()); sf.EditCellValue(ifldGear, iShp, dr["Variation"].ToString()); if (dr["NoHauls"].ToString().Length > 0) { sf.EditCellValue(ifldNumberHauls, iShp, int.Parse(dr["NoHauls"].ToString())); } if (dr["NoFishers"].ToString().Length > 0) { sf.EditCellValue(ifldNumberFisher, iShp, int.Parse(dr["NoFishers"].ToString())); } if (dr["DateSet"].ToString().Length > 0) { sf.EditCellValue(ifldDateSet, iShp, DateTime.Parse(dr["DateSet"].ToString())); } if (dr["TimeSet"].ToString().Length > 0) { sf.EditCellValue(ifldTimeSet, iShp, DateTime.Parse(dr["TimeSet"].ToString())); } if (dr["DateHauled"].ToString().Length > 0) { sf.EditCellValue(ifldDateHauled, iShp, DateTime.Parse(dr["DateHauled"].ToString())); } if (dr["TimeHauled"].ToString().Length > 0) { sf.EditCellValue(ifldTimeHauled, iShp, DateTime.Parse(dr["TimeHauled"].ToString())); } if (dr["VesType"].ToString().Length > 0) { var vesselType = "Motorized"; switch (int.Parse(dr["VesType"].ToString())) { case 1: vesselType = "Motorized"; break; case 2: vesselType = "Non-motorized"; break; case 3: vesselType = "No vessel used"; break; case 4: vesselType = "Not provided"; break; } sf.EditCellValue(ifldVessel, iShp, vesselType); } if (dr["hp"].ToString().Length > 0) { sf.EditCellValue(ifldHP, iShp, dr["hp"].ToString()); } sf.EditCellValue(ifldCatchWt, iShp, double.Parse(dr["WtCatch"].ToString())); } } } } } //n++; } } } MapLayersHandler.RemoveLayer("Fishing grounds"); if (sf.NumShapes > 0) { sf.GeoProjection = _geoProjection; sf.CollisionMode = tkCollisionMode.AllowCollisions; sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; sf.DefaultDrawingOptions.FillColor = new Utils().ColorByName(tkMapColor.Red); sf.DefaultDrawingOptions.LineColor = new Utils().ColorByName(tkMapColor.White); ClassificationType classificationType = ClassificationType.None; if (Aggregated) { classificationType = ClassificationType.NaturalBreaks; ShapefileLayerHelper.CategorizeNumericPointLayer(sf, ifldCount); } else { sf.DefaultDrawingOptions.PointSize = 7; } sf.SelectionAppearance = tkSelectionAppearance.saDrawingOptions; sf.SelectionDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; if (ShapefileLayerHelper.ExtentsPosition(MapControl.Extents, sf.Extents) == ExtentCompare.excoOutside) { var newExtent = MapControl.Extents; newExtent.MoveTo(sf.Extents.Center.x, sf.Extents.Center.y); MapControl.Extents = newExtent; } var h = MapLayersHandler.AddLayer(sf, "Fishing grounds", true, true); MapLayersHandler[h].ClassificationType = classificationType; } } }
public bool MapSamplingFishingGround(string samplingGuid, fadUTMZone utmZone, string layerName) { var success = false; string refNo = ""; List <string> fg = new List <string>(); DataTable dt = new DataTable(); using (var conection = new OleDbConnection(global.ConnectionString)) { try { conection.Open(); var sql = $"Select RefNo from tblSampling WHERE SamplingGUID = {{{samplingGuid}}}"; var adapter = new OleDbDataAdapter(sql, conection); adapter.Fill(dt); DataRow dr = dt.Rows[0]; refNo = dr["RefNo"].ToString(); sql = $@"SELECT FishingGround FROM tblSampling WHERE SamplingGUID={{{samplingGuid}}} UNION ALL SELECT GridName from tblGrid WHERE SamplingGUID={{{samplingGuid}}}"; dt.Rows.Clear(); adapter = new OleDbDataAdapter(sql, conection); adapter.Fill(dt); for (int i = 0; i < dt.Rows.Count; i++) { dr = dt.Rows[i]; fg.Add(dr["FishingGround"].ToString()); } } catch (Exception ex) { Logger.Log(ex.Message, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name); } } if (fg.Count > 0) { var sf = new Shapefile(); if (sf.CreateNew("", ShpfileType.SHP_POINT)) { MapLayersHandler.RemoveLayer(layerName); sf.GeoProjection = _geoProjection; var ifldLabel = sf.EditAddField("Label", FieldType.STRING_FIELD, 1, 15); sf.FieldByName["Label"].Alias = "Fishing ground"; var ifldRefNo = sf.EditAddField("RefNo", FieldType.STRING_FIELD, 1, 20); sf.FieldByName["RefNo"].Alias = "Reference number"; foreach (var item in fg) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { var iShp = 0; var result = FishingGrid.Grid25ToLatLong(item, utmZone); iShp = shp.AddPoint(result.longitude, result.latitude); if (iShp >= 0 && sf.EditInsertShape(shp, 0)) { sf.EditCellValue(ifldLabel, iShp, item); sf.EditCellValue(ifldRefNo, iShp, refNo); sf.CollisionMode = tkCollisionMode.AllowCollisions; } } } sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsCircle); sf.DefaultDrawingOptions.FillColor = new Utils().ColorByName(tkMapColor.Red); sf.DefaultDrawingOptions.PointSize = 7; sf.DefaultDrawingOptions.LineVisible = false; success = MapLayersHandler.AddLayer(sf, layerName, true, true) >= 0; if (MapControl == null) { MapControl = global.MappingForm.MapControl; } if (!MapControl.Extents.ToShape().Contains(sf.Extents.ToShape())) { Point pt = sf.Extents.ToShape().Center; Extents ext = MapControl.Extents; ext.MoveTo(pt.x, pt.y); MapControl.Extents = ext; } } } return(success); }