public static Shapefile NamedPointsFromGPX(GPXFile gpxFile, out List <int> shpIndexes) { shpIndexes = new List <int>(); Shapefile sf; if (gpxFile.NamedWaypointsInLocalTime.Count > 0) { if (GPXMappingManager.WaypointsShapefile == null || GPXMappingManager.WaypointsShapefile.NumFields == 0) { sf = new Shapefile(); if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { sf.GeoProjection = globalMapping.GeoProjection; sf.Key = "gpxfile_waypoint"; sf.EditAddField("Name", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("TimeStamp", FieldType.DATE_FIELD, 1, 1); sf.EditAddField("GPS", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Filename", FieldType.STRING_FIELD, 1, 1); GPXMappingManager.WaypointsShapefile = sf; } } else { sf = GPXMappingManager.WaypointsShapefile; } foreach (var wlt in gpxFile.NamedWaypointsInLocalTime) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { if (shp.AddPoint(wlt.Longitude, wlt.Latitude) >= 0) { var shpIndex = sf.EditAddShape(shp); if (shpIndex >= 0) { sf.EditCellValue(sf.FieldIndexByName["Name"], shpIndex, wlt.Name); sf.EditCellValue(sf.FieldIndexByName["TimeStamp"], shpIndex, wlt.Time); sf.EditCellValue(sf.FieldIndexByName["GPS"], shpIndex, gpxFile.GPS.DeviceName); sf.EditCellValue(sf.FieldIndexByName["Filename"], shpIndex, gpxFile.FileName); shpIndexes.Add(shpIndex); } } } } sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; sf.DefaultDrawingOptions.PointSize = 12; sf.DefaultDrawingOptions.FillColor = _mapWinGISUtils.ColorByName(tkMapColor.Red); return(sf); } else { return(null); } }
/// <summary> /// Sets up the polyline shapefile that makes the graticule /// </summary> private void SetupShapefile() { _sfGraticule = new Shapefile(); if (_sfGraticule.CreateNew("", ShpfileType.SHP_POLYLINE)) { _ifldPart = _sfGraticule.EditAddField("Part", FieldType.STRING_FIELD, 1, 25); _ifldLabel = _sfGraticule.EditAddField("Label", FieldType.STRING_FIELD, 1, 25); _ifldSide = _sfGraticule.EditAddField("Side", FieldType.STRING_FIELD, 1, 1); _sfGraticule.GeoProjection = _geoProjection; GraticuleLoaded?.Invoke(this, EventArgs.Empty); } }
public static Shapefile PointsFromWaypointList(List <WaypointLocalTime> wpts, out List <int> handles) { handles = new List <int>(); Shapefile sf; if (wpts.Count > 0) { if (TripMappingManager.WaypointsShapefile == null || TripMappingManager.WaypointsShapefile.NumFields == 0) { sf = new Shapefile(); if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { sf.EditAddField("Name", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("TimeStamp", FieldType.DATE_FIELD, 1, 1); sf.Key = "gpx_waypoints"; sf.GeoProjection = globalMapping.GeoProjection; TripMappingManager.WaypointsShapefile = sf; } } else { sf = TripMappingManager.WaypointsShapefile; } foreach (var pt in wpts) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { if (shp.AddPoint(pt.Longitude, pt.Latitude) >= 0) { var shpIndex = sf.EditAddShape(shp); if (shpIndex >= 0) { sf.EditCellValue(sf.FieldIndexByName["Name"], shpIndex, pt.Name); sf.EditCellValue(sf.FieldIndexByName["TimeStamp"], shpIndex, pt.Time); handles.Add(shpIndex); } } } } sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle; sf.DefaultDrawingOptions.PointSize = 12; sf.DefaultDrawingOptions.FillColor = _mapWinGISUtils.ColorByName(tkMapColor.Red); return(sf); } else { return(null); } }
public static Shapefile TrackFromGPX(GPXFile gpxFile, out List <int> handles) { handles = new List <int>(); var shpIndex = -1; Shapefile sf; if (gpxFile.TrackWaypoinsInLocalTime.Count > 0) { if (GPXMappingManager.TrackShapefile == null || GPXMappingManager.TrackShapefile.NumFields == 0) { sf = new Shapefile(); if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYLINE)) { sf.EditAddField("GPS", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Filename", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Length", FieldType.DOUBLE_FIELD, 1, 1); sf.EditAddField("DateStart", FieldType.DATE_FIELD, 1, 1); sf.EditAddField("DateEnd", FieldType.DATE_FIELD, 1, 1); sf.Key = "gpxfile_track"; sf.GeoProjection = GPXManager.entities.mapping.globalMapping.GeoProjection; GPXMappingManager.TrackShapefile = sf; } } else { sf = GPXMappingManager.TrackShapefile; } var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POLYLINE)) { foreach (var wlt in gpxFile.TrackWaypoinsInLocalTime) { shp.AddPoint(wlt.Longitude, wlt.Latitude); } } shpIndex = sf.EditAddShape(shp); handles.Add(shpIndex); sf.EditCellValue(sf.FieldIndexByName["GPS"], shpIndex, gpxFile.GPS.DeviceName); sf.EditCellValue(sf.FieldIndexByName["FileName"], shpIndex, gpxFile.FileName); sf.EditCellValue(sf.FieldIndexByName["Length"], shpIndex, gpxFile.TrackLength); sf.EditCellValue(sf.FieldIndexByName["DateStart"], shpIndex, gpxFile.DateRangeStart); sf.EditCellValue(sf.FieldIndexByName["DateEnd"], shpIndex, gpxFile.DateRangeEnd); return(sf); } else { return(null); } }
public static Shapefile TrackFromTrip(List <Trip> trips, out List <int> handles) { handles = new List <int>(); Shapefile sf = null; var shpIndex = -1; int counter = 0; foreach (var trip in trips) { if (counter == 0) { if (TripMappingManager.TrackShapefile == null || TripMappingManager.TrackShapefile.NumFields == 0) { sf = new Shapefile(); if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYLINE)) { sf.EditAddField("GPS", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Fisher", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Vessel", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Gear", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Departed", FieldType.DATE_FIELD, 1, 1); sf.EditAddField("Arrived", FieldType.DATE_FIELD, 1, 1); sf.EditAddField("Filename", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Length", FieldType.DOUBLE_FIELD, 1, 1); sf.Key = "trip_track"; sf.GeoProjection = globalMapping.GeoProjection; TripMappingManager.TrackShapefile = sf; } } else { sf = TripMappingManager.TrackShapefile; } } var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POLYLINE)) { foreach (var wpt in trip.Track.Waypoints) { shp.AddPoint(wpt.Longitude, wpt.Latitude); } } shpIndex = sf.EditAddShape(shp); handles.Add(shpIndex); sf.EditCellValue(sf.FieldIndexByName["GPS"], shpIndex, trip.GPS.DeviceName); sf.EditCellValue(sf.FieldIndexByName["Fisher"], shpIndex, trip.OperatorName); sf.EditCellValue(sf.FieldIndexByName["Vessel"], shpIndex, trip.VesselName); sf.EditCellValue(sf.FieldIndexByName["Departed"], shpIndex, trip.DateTimeDeparture); sf.EditCellValue(sf.FieldIndexByName["Arrived"], shpIndex, trip.DateTimeArrival); sf.EditCellValue(sf.FieldIndexByName["Gear"], shpIndex, trip.Gear); sf.EditCellValue(sf.FieldIndexByName["FileName"], shpIndex, trip.GPXFileName); sf.EditCellValue(sf.FieldIndexByName["Length"], shpIndex, trip.Track.Statistics.Length); counter++; } return(sf); }
private static void OnExentCreated(MapInterActionHandler s, LayerEventArg e) { if (EnableMapInteraction) { if (_hAOI >= 0) { MapWindowManager.MapLayersHandler.RemoveLayer(_hAOI); } else { AOIName = "New AOI"; } _sfAOI = new Shapefile(); if (_sfAOI.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON)) { if (_sfAOI.EditAddShape(e.SelectionExtent.ToShape()) >= 0) { _hAOI = MapWindowManager.MapLayersHandler.AddLayer(_sfAOI, AOIName); if (_hAOI >= 0) { var fldName = _sfAOI.EditAddField("Name", FieldType.STRING_FIELD, 1, 1); _sfAOI.Key = "aoi"; FormatAOI(_sfAOI); } } } } }
public static Shapefile GPXTrackVertices(GPXFile gpxfile, out List <int> shpIndexes) { shpIndexes = new List <int>(); Shapefile sf; if (gpxfile.GPXFileType == GPXFileType.Track && gpxfile.TrackWaypoinsInLocalTime.Count > 0) { sf = new Shapefile(); if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { sf.EditAddField("Name", FieldType.INTEGER_FIELD, 1, 1); sf.EditAddField("Time", FieldType.DATE_FIELD, 1, 1); sf.Key = "gpx_track_vertices"; sf.GeoProjection = globalMapping.GeoProjection; GPXMappingManager.TrackVerticesShapefile = sf; } } else { sf = GPXMappingManager.TrackVerticesShapefile; } foreach (var wlt in gpxfile.TrackWaypoinsInLocalTime) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { if (shp.AddPoint(wlt.Longitude, wlt.Latitude) >= 0) { var shpIndex = sf.EditAddShape(shp); if (shpIndex >= 0) { sf.EditCellValue(sf.FieldIndexByName["Name"], shpIndex, shpIndex + 1); sf.EditCellValue(sf.FieldIndexByName["Time"], shpIndex, wlt.Time); shpIndexes.Add(shpIndex); } } } } sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeRegular; sf.DefaultDrawingOptions.PointSize = 10; sf.DefaultDrawingOptions.PointSidesCount = 4; sf.DefaultDrawingOptions.FillColor = _mapWinGISUtils.ColorByName(tkMapColor.Orange); sf.DefaultDrawingOptions.LineColor = _mapWinGISUtils.ColorByName(tkMapColor.Black); sf.DefaultDrawingOptions.LineWidth = 1.5f; return(sf); }
public static Shapefile TrackFromTrip1(Trip trip, out List <int> handles) { handles = new List <int>(); var shpIndex = -1; Shapefile sf; if (trip.Track.Waypoints.Count > 0) { if (TripMappingManager.TrackShapefile == null || TripMappingManager.TrackShapefile.NumFields == 0) { sf = new Shapefile(); if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYLINE)) { sf.EditAddField("GPS", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Filename", FieldType.STRING_FIELD, 1, 1); sf.EditAddField("Length", FieldType.DOUBLE_FIELD, 1, 1); sf.Key = "trip_track"; sf.GeoProjection = globalMapping.GeoProjection; TripMappingManager.TrackShapefile = sf; } } else { sf = TripMappingManager.TrackShapefile; } var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POLYLINE)) { foreach (var wpt in trip.Track.Waypoints) { shp.AddPoint(wpt.Longitude, wpt.Latitude); } } shpIndex = sf.EditAddShape(shp); handles.Add(shpIndex); sf.EditCellValue(sf.FieldIndexByName["GPS"], shpIndex, trip.GPS.DeviceName); sf.EditCellValue(sf.FieldIndexByName["FileName"], shpIndex, trip.GPXFileName); sf.EditCellValue(sf.FieldIndexByName["Length"], shpIndex, trip.Track.Statistics.Length); return(sf); } else { return(null); } }
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); }
/// <summary>Add a field to the shapefile</summary> /// <param name = "column">The column to add.</param> public void AddField(DataColumn column) { var name = column.ColumnName; var fieldType = GetMapWindowFieldType(column.DataType); var precision = GetPrecision(column); var width = GetWidth(column); var fieldIndexNew = _shapefile.EditAddField(name, fieldType, precision, width); }
public void SaveShapefileTest() { 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: var fieldIndex = sf.EditAddField("date", FieldType.STRING_FIELD, 0, 50); Assert.AreEqual(1, fieldIndex, "Could not add field"); fieldIndex = sf.EditAddField("remarks", FieldType.STRING_FIELD, 0, 100); Assert.AreEqual(2, fieldIndex, "Could not add field"); fieldIndex = sf.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.Save(); Assert.IsTrue(result, "Could not save shapefile"); 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 MapTextGraticuleHelper(GeoProjection projection, Graticule graticule) { _graticule = graticule; TitleSize = 13; NoteSize = 10; TextBold = false; TitleText = "Map title"; NoteText = "Map note"; TitleVisible = false; NoteVisible = false; TitleAlignment = tkLabelAlignment.laCenter; NoteAlignment = tkLabelAlignment.laCenterLeft; MapTextType = fadMapTextType.mapTextTypeNone; _textShapefile = new Shapefile(); if (_textShapefile.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { _textShapefile.GeoProjection = projection; _ifldTextType = _textShapefile.EditAddField("TextType", FieldType.STRING_FIELD, 1, 5); _ifldText = _textShapefile.EditAddField("Text", FieldType.STRING_FIELD, 1, 100); _categoryTitle = _textShapefile.Labels.AddCategory("Text"); _categoryNote = _textShapefile.Labels.AddCategory("Note"); } }
/// <summary> /// create minor grid shapefile /// </summary> /// <returns></returns> private static bool SetUpMInorGridShapefile() { MinorGridsShapefile = new Shapefile(); if (MinorGridsShapefile.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON)) { _iFldName = MinorGridsShapefile.EditAddField("name", FieldType.STRING_FIELD, 1, 8); _iFldInland = MinorGridsShapefile.EditAddField("inland", FieldType.BOOLEAN_FIELD, 1, 1); MinorGridsShapefile.GeoProjection = global.MappingForm.MapControl.GeoProjection; if (_inlandMinorGrids == null) { _inlandMinorGrids = new Shapefile(); if (_inlandMinorGrids.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON)) { _inlandMinorGrids.EditAddField("name", FieldType.STRING_FIELD, 1, 8); _inlandMinorGrids.EditAddField("inland", FieldType.BOOLEAN_FIELD, 1, 1); } } return(true); } return(false); }
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 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> /// 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; } }
/// <summary> /// Creates a new shapefile from a point shapefile where each point is located in the center of a grid25 cell. All fields in the source point shapefile are copied to the new shapefile /// </summary> /// <param name="pointShapefile"></param> /// <param name="utmZone"></param> /// <returns></returns> public static Shapefile ConvertToGrid25(Shapefile pointShapefile, fadUTMZone utmZone, fad3ActionType inlandAction = fad3ActionType.atIgnore, fad3ActionType outsideMapAction = fad3ActionType.atIgnore, bool includeCoordinates = false) { var sf = new Shapefile(); var listFields = new List <string>(); var zoneName = string.Empty; if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT)) { var gp = new GeoProjection(); switch (utmZone) { case fadUTMZone.utmZone50N: gp.SetWgs84Projection(tkWgs84Projection.Wgs84_UTM_zone_50N); zoneName = "50N"; break; case fadUTMZone.utmZone51N: gp.SetWgs84Projection(tkWgs84Projection.Wgs84_UTM_zone_51N); zoneName = "51N"; break; } sf.GeoProjection = gp; //recreate all fields from source to destination for (int f = 0; f < pointShapefile.NumFields; f++) { listFields.Add(pointShapefile.Field[f].Name); sf.EditAddField(listFields[f], pointShapefile.Field[f].Type, pointShapefile.Field[f].Precision, pointShapefile.Field[f].Width); } var ifldGrid = sf.EditAddField("grid25", FieldType.STRING_FIELD, 1, 8); var ifldInlandAction = -1; if (inlandAction == fad3ActionType.atTakeNote) { ifldInlandAction = sf.EditAddField("isInland", FieldType.BOOLEAN_FIELD, 1, 1); } var ifldOutsideAction = -1; if (outsideMapAction == fad3ActionType.atTakeNote) { ifldOutsideAction = sf.EditAddField("isOutsid", FieldType.BOOLEAN_FIELD, 1, 1); } //create fields for coordinate data var ifldCoordinatesX = -1; var ifldCoordinatesY = -1; if (includeCoordinates) { ifldCoordinatesX = sf.EditAddField("Grid25X", FieldType.INTEGER_FIELD, 0, 8); ifldCoordinatesY = sf.EditAddField("Grid25Y", FieldType.INTEGER_FIELD, 0, 8); } for (int n = 0; n < pointShapefile.NumShapes; n++) { var shp = new Shape(); if (shp.Create(ShpfileType.SHP_POINT)) { //get the x,y coordinates of the source point shape var x = pointShapefile.Shape[n].Point[0].x; var y = pointShapefile.Shape[n].Point[0].y; //call the function that returns the coordinates of the grid center where the point is located var result = FishingGrid.utmCoordinatesToGrid25(x, y, utmZone); var removeInland = false; var isInland = false; if (inlandAction != fad3ActionType.atIgnore) { isInland = FishingGrid.MinorGridIsInland(result.grid25Name, zoneName); removeInland = isInland && inlandAction == fad3ActionType.atRemove; } if (!removeInland) { //create a new point shape and add it to the destination shapefile shp.AddPoint(result.Easting, result.Northing); var iShp = sf.EditAddShape(shp); //update the destination shapefile fields foreach (var item in listFields) { var ifldDestination = sf.FieldIndexByName[item]; var ifldSource = pointShapefile.FieldIndexByName[item]; sf.EditCellValue(ifldDestination, iShp, pointShapefile.CellValue[ifldSource, n]); } sf.EditCellValue(ifldGrid, iShp, result.grid25Name); //update coordinate fields if required if (includeCoordinates) { sf.EditCellValue(ifldCoordinatesX, iShp, result.Easting); sf.EditCellValue(ifldCoordinatesY, iShp, result.Northing); } //update isInland field if required if (ifldInlandAction >= 0) { sf.EditCellValue(ifldInlandAction, iShp, isInland); } } } } return(sf); } return(null); }
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); } }
// <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, ""); }
// <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 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 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 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; } } }
/// <summary> /// add the MBR of a target area as a new map layer /// </summary> /// <param name="moveMapToMBRCenter"></param> public void AddMBRLayer(TargetArea targetArea, bool moveMapToMBRCenter = false) { var sf = new Shapefile(); if (sf.CreateNew("", ShpfileType.SHP_POLYGON)) { GeoProjection gp = new GeoProjection(); gp.SetWgs84(); sf.GeoProjection = gp; int ifldTargetArea = sf.EditAddField("Target area", FieldType.STRING_FIELD, 1, 30); int ifldyMax = sf.EditAddField("yMax", FieldType.DOUBLE_FIELD, 10, 12); int ifldxMin = sf.EditAddField("xMin", FieldType.DOUBLE_FIELD, 10, 12); int ifldyMin = sf.EditAddField("yMin", FieldType.DOUBLE_FIELD, 10, 12); int ifldxMax = sf.EditAddField("xMax", FieldType.DOUBLE_FIELD, 10, 12); int ifldWidth = sf.EditAddField("Width", FieldType.DOUBLE_FIELD, 10, 12); int ifldHeight = sf.EditAddField("Height", FieldType.DOUBLE_FIELD, 10, 12); int ifldArea = sf.EditAddField("Area", FieldType.DOUBLE_FIELD, 15, 17); var ext = new Extents(); //ext.SetBounds(FishingGrid.LowerRighttExtent.X, // FishingGrid.LowerRighttExtent.Y, // 0, // FishingGrid.UpperLeftExtent.X, // FishingGrid.UpperLeftExtent.Y, // 0); ext.SetBounds(targetArea.UpperLeftPointLL.X, targetArea.LowerRightPointLL.Y, 0, targetArea.LowerRightPointLL.X, targetArea.UpperLeftPointLL.Y, 0); var shp = ext.ToShape(); int iShp = sf.EditAddShape(shp); if (iShp >= 0) { sf.EditCellValue(ifldTargetArea, iShp, targetArea.TargetAreaName); if (sf.Labels.Generate("[Target area]", tkLabelPositioning.lpCenter, true) > 0) { sf.Labels.FontSize = 13; sf.Labels.FrameVisible = false; sf.Labels.Visible = true; sf.Labels.FontBold = true; } sf.EditCellValue(ifldyMax, iShp, ext.yMax); sf.EditCellValue(ifldxMin, iShp, ext.xMin); sf.EditCellValue(ifldyMin, iShp, ext.yMin); sf.EditCellValue(ifldxMax, iShp, ext.xMax); sf.EditCellValue(ifldWidth, iShp, targetArea.Width); sf.EditCellValue(ifldHeight, iShp, targetArea.Height); sf.EditCellValue(ifldArea, iShp, targetArea.Area); sf.DefaultDrawingOptions.FillVisible = false; sf.DefaultDrawingOptions.LineColor = new Utils().ColorByName(tkMapColor.Blue); sf.DefaultDrawingOptions.LineWidth = 2; AddLayer(sf, "MBR", true, true); if (moveMapToMBRCenter) { ext = MapControl.Extents; ext.MoveTo(sf.Extents.Center.x, sf.Extents.Center.y); MapControl.Extents = ext; } } } }
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 static void SetupIDColumn(Shapefile sf, bool saveChanges = false) { bool proceed = true; if (!sf.EditingTable) { Callback = new Callback(); proceed = sf.StartEditingTable(Callback); } int idx; if (proceed) { if (sf.NumFields == 1) { if (sf.Field[0].Type != FieldType.INTEGER_FIELD) { idx = sf.EditAddField("MWShapeID", FieldType.INTEGER_FIELD, 1, 1); if (FillFieldWithUniqueInt(sf, idx)) { UnqiueIDColumnName = sf.Field[idx].Name; UnqiueIDColumnIndex = idx; } } else { if (!FieldContainsUniqueIntegerValues(sf, 0)) { idx = sf.EditAddField("MWShapeID", FieldType.INTEGER_FIELD, 1, 1); if (FillFieldWithUniqueInt(sf, idx)) { UnqiueIDColumnName = sf.Field[idx].Name; UnqiueIDColumnIndex = idx; } } else { UnqiueIDColumnName = sf.Field[0].Name; UnqiueIDColumnIndex = 0; } } } else if (sf.NumFields == 0) { idx = sf.EditAddField("MWShapeID", FieldType.INTEGER_FIELD, 1, 1); if (FillFieldWithUniqueInt(sf, idx)) { UnqiueIDColumnName = sf.Field[idx].Name; UnqiueIDColumnIndex = idx; } } else { bool sfHasUniqueIDs = false; for (int x = 0; x < sf.NumFields; x++) { if (sf.Field[x].Type == FieldType.INTEGER_FIELD) { if (FieldContainsUniqueIntegerValues(sf, x)) { sfHasUniqueIDs = true; UnqiueIDColumnName = sf.Field[x].Name; UnqiueIDColumnIndex = x; sf.StopEditingTable(); break; } } } if (!sfHasUniqueIDs) { idx = sf.EditAddField("MWShapeID", FieldType.INTEGER_FIELD, 1, 1); if (FillFieldWithUniqueInt(sf, idx)) { UnqiueIDColumnName = sf.Field[idx].Name; UnqiueIDColumnIndex = idx; } } } if (sf.EditingTable) { Callback = new Callback(); sf.StopEditingTable(saveChanges, Callback); } } }
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; } } }
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(); }