private bool Save() { var list = tableLayoutPanel1.Controls.OfType <TextBox>(); foreach (var txt in list) { if (!txt.Enabled) { continue; } int fieldIndex = (int)txt.Tag; var fld = _sf.Field[fieldIndex]; switch (fld.Type) { case FieldType.STRING_FIELD: { _sf.EditCellValue(fieldIndex, _shapeIndex, txt.Text); break; } case FieldType.INTEGER_FIELD: { int val; if (!Int32.TryParse(txt.Text, out val)) { txt.Focus(); //MessageHelper.Info("Failed to parse integer value: " + txt.Text); MessageBox.Show("Failed to parse integer value: " + txt.Text); return(false); } _sf.EditCellValue(fieldIndex, _shapeIndex, val); break; } case FieldType.DOUBLE_FIELD: { double val; if (!Double.TryParse(txt.Text, out val)) { txt.Focus(); //MessageHelper.Info("Faield to parse double value: " + txt.Text); MessageBox.Show("Faield to parse double value: " + txt.Text); return(false); } _sf.EditCellValue(fieldIndex, _shapeIndex, val); break; } } } return(true); }
// <summary> // A shorter variant of procedure with less checks // </summary> public void CalculateAreaFast(Shapefile sf) { bool editing = sf.EditingTable; if (!sf.EditingTable) { if (sf.StartEditingTable(null)) { MessageBox.Show("Failed to open editing mode: " + sf.ErrorMsg[sf.LastErrorCode]); return; } int fldIndex = sf.Table.FieldIndexByName["Area"]; if (fldIndex == -1) { MessageBox.Show("Field index doesn't exists"); } else { for (int i = 0; i < sf.NumShapes; i++) { Shape shp = sf.Shape[i]; sf.EditCellValue(fldIndex, i, shp.Area); } if (!editing) { sf.StopEditingTable(true, null); } } } }
private void EditMenu_Click(object sender, System.EventArgs e) { try { if (lv.SelectedIndices.Count > 0 && m_SelShape != -1) { string fieldValue = frmEdit.ShowFrm(this, lv.SelectedItems[0].SubItems[1].Text); //if the cancel button wasn't pressed then save the new value if (fieldValue != null) { m_ShapeFile.StartEditingTable(null); if (m_ShapeFile.EditCellValue(lv.SelectedIndices[0], m_SelShape, fieldValue) == false) { MapWinUtility.Logger.Msg("Error in EditMenu_Click(), Message: " + m_ShapeFile.get_ErrorMsg(m_ShapeFile.LastErrorCode)); } m_ShapeFile.StopEditingTable(true, null); //update the value in the list view lv.SelectedItems[0].SubItems[1].Text = fieldValue; } } } catch (System.Exception ex) { ShowErrorBox("EditMenu_Click()", ex.Message); } }
public static void UpdateAOIName(string aoiName) { MapWindowManager.MapLayersHandler.EditLayer(_hAOI, aoiName, true); Shapefile sf = (Shapefile)MapWindowManager.MapLayersHandler.get_MapLayer(_hAOI).LayerObject; var fldName = sf.EditAddField("Name", FieldType.STRING_FIELD, 1, 1); sf.EditCellValue(fldName, 0, aoiName); }
public int AddSubgrid(SubGridType subgridType, int position, int iFldDirection, int ifldBoundary, int ifldLineType) { int shpIndex = -1; int ptX = 0; int ptY = 0; string lineType = subgridType == SubGridType.Row ? "R" : "C"; int subgridCount = (int)Math.Sqrt(_grid25MajorGrid.SubGridCount); for (int r = 0; r < subgridCount - 1; r++) { Shape shp = new Shape(); if (shp.Create(ShpfileType.SHP_POLYLINE)) { if (subgridType == SubGridType.Column) { ptX = (position * CELLSIDE) + _minorGridOriginX + ((CELLSIDE / subgridCount) * (r + 1)); ptY = _minorGridOriginY; shp.AddPoint(ptX, ptY); ptX = (position * CELLSIDE) + _minorGridOriginX + ((CELLSIDE / subgridCount) * (r + 1)); ptY = _minorGridOriginY + _minorGridMBRHeight; shp.AddPoint(ptX, ptY); } else { ptX = _minorGridOriginX; ptY = (position * CELLSIDE) + _minorGridOriginY + ((CELLSIDE / subgridCount) * (r + 1)); shp.AddPoint(ptX, ptY); ptX = _minorGridOriginX + _minorGridMBRWidth; ptY = (position * CELLSIDE) + _minorGridOriginY + ((CELLSIDE / subgridCount) * (r + 1)); shp.AddPoint(ptX, ptY); } shpIndex = _shapefileMinorGridLines.EditAddShape(shp); if (shpIndex >= 0) { _shapefileMinorGridLines.EditCellValue(iFldDirection, shpIndex, lineType); _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "F"); _shapefileMinorGridLines.EditCellValue(ifldLineType, shpIndex, "SG"); } } } return(shpIndex); }
private void CreateShape(string path, DataTable dataTable) { Shapefile myShapefile; try { myShapefile = new Shapefile(); string fileName = Path.GetFileNameWithoutExtension(txtBox_excel.Text); string shapeilePath = Path.GetDirectoryName(path) + "\\" + fileName + ".shp"; Directory.CreateDirectory(Path.GetDirectoryName(shapeilePath)); myShapefile.CreateNew(shapeilePath, 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 = 1; myShapefile.EditInsertField(myField, ref intFieldIndex, null); int myCounter = 0; int myShapeIndex = 0; //First Create header CreateHeader(dataTable.Columns, myShapefile); for (int i = 0; i < dataTable.Rows.Count; i++) { MapWinGIS.Shape myShape = new Shape(); myShape.Create(ShpfileType.SHP_POINT); MapWinGIS.Point myPoint = new MapWinGIS.Point(); myPoint.x = Convert.ToDouble(dataTable.Rows[i][x_Index]); myPoint.y = Convert.ToDouble(dataTable.Rows[i][y_Index]); object fld_Value = dataTable.Rows[i][0]; int myPointIndex = 0; myShape.InsertPoint(myPoint, ref myPointIndex); myShapefile.EditInsertShape(myShape, ref myShapeIndex); myShapefile.EditCellValue(0, myShapeIndex, fld_Value); CreatePointData(dataTable, myShapefile, myShapeIndex, i); myShapeIndex++; myCounter++; } GeoProjection proj = new GeoProjection(); // EPSG code proj.ImportFromEPSG(4326); // WGS84 myShapefile.GeoProjection = proj; myShapefile.StopEditingShapes(true, true, null); myShapefile.Close(); } catch (Exception) { throw; } }
private void CreatePointData(DataTable dataTable, Shapefile myShapefile, int myShapeIndex, int rowIndex) { int intFieldIndex = 1; string fld_Value = string.Empty; for (int i = 0; i < dataTable.Columns.Count; i++) { myShapefile.EditCellValue(intFieldIndex, myShapeIndex, dataTable.Rows[rowIndex][i]); intFieldIndex++; } }
public static void CopyAttributes(this Shapefile sf, int sourceIndex, Shapefile target, int targetIndex) { for (int i = 0; i < sf.NumFields; i++) { if (sf.Field[i].Name.ToLower() == "mwshapeid") { continue; } target.EditCellValue(i, targetIndex, sf.CellValue[i, sourceIndex]); } }
// <summary> // Submits new attibutes and updates the labels // </summary> void BtnClick(object sender, EventArgs e) { Form form = (sender as Control).Parent as Form; if (form == null) { return; } Button btn = sender as Button; if (btn != null) { int layerHandle = axMap1.get_LayerHandle(0); Shapefile sf = axMap1.get_Shapefile(layerHandle); if (sf != null) { if (btn.Text == "Ok") { // now we shall find the selected shape, the one being edited // in real-world application would be better of course to store the index of this shape in private variable int shapeIndex = -1; for (int i = 0; i < sf.NumShapes; i++) { if (sf.ShapeSelected[i]) { shapeIndex = i; break; } } if (shapeIndex != -1) { foreach (Control control in form.Controls) { if (control is TextBox) { int fieldIndex = sf.Table.FieldIndexByName[control.Name]; if (fieldIndex != -1) { sf.EditCellValue(fieldIndex, shapeIndex, control.Text); } } } sf.Labels.Expression = sf.Labels.Expression; // update the labels axMap1.Redraw(); } } } } form.Close(); }
private static bool FillFieldWithUniqueInt(Shapefile sf, int fieldIndex) { int counter = 0; for (int x = 0; x < sf.NumShapes; x++) { if (!sf.EditCellValue(fieldIndex, x, counter++)) { return(false); } } return(true); }
public void EditAttribute() { if (!sf.StartEditingShapes(true, null)) { MessageBox.Show("Failed to start edit mode: " + sf.ErrorMsg[sf.LastErrorCode]); } else { int fieldIndex = sf.EditAddField("shapeStr", FieldType.STRING_FIELD, 0, 0); for (int i = 0; i < sf.NumShapes; i++) { sf.EditCellValue(fieldIndex, i, pointData[i].str); } } }
public static void CopyAttributes(this Shapefile sf, int sourceIndex, Shapefile target, int targetIndex, Dictionary <int, int> fieldMap) { if (fieldMap == null || target == null) { return; } var list = fieldMap.ToList(); foreach (var fld in list) { object val = sf.get_CellValue(fld.Key, sourceIndex); target.EditCellValue(fld.Value, targetIndex, val); } }
public static void CalculateArea(this Shapefile sf) { if (sf == null) { return; } if (sf.ShapefileType2D != ShpfileType.SHP_POLYGON) { MessageHelper.Info("Area can be calculated for polygon shapefiles only."); return; } bool editing = sf.EditingTable; if (!editing) { if (!sf.StartEditingTable()) { MessageHelper.Warn("Failed to start editing mode for table."); return; } } bool ellipsoid = App.Map.Measuring.IsUsingEllipsoid; string fieldName = ellipsoid ? "GeoArea" : "Area"; int fieldIndex = sf.EditAddField(fieldName, FieldType.DOUBLE_FIELD, 6, 18); for (int i = 0; i < sf.NumShapes; i++) { double area = ellipsoid ? App.Map.GeodesicArea(sf.Shape[i]) : sf.Shape[i].Area; sf.EditCellValue(fieldIndex, i, area); } if (!editing) { if (!sf.StopEditingTable()) { MessageHelper.Warn("Failed to save calculated area to the datasource."); return; } } MessageHelper.Info(string.Format("Area was calculated in {0} field.", fieldName)); }
/// <summary>Changes the data in the shapefile</summary> /// <param name = "dataTable">The datatable with data.</param> private void ChangeData(DataTable dataTable) { var datatChangedData = dataTable.GetChanges(); if (datatChangedData != null) { for (var i = 0; i < datatChangedData.Rows.Count; i++) { for (var j = 0; j < _shapefile.NumFields; j++) { var shapeId = Convert.ToInt32(datatChangedData.Rows[i][0]); if (!_shapefile.EditCellValue(j, shapeId, datatChangedData.Rows[i][j + 1])) { MessageBox.Show(string.Format("Error in EditCellValue: {0}", _shapefile.get_ErrorMsg(_shapefile.LastErrorCode))); } } } } }
/// <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); }
// <summary> // Loads the layers and registers event handler // </summary> public void RemoveShape(AxMap axMap1, string dataPath) { axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR; string filename = dataPath + "natural.shp"; if (!File.Exists(filename)) { MessageBox.Show("Couldn't file the file: " + filename); return; } var sf = new Shapefile(); sf.Open(filename, null); int layerHandle = axMap1.AddLayer(sf, true); sf = axMap1.get_Shapefile(layerHandle); // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding if (!sf.StartEditingShapes(true, null)) { MessageBox.Show("Failed to start edit mode: " + sf.ErrorMsg[sf.LastErrorCode]); } else { int fieldIndex = sf.EditAddField("ShapeIndex", FieldType.INTEGER_FIELD, 0, 0); for (int i = 0; i < sf.NumShapes; i++) { sf.EditCellValue(fieldIndex, i, i); } sf.Labels.Generate("[ShapeIndex]", tkLabelPositioning.lpCentroid, false); sf.Labels.Synchronized = true; sf.Labels.TextRenderingHint = tkTextRenderingHint.SystemDefault; axMap1.SendMouseDown = true; MapEvents.MouseDownEvent += AxMap1MouseDownEvent1; // change MapEvents to axMap1 axMap1.MapUnits = tkUnitsOfMeasure.umMeters; axMap1.CurrentScale = 50000; axMap1.CursorMode = tkCursorMode.cmNone; } }
public bool MapGearDistribution(List <GearInventoryMappingItem> distributionList, string gearName, bool doFisherJenks = false) { Shapefile sf = new Shapefile(); if (sf.CreateNew("", ShpfileType.SHP_POINT)) { sf.GeoProjection = _mapControl.GeoProjection; int ifldProjectName = sf.EditAddField("Inventory project", FieldType.STRING_FIELD, 1, 50); int ifldProvince = sf.EditAddField("Province", FieldType.STRING_FIELD, 1, 30); int ifldMunicipalityName = sf.EditAddField("Municipality", FieldType.STRING_FIELD, 1, 30); int ifldMuni = sf.EditAddField("Muni", FieldType.STRING_FIELD, 1, 8); int ifldGear = sf.EditAddField("Gear", FieldType.STRING_FIELD, 1, 50); int ifldX = sf.EditAddField("x", FieldType.DOUBLE_FIELD, 9, 12); int ifldY = sf.EditAddField("y", FieldType.DOUBLE_FIELD, 9, 12); int ifldCount = sf.EditAddField("n", FieldType.INTEGER_FIELD, 1, 7); int ifldCommercial = sf.EditAddField("Commercial", FieldType.INTEGER_FIELD, 1, 7); int ifldMunicipalMot = sf.EditAddField("Motorized", FieldType.INTEGER_FIELD, 1, 7); int ifldMunicipalNonMot = sf.EditAddField("Non-motorized", FieldType.INTEGER_FIELD, 1, 7); int ifldNoBoat = sf.EditAddField("No boat", FieldType.INTEGER_FIELD, 1, 7); foreach (var item in distributionList) { Shape sh = new Shape(); if (sh.Create(ShpfileType.SHP_POINT) && sh.AddPoint(item.X, item.Y) >= 0) { var iShp = sf.EditAddShape(sh); if (iShp >= 0) { sf.EditCellValue(ifldProjectName, iShp, item.InventoryProjectName); sf.EditCellValue(ifldProvince, iShp, item.ProvinceName); sf.EditCellValue(ifldMunicipalityName, iShp, item.Municipality); //sf.EditCellValue(ifldMunNameAbbrev, iShp, item.Municipality.Substring(0, 4)); sf.EditCellValue(ifldMuni, iShp, Database.Classes.LGUs.ShortenPlaceName(item.Municipality)); sf.EditCellValue(ifldGear, iShp, item.GearVariationName); sf.EditCellValue(ifldX, iShp, item.X); sf.EditCellValue(ifldY, iShp, item.Y); sf.EditCellValue(ifldCount, iShp, item.TotalUsed); sf.EditCellValue(ifldCommercial, iShp, item.CountCommercial); sf.EditCellValue(ifldMunicipalMot, iShp, item.CountMunicipalMotorized); sf.EditCellValue(ifldMunicipalNonMot, iShp, item.CountMunicipalNonMotorized); sf.EditCellValue(ifldNoBoat, iShp, item.CountNoBoat); } } } sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; sf.DefaultDrawingOptions.FillColor = new Utils().ColorByName(tkMapColor.Blue); sf.DefaultDrawingOptions.LineColor = new Utils().ColorByName(tkMapColor.White); sf.DefaultDrawingOptions.LineVisible = true; sf.CollisionMode = tkCollisionMode.AllowCollisions; Database.Classes.ClassificationType classificationType = Database.Classes.ClassificationType.NaturalBreaks; if (ComparisonAmongLGUs) { ShapefileLayerHelper.CategorizeNumericPointLayer(sf, ifldCount); } else { ShapefileLayerHelper.CategorizeNumericPointLayer(sf, GearDataFisherJenksBreaks, ifldCount, BreakSourceMaximum); classificationType = Database.Classes.ClassificationType.JenksFisher; } InventoryLayerHandle = _layersHandler.AddLayer(sf, gearName); _layersHandler[InventoryLayerHandle].ClassificationType = classificationType; //_layersHandler.set_MapLayer(h); if (Labels != null) { sf.Labels.Clear(); _layersHandler.ShapeFileLableHandler.LabelShapefile(_labelXML); } _layersHandler.SetAsPointLayerFromDatabase(_layersHandler[InventoryLayerHandle]); } return(sf.NumShapes > 0); }
public bool GeneratedSubGrids(int gridSize) { GridIsLoaded = false; var floor = Math.Floor(2000.0 / (double)gridSize); if (floor * gridSize == 2000) { SubGrids = new Shapefile(); if (SubGrids.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON)) { SubGrids.GeoProjection = MapWindowManager.Grid25MajorGrid.GeoProjection; SubGrids.EditAddField("CellID", FieldType.INTEGER_FIELD, 1, 1); SubGrids.EditAddField("CellNo", FieldType.INTEGER_FIELD, 1, 1); SubGrids.EditAddField("Name", FieldType.STRING_FIELD, 1, 1); SubGrids.Key = $"subgrid_{Name}"; var numShapes = Grid2Km.NumShapes; int id = 0; for (int x = 0; x < numShapes; x++) { var cell50km = Grid2Km.Shape[x]; var ext = cell50km.Extents; var parentName = Grid2Km.CellValue[Grid2Km.FieldIndexByName["Name"], x]; var steps = 2000 / gridSize; for (int r = 0; r < steps; r++) { var top = ext.yMax - (gridSize * r); for (int c = 0; c < steps; c++) { var left = ext.xMin + (gridSize * c); Shape cell = new Shape(); if (cell.Create(ShpfileType.SHP_POLYGON)) { cell.AddPoint(left, top); cell.AddPoint(left + (int)gridSize, top); cell.AddPoint(left + (int)gridSize, top - gridSize); cell.AddPoint(left, top - gridSize); cell.AddPoint(left, top); } id++; int idx = SubGrids.EditAddShape(cell); if (idx >= 0) { int cellNo = (r * steps) + c + 1; SubGrids.EditCellValue(SubGrids.FieldIndexByName["CellID"], idx, id); SubGrids.EditCellValue(SubGrids.FieldIndexByName["CellNo"], idx, cellNo); SubGrids.EditCellValue(SubGrids.FieldIndexByName["Name"], idx, $"{parentName}-{cellNo}"); } } } } GridIsLoaded = true; } } return(GridIsLoaded); }
public bool MapFisherBoatDistribution(List <FisherVesselInventoryItem> distributionList, string itemToMap) { Shapefile sf = new Shapefile(); if (sf.CreateNew("", ShpfileType.SHP_POINT)) { sf.GeoProjection = _mapControl.GeoProjection; int ifldProjectName = sf.EditAddField("Inventory project", FieldType.STRING_FIELD, 1, 50); int ifldProvince = sf.EditAddField("Province", FieldType.STRING_FIELD, 1, 30); int ifldMunicipalityName = sf.EditAddField("Municipality", FieldType.STRING_FIELD, 1, 30); int ifldMuni = sf.EditAddField("Muni", FieldType.STRING_FIELD, 1, 4); int ifldX = sf.EditAddField("x", FieldType.DOUBLE_FIELD, 9, 12); int ifldY = sf.EditAddField("y", FieldType.DOUBLE_FIELD, 9, 12); int ifldFishers = sf.EditAddField("Fishers", FieldType.INTEGER_FIELD, 1, 7); int ifldCommercial = sf.EditAddField("Commercial", FieldType.INTEGER_FIELD, 1, 7); int ifldMunicipalMot = sf.EditAddField("Municipal Motorized", FieldType.INTEGER_FIELD, 1, 7); int ifldMunicipalNonMot = sf.EditAddField("Municipal Non-motorized", FieldType.INTEGER_FIELD, 1, 7); foreach (var item in distributionList) { Shape sh = new Shape(); if (sh.Create(ShpfileType.SHP_POINT) && sh.AddPoint(item.X, item.Y) >= 0) { var iShp = sf.EditAddShape(sh); if (iShp >= 0) { sf.EditCellValue(ifldProjectName, iShp, item.InventoryProjectName); sf.EditCellValue(ifldProvince, iShp, item.ProvinceName); sf.EditCellValue(ifldMunicipalityName, iShp, item.Municipality); sf.EditCellValue(ifldMuni, iShp, Database.Classes.LGUs.ShortenPlaceName(item.Municipality)); sf.EditCellValue(ifldX, iShp, item.X); sf.EditCellValue(ifldY, iShp, item.Y); sf.EditCellValue(ifldFishers, iShp, item.CountFisher); sf.EditCellValue(ifldCommercial, iShp, item.CountCommercial); sf.EditCellValue(ifldMunicipalMot, iShp, item.CountMunicipalMotorized); sf.EditCellValue(ifldMunicipalNonMot, iShp, item.CountMunicipalNonMotorized); } } } sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; sf.DefaultDrawingOptions.FillColor = new Utils().ColorByName(tkMapColor.Blue); sf.DefaultDrawingOptions.LineColor = new Utils().ColorByName(tkMapColor.White); sf.DefaultDrawingOptions.LineVisible = true; sf.CollisionMode = tkCollisionMode.AllowCollisions; int fld = 0; string itemName = ""; switch (itemToMap) { case "fishers": itemName = "Total number of fishers"; fld = ifldFishers; break; case "commercial": fld = ifldCommercial; itemName = "Total number of commercial fishing vessels"; break; case "municipalMotorized": fld = ifldMunicipalMot; itemName = "Total number of municipal motorized vessels"; break; case "municipalNonMotorized": fld = ifldMunicipalNonMot; itemName = "Total number of municipal non-motorized vessels"; break; } Database.Classes.ClassificationType classificationType = Database.Classes.ClassificationType.NaturalBreaks; if (itemToMap == "fishers" || ComparisonAmongLGUs) { ShapefileLayerHelper.CategorizeNumericPointLayer(sf, fld); } else { ShapefileLayerHelper.CategorizeNumericPointLayer(sf, FisherVesselDataFisherJenksBreaks, fld, BreakSourceMaximum); classificationType = Database.Classes.ClassificationType.JenksFisher; } InventoryLayerHandle = _layersHandler.AddLayer(sf, itemName); _layersHandler[InventoryLayerHandle].IgnoreZeroWhenClassifying = true; _layersHandler[InventoryLayerHandle].ClassificationType = classificationType; if (Labels != null) { sf.Labels.Clear(); _layersHandler.ShapeFileLableHandler.LabelShapefile(_labelXML); } _layersHandler.SetAsPointLayerFromDatabase(_layersHandler[InventoryLayerHandle]); } return(sf.NumShapes > 0); }
public static Shapefile MapThisGear(string aoiGuid, string gearVarGuid, List <int> samplingYear, bool aggregate = false, bool notInclude1 = false, bool RemoveInland = false) { var query = ""; var dt = new DataTable(); var sf = new Shapefile(); using (var conection = new OleDbConnection(global.ConnectionString)) { try { conection.Open(); var years = ""; foreach (var item in samplingYear) { years += $"{item},"; } years = years.Trim(','); if (aggregate) { if (!notInclude1) { query = $@"SELECT tblSampling.FishingGround, Count(tblSampling.SamplingGUID) AS n FROM tblSampling GROUP BY tblSampling.AOI, tblSampling.GearVarGUID, Year([SamplingDate]), tblSampling.FishingGround HAVING tblSampling.AOI={{{aoiGuid}}} AND tblSampling.GearVarGUID= {{{gearVarGuid}}} AND Year([SamplingDate]) In ({years})"; } else { query = $@"SELECT tblSampling.FishingGround, Count(tblSampling.SamplingGUID) AS n FROM tblSampling GROUP BY tblSampling.FishingGround, tblSampling.AOI, tblSampling.GearVarGUID, Year([SamplingDate]) HAVING Count(tblSampling.SamplingGUID) > 1 AND tblSampling.AOI = {{{aoiGuid}}} AND tblSampling.GearVarGUID = {{{gearVarGuid}}} AND Year([SamplingDate]) In ({years})"; } } else { query = $@"SELECT tblGearClass.GearClassName, tblGearVariations.Variation, tblAOI.AOIName, tblSampling.RefNo, tblSampling.SamplingDate, tblSampling.SamplingTime, tblSampling.FishingGround, tblSampling.TimeSet, tblSampling.DateSet, tblSampling.TimeHauled, tblSampling.DateHauled, tblSampling.NoHauls, tblSampling.NoFishers, tblSampling.Engine, tblSampling.hp, tblSampling.WtCatch, tblSampling.WtSample, tblLandingSites.LSName, temp_VesselType.VesselType FROM tblGearClass INNER JOIN (tblGearVariations INNER JOIN (((tblAOI INNER JOIN tblLandingSites ON tblAOI.AOIGuid = tblLandingSites.AOIGuid) INNER JOIN tblSampling ON tblLandingSites.LSGUID = tblSampling.LSGUID) INNER JOIN temp_VesselType ON tblSampling.VesType = temp_VesselType.VesselTypeNo) ON tblGearVariations.GearVarGUID = tblSampling.GearVarGUID) ON tblGearClass.GearClass = tblGearVariations.GearClass WHERE tblSampling.AOI= {{{aoiGuid}}} AND tblSampling.GearVarGUID= {{{gearVarGuid}}} AND Year([SamplingDate]) In ({years})"; } var adapter = new OleDbDataAdapter(query, conection); adapter.Fill(dt); var fishingGround = ""; var iShp = 0; var pointAdded = false; var iFldFG = 0; var iFLdCount = 0; fadUTMZone utmZone = FishingGrid.UTMZone; if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { sf.GeoProjection = global.MappingForm.GeoProjection; if (aggregate) { iFldFG = sf.EditAddField("fishingGround", FieldType.STRING_FIELD, 1, 9); iFLdCount = sf.EditAddField("n", FieldType.INTEGER_FIELD, 1, 1); } else { } for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; fishingGround = dr["FishingGround"].ToString(); var proceed = false; if (RemoveInland && !FishingGrid.MinorGridIsInland(fishingGround)) { proceed = true; } else if (!RemoveInland) { proceed = true; } if (proceed) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { if (sf.GeoProjection.IsGeographic) { var result = FishingGrid.Grid25ToLatLong(fishingGround, utmZone); pointAdded = shp.AddPoint(result.longitude, result.latitude) >= 0; } else { } if (pointAdded) { iShp = sf.EditAddShape(shp); if (iShp >= 0) { if (aggregate) { sf.EditCellValue(iFldFG, iShp, fishingGround); sf.EditCellValue(iFLdCount, iShp, (int)dr["n"]); } else { } } } } } } } } catch (Exception ex) { Logger.Log(ex.Message, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name); } } if (sf.NumShapes >= 0) { return(sf); } else { return(null); } }
// <summary> // This code calculates an area of polygons, writes it to the attribute table, and displays as labels. // </summary> public void CalculateArea(AxMap axMap1, string dataPath) { axMap1.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR; string filename = dataPath + "buildings.shp"; if (!File.Exists(filename)) { MessageBox.Show("Couldn't file the file: " + filename); return; } var sf = new Shapefile(); if (!sf.Open(filename, null)) { return; } if (sf.ShapefileType != ShpfileType.SHP_POLYGON) { MessageBox.Show("Polygon shapefile is expected." + Environment.NewLine + "Received: " + sf.ShapefileType); } else { int layerHandle = axMap1.AddLayer(sf, true); sf = axMap1.get_Shapefile(layerHandle); // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding int fldIndex = sf.Table.FieldIndexByName["CalcArea"]; if (fldIndex != -1) { if (MessageBox.Show("The area field exists. Do you want to overwrite it?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { sf.Close(); return; } } if (!sf.StartEditingTable(null)) { MessageBox.Show("Failed to start editing mode: " + sf.ErrorMsg[sf.LastErrorCode]); sf.Close(); } else { // removing the field in case it is already present if (fldIndex != -1) { if (!sf.EditDeleteField(fldIndex, null)) { MessageBox.Show("Failed to delete field: " + sf.ErrorMsg[sf.LastErrorCode]); sf.Close(); return; } } //adding the new field in the end of the table fldIndex = sf.EditAddField("CalcArea", FieldType.DOUBLE_FIELD, 12, 12); if (fldIndex == -1) { MessageBox.Show("Failed to insert field: " + sf.ErrorMsg[sf.LastErrorCode]); sf.Close(); return; } for (int i = 0; i < sf.NumShapes; i++) { Shape shp = sf.Shape[i]; sf.EditCellValue(fldIndex, i, shp.Area); } sf.Labels.Generate("[CalcArea] + \" sqr.m\"", tkLabelPositioning.lpCentroid, true); sf.Labels.FrameVisible = true; } } }
public void GenerateMinorGrids() { List <double> northings = new List <double>(); List <double> eastings = new List <double>(); List <Shape> selectedMajorGrids = new List <Shape>(); foreach (var idx in _selectedMajorGridIndices) { var shp = MapWindowManager.Grid25MajorGrid.Shape[idx]; var ext = shp.Extents; selectedMajorGrids.Add(shp); northings.Add(ext.yMax); eastings.Add(ext.xMin); } double top = northings.Max(); double left = eastings.Min(); double currentRow = top; double topRow = 0; double bottomRow = 0; do { currentRow -= 2000; if (currentRow < _extentUTM.yMax && topRow == 0) { topRow = currentRow + 2000; } bottomRow = currentRow; } while (currentRow > _extentUTM.yMin); double currentCol = left; double leftCol = 0; double righCol = 0; do { currentCol += 2000; if (currentCol > _extentUTM.xMin && leftCol == 0) { leftCol = currentCol - 2000; } righCol = currentCol; } while (currentCol < _extentUTM.xMax); Shapefile grid2km = new Shapefile(); if (grid2km.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON)) { grid2km.GeoProjection = MapWindowManager.Grid25MajorGrid.GeoProjection; grid2km.EditAddField("MajorGrid", FieldType.INTEGER_FIELD, 1, 1); grid2km.EditAddField("Col", FieldType.STRING_FIELD, 1, 1); grid2km.EditAddField("Row", FieldType.INTEGER_FIELD, 1, 1); grid2km.EditAddField("Name", FieldType.STRING_FIELD, 1, 1); double row = topRow; do { double col = leftCol; do { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POLYGON)) { shp.AddPoint(col, row); shp.AddPoint(col + 2000, row); shp.AddPoint(col + 2000, row - 2000); shp.AddPoint(col, row - 2000); shp.AddPoint(col, row); } col += 2000; var shpIndex = grid2km.EditAddShape(shp); if (shpIndex >= 0) { var pt = shp.Centroid; foreach (var idx in _selectedMajorGridIndices) { if (new Utils().PointInPolygon(MapWindowManager.Grid25MajorGrid.Shape[idx], pt)) { var result = GetCellAddressOfPointInMajorGrid(pt, MapWindowManager.Grid25MajorGrid.Shape[idx]); var grid_no = MapWindowManager.Grid25MajorGrid.CellValue[MapWindowManager.Grid25MajorGrid.FieldIndexByName["Grid_no"], idx]; grid2km.EditCellValue(grid2km.FieldIndexByName["MajorGrid"], shpIndex, grid_no); grid2km.EditCellValue(grid2km.FieldIndexByName["Col"], shpIndex, result.col.ToString()); grid2km.EditCellValue(grid2km.FieldIndexByName["Row"], shpIndex, result.row); grid2km.EditCellValue(grid2km.FieldIndexByName["Name"], shpIndex, $"{grid_no}-{result.col}{result.row}"); break; } } } } while (col + 2000 <= righCol); row -= 2000; } while (row - 2000 >= bottomRow); if (grid2km.NumShapes > 0) { Grid2Km = grid2km; } else { Grid2Km = null; } } }
// <summary> // Calculates area of polygons and sets 3 range of categories with different symbology // </summary> public void AddCategoryRange(AxMap axMap, string dataPath) { axMap.Projection = tkMapProjection.PROJECTION_GOOGLE_MERCATOR; string filename = dataPath + "landuse.shp"; if (File.Exists(filename) == false) { MessageBox.Show(@"Failed to open file: " + filename); return; } Shapefile sf = new Shapefile(); if (!sf.Open(filename)) { return; } if (!sf.StartEditingTable()) { MessageBox.Show(@"Failed to open editing mode."); return; } int fieldIndex = sf.Table.FieldIndexByName["Area"]; if (fieldIndex == -1) { fieldIndex = sf.EditAddField("Area", FieldType.DOUBLE_FIELD, 15, 18); } for (int i = 0; i < sf.NumShapes; i++) { double area = sf.Shape[i].Area * 100000.0; sf.EditCellValue(fieldIndex, i, area); } // adding to map int handle = axMap.AddLayer(sf, true); sf = axMap.get_Shapefile(handle); // in case a copy of shapefile was created by GlobalSettings.ReprojectLayersOnAdding double mean = sf.Table.MeanValue[fieldIndex]; double stDev = sf.Table.StandardDeviation[fieldIndex]; double min = (double)sf.Table.MinValue[fieldIndex]; double max = (double)sf.Table.MaxValue[fieldIndex]; var scheme = new ColorScheme(); // 1. the first range [min; mean - stDev] Utils utils = new Utils(); sf.DefaultDrawingOptions.FillType = tkFillType.ftHatch; sf.DefaultDrawingOptions.FillHatchStyle = tkGDIPlusHatchStyle.hsDiagonalBrick; sf.Categories.AddRange(fieldIndex, tkClassificationType.ctNaturalBreaks, 5, min, mean); scheme.SetColors2(tkMapColor.Red, tkMapColor.Yellow); // apply colors 0 and 4 are indices of categories, since 5 categories were added - from 0 to 4 sf.Categories.ApplyColorScheme3(tkColorSchemeType.ctSchemeRandom, scheme, tkShapeElements.shElementFill, 0, 4); // 2. the second range [mean - stDev; mean + stDev] // the default drawing options will be copied to the new categories sf.DefaultDrawingOptions.FillType = tkFillType.ftHatch; sf.DefaultDrawingOptions.FillHatchStyle = tkGDIPlusHatchStyle.hsCross; sf.Categories.AddRange(fieldIndex, tkClassificationType.ctEqualIntervals, 5, mean, mean + stDev); scheme.SetColors2(tkMapColor.Green, tkMapColor.Blue); sf.Categories.ApplyColorScheme3(tkColorSchemeType.ctSchemeGraduated, scheme, tkShapeElements.shElementFill, 5, 9); // 3. the third range [mean + stDev; max] // the default drawing options will be copied to the new categories sf.DefaultDrawingOptions.FillType = tkFillType.ftGradient; sf.DefaultDrawingOptions.FillColor2 = utils.ColorByName(tkMapColor.Gray); sf.Categories.AddRange(fieldIndex, tkClassificationType.ctEqualIntervals, 5, mean + stDev, max); scheme.SetColors2(tkMapColor.Pink, tkMapColor.Violet); sf.Categories.ApplyColorScheme3(tkColorSchemeType.ctSchemeGraduated, scheme, tkShapeElements.shElementFill, 10, 14); // apply expresions should be called exlicitly sf.Categories.ApplyExpressions(); axMap.Redraw(); // saving options to see categories desription in XML axMap.SaveLayerOptions(handle, "categories_sample", true, ""); }
public void SetText(string text) { switch (MapTextType) { case fadMapTextType.mapTextTypeTitle: TitleText = text; TitleVisible = TitleText.Length > 0; _categoryTitle.FontSize = TextSize; _categoryTitle.FontBold = TextBold; _categoryTitle.Alignment = TextAlignment; if (_textShapefile.NumShapes == 0) { var shape = new Shape(); var x = 0D; var y = 0D; if (shape.Create(ShpfileType.SHP_POINT)) { switch (_categoryTitle.Alignment) { case tkLabelAlignment.laCenterLeft: x = _graticule.GraticuleExtents.xMin; break; case tkLabelAlignment.laCenter: x = ((_graticule.GraticuleExtents.xMax - _graticule.GraticuleExtents.xMin) / 2) + _graticule.GraticuleExtents.xMin; break; case tkLabelAlignment.laCenterRight: x = _graticule.GraticuleExtents.xMax; break; } y = _graticule.GraticuleExtents.yMax; shape.AddPoint(x, y); _iShpTitle = _textShapefile.EditAddShape(shape); _textShapefile.EditCellValue(_ifldText, _iShpTitle, TitleText); } } else { _textShapefile.EditCellValue(_ifldText, _iShpTitle, TitleText); } break; case fadMapTextType.mapTextTypeNote: NoteText = text; NoteVisible = NoteText.Length > 0; _categoryNote.FontSize = TextSize; _categoryNote.Alignment = TextAlignment; _categoryNote.FontBold = TextBold; if (_textShapefile.NumShapes == 1) { var shape = new Shape(); if (shape.Create(ShpfileType.SHP_POINT)) { _iShpTitle = _textShapefile.EditAddShape(shape); _textShapefile.EditCellValue(_ifldText, _ishpNote, NoteText); } } else { _textShapefile.EditCellValue(_ifldText, _ishpNote, NoteText); } break; } ShowText(); }
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 ShapefileDataTest() { var tempFolder = Path.GetTempPath(); var tempFilename = Path.Combine(tempFolder, "ShapefileDataTest.shp"); var esriShapefilePath = @"C:\dev\MapWinGIS\unittests\MapWinGISTests\Testdata\Issues\MWGIS-48-68\EsriShapefile.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 of each data type: var fieldIndex = sf.EditAddField("intField", FieldType.INTEGER_FIELD, 0, 10); Assert.AreEqual(1, fieldIndex, "Could not add Integer field"); var width = sf.Field[fieldIndex].Width; Assert.AreEqual(9, width, "Integer field did not shrink to 9 digits"); fieldIndex = sf.EditAddField("dateField", FieldType.DATE_FIELD, 0, 6); Assert.AreEqual(2, fieldIndex, "Could not add Date field"); width = sf.Field[fieldIndex].Width; Assert.AreEqual(8, width, "Date field did not expand to 8 digits"); fieldIndex = sf.EditAddField("boolField", FieldType.BOOLEAN_FIELD, 0, 3); Assert.AreEqual(3, fieldIndex, "Could not add Boolean field"); width = sf.Field[fieldIndex].Width; Assert.AreEqual(1, width, "Boolean field did not shrink to 1 character"); // Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect"); result = sf.Save(); Assert.IsTrue(result, "Could not save shapefile"); Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect"); // Create shape: var shp = new Shape(); result = shp.Create(ShpfileType.SHP_POINT); Assert.IsTrue(result, "Could not create point shape"); var idx = sf.EditAddShape(shp); // Add data: result = sf.EditCellValue(sf.FieldIndexByName["intField"], idx, 99); Assert.IsTrue(result, "Could not edit intField"); DateTime dt = System.DateTime.Now; result = sf.EditCellValue(sf.FieldIndexByName["dateField"], idx, dt); Assert.IsTrue(result, "Could not edit dateField"); result = sf.EditCellValue(sf.FieldIndexByName["boolField"], idx, true); Assert.IsTrue(result, "Could not edit boolField"); result = sf.StopEditingShapes(); Assert.IsTrue(result, "Could not stop editing shapefile"); // Read back data: for (idx = 0; idx < sf.NumShapes; idx++) { int iField = (int)sf.CellValue[sf.FieldIndexByName["intField"], idx]; Assert.AreEqual(iField, 99, "intField value of 99 was not returned"); DateTime dField = (DateTime)sf.CellValue[sf.FieldIndexByName["dateField"], idx]; Assert.IsTrue(DateTime.Now.DayOfYear.Equals(((DateTime)dField).DayOfYear), "dateField value of Now was not returned"); bool bField = (bool)sf.CellValue[sf.FieldIndexByName["boolField"], idx]; Assert.AreEqual(bField, true, "boolField value of True was not returned"); } } finally { // Close the shapefile: result = sf.Close(); Assert.IsTrue(result, "Could not close shapefile"); } // although the default setting, indicate intent to interpret Y/N OGR String fields as Boolean GlobalSettings gs = new GlobalSettings(); gs.OgrInterpretYNStringAsBoolean = true; // setting to false results in exception reading boolField below // open as OGRLayer OgrDatasource _datasource = new OgrDatasource(); _datasource.GlobalCallback = this; if (_datasource.Open(tempFilename)) // "ESRI Shapefile:" + { // read layer through OGR library IOgrLayer ogrLayer = _datasource.GetLayer(0); sf = ogrLayer.GetBuffer(); for (int idx = 0; idx < sf.NumShapes; idx++) { int iField = (int)sf.CellValue[sf.FieldIndexByName["intField"], idx]; Assert.AreEqual(iField, 99, "intField value of 99 was not returned"); DateTime dField = (DateTime)sf.CellValue[sf.FieldIndexByName["dateField"], idx]; Assert.IsTrue(DateTime.Now.DayOfYear.Equals(((DateTime)dField).DayOfYear), "dateField value of Now was not returned"); bool bField = (bool)sf.CellValue[sf.FieldIndexByName["boolField"], idx]; Assert.AreEqual(bField, true, "boolField value of True was not returned"); } sf.Close(); } // open and read a Shapefile created by ESRI MapObjects, including a Boolean and Date field // table has a Boolean 'Inspected' field, and a Date 'InspDate' field Assert.IsTrue(sf.Open(esriShapefilePath, this)); for (int fld = 0; fld < sf.NumFields; fld++) { Console.WriteLine(string.Format("Field({0}): Name = '{1}', Fieldtype = {2}", fld, sf.Field[fld].Name, sf.Field[fld].Type)); } for (int idx = 0; idx < sf.NumShapes; idx++) { // read 'Inspected' value as object object inspected = sf.CellValue[sf.FieldIndexByName["Inspected"], idx]; // verify that it's a bool Assert.IsTrue(inspected is bool); // watch for Inspected rows (there aren't many) if ((bool)inspected == true) { // read 'InspDate' value as object object dt = sf.CellValue[sf.FieldIndexByName["InspDate"], idx]; // verify that it's a Date Assert.IsTrue(dt is DateTime); Console.WriteLine(string.Format("idx = {0}, Inspected = true, Inspection Date = {1}", idx, (DateTime)dt)); } } sf.Close(); }
// <summary> // Performs a segmentation of shapes by regular grid // </summary> public void Segmentation(AxMap axMap1, string dataPath) { axMap1.Projection = tkMapProjection.PROJECTION_NONE; axMap1.GrabProjectionFromData = true; string[] filenames = new string[2]; filenames[0] = dataPath + "natural.shp"; filenames[1] = dataPath + "landuse.shp"; if (!File.Exists(filenames[0]) || !File.Exists(filenames[1])) { MessageBox.Show("Couldn't file the files (natural.shp, landuse.shp): " + dataPath); return; } List <Shapefile> layers = new List <Shapefile>(); for (int i = 0; i < filenames.Length; i++) { Shapefile sf = new Shapefile(); sf.Open(filenames[i], null); layers.Add(sf); axMap1.AddLayer(layers[i], true); } int count = 4; Extents ext = axMap1.MaxExtents as Extents; double xStep = (ext.xMax - ext.xMin) / count; double yStep = (ext.yMax - ext.yMin) / count; Shapefile sfGrid = new Shapefile(); sfGrid.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON); sfGrid.GeoProjection.CopyFrom(layers[0].GeoProjection); ColorScheme scheme = new ColorScheme(); scheme.SetColors2(tkMapColor.Orange, tkMapColor.Yellow); for (int i = 0; i < layers.Count; i++) { string name = Path.GetFileNameWithoutExtension(layers[i].Filename); int fieldIndex = sfGrid.EditAddField(name, FieldType.DOUBLE_FIELD, 10, 12); uint color = scheme.GraduatedColor[(i + 1) / (double)layers.Count]; sfGrid.Charts.AddField2(fieldIndex, color); } for (int i = 0; i < count; i++) { for (int j = 0; j < count; j++) { Shape shp = new Shape(); shp.Create(ShpfileType.SHP_POLYGON); shp.AddPoint(ext.xMin + i * xStep, ext.yMin + j * yStep); shp.AddPoint(ext.xMin + i * xStep, ext.yMin + (j + 1) * yStep); shp.AddPoint(ext.xMin + (i + 1) * xStep, ext.yMin + (j + 1) * yStep); shp.AddPoint(ext.xMin + (i + 1) * xStep, ext.yMin + j * yStep); shp.AddPoint(ext.xMin + i * xStep, ext.yMin + j * yStep); int shapeIndex = sfGrid.EditAddShape(shp); for (int layer = 0; layer < layers.Count; layer++) { Shapefile sf = layers[layer]; double area = 0.0; for (int n = 0; n < sf.NumShapes; n++) { Shape shp2 = sf.Shape[n]; if (shp.Intersects(shp2)) { Shape shpResult = shp2.Clip(shp, tkClipOperation.clIntersection); if (shpResult != null) { area += shpResult.Area; } } } // divide by 10000.0 to convert square meters to hectars bool success = sfGrid.EditCellValue(layer + 1, shapeIndex, area / 10000.0); } } } // generating charts Charts charts = sfGrid.Charts; charts.Generate(tkLabelPositioning.lpCenter); charts.ChartType = tkChartType.chtPieChart; charts.PieRadius = 18; charts.Thickness = 10; charts.ValuesVisible = true; charts.Visible = true; ShapeDrawingOptions options = sfGrid.DefaultDrawingOptions; options.FillVisible = false; options.LineWidth = 2; options.LineStipple = tkDashStyle.dsDash; options.LineColor = 255; axMap1.AddLayer(sfGrid, true); axMap1.ZoomToMaxExtents(); }
public bool SetValue(int fieldIndex, object value) { return(_shapefile.EditCellValue(fieldIndex, _shapeIndex, value)); }
// <summary> // Calculates a minimal distance from each building to the river. // </summary> public void MinimalDistance(AxMap axMap1, string dataPath, ToolStripStatusLabel label) { axMap1.Projection = tkMapProjection.PROJECTION_NONE; axMap1.GrabProjectionFromData = true; string filename1 = dataPath + "waterways.shp"; string filename2 = dataPath + "buildings.shp"; if (!File.Exists(filename1) || !File.Exists(filename2)) { MessageBox.Show("The necessary files (waterways.shp, building.shp) are missing: " + dataPath); } else { Shapefile sfRivers = new Shapefile(); sfRivers.Open(filename1, null); Utils utils = new Utils(); sfRivers.DefaultDrawingOptions.LineColor = utils.ColorByName(tkMapColor.Blue); sfRivers.DefaultDrawingOptions.LineWidth = 5.0f; Shapefile sfBuildings = new Shapefile(); sfBuildings.Open(filename2, null); // adds a field in the table Field field = new Field(); field.Name = "RiverDist"; field.Type = FieldType.DOUBLE_FIELD; field.Precision = 10; int fieldIndex = sfBuildings.NumFields; sfBuildings.StartEditingShapes(true, null); sfBuildings.EditInsertField(field, ref fieldIndex, null); ShapefileCategory ct = sfBuildings.Categories.Add("Named buildings"); ct.Expression = "[Name] <> \"\""; sfBuildings.Categories.ApplyExpressions(); sfRivers.StartEditingShapes(false, null); for (int i = 0; i < sfBuildings.NumShapes; i++) { if (sfBuildings.ShapeCategory[i] == 0) { label.Text = "Processing building: " + (i + 1) + " / " + sfBuildings.NumShapes; Application.DoEvents(); Shape shp = sfBuildings.Shape[i]; double minDist = Double.MaxValue; for (int j = 0; j < sfRivers.NumShapes; j++) { Shape shp2 = sfRivers.Shape[j]; double distance = shp.Distance(shp2); if (distance < minDist) { minDist = distance; } } if (minDist != Double.MaxValue) { sfBuildings.EditCellValue(fieldIndex, i, minDist); } } else { sfBuildings.EditCellValue(fieldIndex, i, 0.0); } } sfRivers.StopEditingShapes(false, true, null); sfBuildings.Categories.Generate(fieldIndex, tkClassificationType.ctNaturalBreaks, 8); ColorScheme scheme = new ColorScheme(); scheme.SetColors2(tkMapColor.Blue, tkMapColor.Yellow); sfBuildings.Categories.ApplyColorScheme(tkColorSchemeType.ctSchemeGraduated, scheme); sfBuildings.Labels.Generate("[Name] + \"\n\" + [RiverDist] + \" m\"", tkLabelPositioning.lpCentroid, true); sfBuildings.Labels.TextRenderingHint = tkTextRenderingHint.SystemDefault; sfBuildings.VisibilityExpression = "[Name] <> \"\""; axMap1.AddLayer(sfRivers, true); axMap1.AddLayer(sfBuildings, true); label.Text = ""; } }
private void OnListMouseDown(object sender, MouseEventArgs e) { chkShowOnMap.Enabled = global.MapIsOpen; ListViewHitTestInfo hitTest = lvCoordinates.HitTest(e.X, e.Y); _treeLevel = hitTest.Item.Tag.ToString(); if (_coordinateEntryForm != null) { _coordinateEntryForm.TreeLevel = _treeLevel; _coordinateEntryForm.SetLocation(hitTest.Item.Text, int.Parse(hitTest.Item.Name)); } if (chkShowOnMap.Checked && global.MapIsOpen && hitTest.Item.SubItems[1].Text.Length > 0 && hitTest.Item.SubItems[2].Text.Length > 0 ) { Shapefile sf = new Shapefile(); sf.GeoProjection = global.MappingForm.MapControl.GeoProjection; if (sf.CreateNew("", ShpfileType.SHP_POINT)) { var ifldLocation = sf.EditAddField("Location", FieldType.STRING_FIELD, 0, 50); Shape shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { float y = _dictCoordinate[int.Parse(hitTest.Item.Name)].Latitude; float x = _dictCoordinate[int.Parse(hitTest.Item.Name)].Longitude; var iPt = shp.AddPoint(x, y); if (iPt >= 0) { var iShp = sf.EditAddShape(shp); if (iShp >= 0) { sf.EditCellValue(ifldLocation, iShp, hitTest.Item.Text); sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; sf.DefaultDrawingOptions.FillColor = new Utils().ColorByName(tkMapColor.Red); sf.DefaultDrawingOptions.LineVisible = false; sf.DefaultDrawingOptions.PointSize = 8; sf.CollisionMode = tkCollisionMode.AllowCollisions; global.MappingForm.MapLayersHandler.AddLayer(sf, "Location", isVisible: true, uniqueLayer: true); } } } } } if (e.Button == MouseButtons.Right) { menuDropDown.Items.Clear(); var item = menuDropDown.Items.Add("Set coordinate"); item.Name = "itemSetCoordinate"; item.Enabled = global.MapIsOpen; item = menuDropDown.Items.Add("Map coordinates"); item.Name = "itemMapCoordinates"; item.Enabled = global.MapIsOpen; item = menuDropDown.Items.Add("Copy text"); item.Name = "itemCopyText"; menuDropDown.Show(Cursor.Position); } }