public void CreateAnglePolylines()
        {
            var tempFolder  = Path.GetTempPath();
            var sfLineInput = Helper.OpenShapefile(Path.Combine(@"sf", "Tracks.shp"));
            var utils       = new Utils();

            // Create new shapefile with polylines:
            var sfNew = Helper.CreateSf(ShpfileType.SHP_POLYLINE);

            sfNew.GeoProjection = sfLineInput.GeoProjection.Clone();

            var numShapesInput = sfLineInput.NumShapes;

            for (var i = 0; i < numShapesInput; i++)
            {
                var       shape     = sfLineInput.Shape[i];
                var       numPoints = shape.numPoints;
                const int distance  = 20;

                // Skip the first point:
                for (var j = 0; j < numPoints; j++)
                {
                    var firstPoint  = shape.Point[j];
                    var secondPoint = shape.Point[j + 1];
                    if (j == numPoints - 1)
                    {
                        secondPoint = shape.Point[j - 1];
                    }

                    var angle = GetAngle(utils, firstPoint, secondPoint);

                    var newLineShp = new Shape();
                    newLineShp.Create(ShpfileType.SHP_POLYLINE);
                    newLineShp.AddPoint(firstPoint.x, firstPoint.y);
                    newLineShp.AddPoint(Math.Cos(angle) * distance + firstPoint.x,
                                        Math.Sin(angle) * distance + firstPoint.y);
                    sfNew.EditAddShape(newLineShp);
                    // Add line to other side:
                    newLineShp = new Shape();
                    newLineShp.Create(ShpfileType.SHP_POLYLINE);
                    newLineShp.AddPoint(firstPoint.x, firstPoint.y);
                    newLineShp.AddPoint(Math.Cos(angle) * -1 * distance + firstPoint.x,
                                        Math.Sin(angle) * -1 * distance + firstPoint.y);
                    sfNew.EditAddShape(newLineShp);
                }
            }

            // Save new shapefile:
            Helper.SaveAsShapefile(sfNew, Path.Combine(tempFolder, "AngledLines.shp"));
            sfNew.Close();

            var retVal = sfLineInput.Close();

            Assert.IsTrue(retVal, "Cannot close line shapefile: " + sfLineInput.ErrorMsg[sfLineInput.LastErrorCode]);
        }
示例#2
0
        private void button6_Click(object sender, EventArgs e)
        {
            // Create a polygon shapefile:
            var sfPolygon = new Shapefile();

            sfPolygon.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);
            var shp = new Shape();

            shp.ImportFromWKT(
                "POLYGON((330695.973322992 5914896.16305817, 330711.986129861 5914867.19586245, 330713.350435287 5914867.56644015, 330716.510827627 5914862.28973662, 330715.632568651 5914860.60107999, 330652.234582712 5914803.80510632, 330553.749382483 5914715.80328169, 330551.979355848 5914714.83347535, 330549.911988583 5914715.86502807, 330545.027807355 5914724.05916443, 330544.592985976 5914725.93531509, 330544.30963704 5914726.72754692, 330543.612620707 5914726.14904553, 330543.271515787 5914727.06633931, 330542.234090059 5914729.85597723, 330542.959654761 5914730.50411962, 330530.319252794 5914765.86064153, 330505.294840402 5914836.7930124, 330471.411812074 5914931.61558331, 330486.074748666 5914941.33795239, 330585.983154737 5915010.32749106, 330618.427962455 5915031.20447119, 330653.234601917 5914970.37328093, 330695.973322992 5914896.16305817))");
            sfPolygon.EditAddShape(shp);

            // Create some random points:
            var       random    = new Random();
            const int numPoints = 50;
            var       extents   = sfPolygon.Extents;
            var       width     = extents.xMax - extents.xMin;
            var       height    = extents.yMax - extents.yMin;

            var sfPoint = new Shapefile();

            sfPoint.CreateNewWithShapeID("", ShpfileType.SHP_POINT);
            for (var i = 0; i < numPoints; i++)
            {
                var x        = extents.xMin + width * random.NextDouble();
                var y        = extents.yMin + height * random.NextDouble();
                var shpPoint = new Shape();
                shpPoint.Create(ShpfileType.SHP_POINT);
                shpPoint.AddPoint(x, y);
                sfPoint.EditAddShape(shpPoint);
            }

            axMap1.AddLayer(sfPolygon, true);
            axMap1.AddLayer(sfPoint, true);
        }
        /// <summary>
        /// Simplify polyline using Douglas-Peucker reduction
        /// </summary>
        /// <param name="inShape"></param>
        /// <param name="ToleranceMeters"></param>
        /// <returns></returns>
        public static Shape DouglasPeuckerReduction(Shape inShape, double ToleranceMeters)
        {
            ShapeSimplified = null;

            if (inShape.numPoints < 3)
            {
                ShapeSimplified = inShape;
                return(inShape);
            }

            var points = new List <Point>();

            for (int x = 0; x < inShape.numPoints; x++)
            {
                points.Add(new Point {
                    X = inShape.Point[x].x, Y = inShape.Point[x].y
                });
            }

            var tolerance = ToleranceMeters / (1852 * 60);
            var outPoints = DouglasPeuckerReduction(points, tolerance);

            var outShape = new Shape();

            if (outShape.Create(ShpfileType.SHP_POLYLINE))
            {
                foreach (var pt in outPoints)
                {
                    outShape.AddPoint(pt.X, pt.Y);
                }
            }

            ShapeSimplified = outShape;
            return(outShape);
        }
示例#4
0
        public static Shapefile TrackFromWaypoints()
        {
            if (WaypointsinLocalTine.Count > 0)
            {
                Shapefile shpFile = new Shapefile();
                if (shpFile.CreateNewWithShapeID("", ShpfileType.SHP_POLYLINE))
                {
                    shpFile.GeoProjection = globalMapping.GeoProjection;
                    var shp = new Shape();
                    if (shp.Create(ShpfileType.SHP_POLYLINE))
                    {
                        foreach (var wlt in WaypointsinLocalTine)
                        {
                            var shpIndex = shp.AddPoint(wlt.Longitude, wlt.Latitude);
                        }
                    }
                    shpFile.EditAddShape(shp);
                }

                return(shpFile);
            }
            else
            {
                throw new ArgumentException("Waypoint source cannot be null or cannot have zero elements");
            }
        }
示例#5
0
        public static Shapefile PointsFromWayPointList(List <TripWaypoint> wpts, out List <int> handles, string gpsName, string fileName)
        {
            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("Type", FieldType.STRING_FIELD, 1, 1);
                        sf.EditAddField("Set number", FieldType.INTEGER_FIELD, 3, 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);
                        sf.Key           = "trip_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.Waypoint.Longitude, pt.Waypoint.Latitude) >= 0)
                        {
                            var shpIndex = sf.EditAddShape(shp);
                            if (shpIndex >= 0)
                            {
                                sf.EditCellValue(sf.FieldIndexByName["Name"], shpIndex, pt.WaypointName);
                                sf.EditCellValue(sf.FieldIndexByName["TimeStamp"], shpIndex, pt.TimeStampAdjusted);
                                sf.EditCellValue(sf.FieldIndexByName["Type"], shpIndex, pt.WaypointType);
                                sf.EditCellValue(sf.FieldIndexByName["Set number"], shpIndex, pt.SetNumber);
                                sf.EditCellValue(sf.FieldIndexByName["GPS"], shpIndex, gpsName);
                                sf.EditCellValue(sf.FieldIndexByName["Filename"], shpIndex, fileName);
                                handles.Add(shpIndex);
                            }
                        }
                    }
                }
                sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle;
                sf.DefaultDrawingOptions.PointSize  = 12;
                sf.DefaultDrawingOptions.FillColor  = _mapWinGISUtils.ColorByName(tkMapColor.Red);
                return(sf);
            }
            else
            {
                return(null);
            }
        }
示例#6
0
        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);
        }
示例#7
0
        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);
        }
示例#8
0
        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>
        /// 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);
        }
        public static void AddCoordinatesToLineSf(Shapefile sfLines, Helper.Coordinate coordinate1,
                                                  Helper.Coordinate coordinate2)
        {
            var shp = new Shape();

            if (!shp.Create(ShpfileType.SHP_POLYLINE))
            {
                throw new Exception("Error in creating shape. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (shp.AddPoint(coordinate1.X, coordinate1.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (shp.AddPoint(coordinate2.X, coordinate2.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }

            // Check if this line intersects other lines, if so shorten to intersection point:
            var numShapes = sfLines.NumShapes;

            for (var i = 0; i < numShapes; i++)
            {
                var shpTesting = sfLines.Shape[i];
                if (!shpTesting.Crosses(shp))
                {
                    continue;
                }

                var newCoordinate = GetIntersection(Helper.PointToCoordinate(shp.Point[0]),
                                                    Helper.PointToCoordinate(shp.Point[1]), Helper.PointToCoordinate(shpTesting.Point[0]),
                                                    Helper.PointToCoordinate(shpTesting.Point[1]));
                // Replace point:
                shp.Point[1] = Helper.CoordinateToPoint(newCoordinate);
            }

            if (sfLines.EditAddShape(shp) < 0)
            {
                throw new Exception("Error in adding shape. Error: " + sfLines.ErrorMsg[sfLines.LastErrorCode]);
            }
        }
示例#11
0
        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);
            }
        }
示例#12
0
        private void CreateLayer()
        {
            var sf = new Shapefile();

            sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);

            var shp = new Shape();

            shp.Create(sf.ShapefileType);
            // 24.0, 57.0
            shp.AddPoint(23.8, 56.8);
            shp.AddPoint(23.8, 57.2);
            shp.AddPoint(24.2, 57.2);
            shp.AddPoint(24.2, 56.8);
            shp.AddPoint(23.8, 56.8);
            Assert.IsTrue(shp.IsValid, "Shape is invalid");

            sf.EditAddShape(shp);
            _axMap1.AddLayer(sf, true);
            _axMap1.ZoomToShape(0, 0);
            _axMap1.ZoomOut(0.5);
            _axMap1.ZoomToTileLevel(_axMap1.Tiles.CurrentZoom);
        }
示例#13
0
        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);
        }
示例#14
0
        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);
            }
        }
示例#15
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);
        }
示例#16
0
        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();
        }
        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);
            }
        }
示例#18
0
        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;
                }
            }
        }
示例#19
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);
        }
示例#20
0
        public static bool ShowLandingSitesOnMap(MapLayersHandler layersHandler, string aoiGUID, GeoProjection gp, ref string layerName, bool uniqueLayerName = false)
        {
            layerName = "Landing sites";
            var myDT = new DataTable();
            var iShp = -1;

            using (var conection = new OleDbConnection(global.ConnectionString))
            {
                try
                {
                    conection.Open();
                    string query = $@"SELECT Municipality, ProvinceName, LSName, cx, cy
                                    FROM Provinces INNER JOIN (Municipalities INNER JOIN tblLandingSites ON Municipalities.MunNo = tblLandingSites.MunNo)
                                    ON Provinces.ProvNo = Municipalities.ProvNo
                                    WHERE tblLandingSites.AOIGuid={{{aoiGUID}}}";

                    var adapter = new OleDbDataAdapter(query, conection);
                    adapter.Fill(myDT);
                    if (myDT.Rows.Count > 0)
                    {
                        var sf = new Shapefile();
                        if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POINT))
                        {
                            var ifldName = sf.EditAddField("Name", FieldType.STRING_FIELD, 1, 50);
                            var ifldLGU  = sf.EditAddField("LGU", FieldType.STRING_FIELD, 1, 50);
                            var ifldX    = sf.EditAddField("x", FieldType.DOUBLE_FIELD, 8, 12);
                            var ifldY    = sf.EditAddField("y", FieldType.DOUBLE_FIELD, 8, 12);
                            sf.GeoProjection = gp;

                            for (int i = 0; i < myDT.Rows.Count; i++)
                            {
                                DataRow dr = myDT.Rows[i];
                                if (dr["cx"].ToString().Length > 0 && dr["cy"].ToString().Length > 0)
                                {
                                    var x    = (double)dr["cx"];
                                    var y    = (double)dr["cy"];
                                    var name = dr["LSName"].ToString();
                                    var LGU  = $"{dr["Municipality"].ToString()}, {dr["ProvinceName"].ToString()}";
                                    var shp  = new Shape();
                                    if (shp.Create(ShpfileType.SHP_POINT))
                                    {
                                        if (global.MappingMode == fad3MappingMode.grid25Mode)
                                        {
                                            var converter = new LatLngUTMConverter("WGS 84");
                                            var result    = converter.convertLatLngToUtm(y, x);
                                            x = result.Easting;
                                            y = result.Northing;
                                        }

                                        shp.AddPoint(x, y);

                                        iShp = sf.EditAddShape(shp);
                                        if (iShp >= 0)
                                        {
                                            sf.EditCellValue(ifldName, iShp, name);
                                            sf.EditCellValue(ifldLGU, iShp, LGU);
                                            sf.EditCellValue(ifldX, iShp, x);
                                            sf.EditCellValue(ifldY, iShp, y);
                                        }
                                    }
                                }
                            }
                            sf.DefaultDrawingOptions.PointShape  = tkPointShapeType.ptShapeCircle;
                            sf.DefaultDrawingOptions.FillColor   = new Utils().ColorByName(tkMapColor.Red);
                            sf.DefaultDrawingOptions.PointSize   = 7;
                            sf.DefaultDrawingOptions.LineVisible = false;
                            if (sf.Labels.Generate("[Name]", tkLabelPositioning.lpCenter, false) > 0)
                            {
                                sf.Labels.FontSize     = 7;
                                sf.Labels.FontBold     = true;
                                sf.Labels.FrameVisible = false;
                            }
                            if (iShp >= 0)
                            {
                                layersHandler.AddLayer(sf, layerName, true, uniqueLayerName);
                            }
                        }
                    }
                }
                catch (Exception ex) { Logger.Log(ex.Message, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name); }
            }

            return(iShp >= 0);
        }
示例#21
0
        /// <summary>
        /// Constructs the minor grid lines. This yields a rectangular grid of lines which may be clipped later on.
        /// </summary>
        /// <param name="extentIsMaxExtent"></param>
        private bool ConstructMinorGridLines(bool extentIsMaxExtent)
        {
            var success = false;

            _shapefileMinorGridLines = new Shapefile();
            int subgridCount = 0;

            if (_shapefileMinorGridLines.CreateNewWithShapeID("", ShpfileType.SHP_POLYLINE))
            {
                _shapefileMinorGridLines.GeoProjection = _axMap.GeoProjection;
                _shapefileMinorGridLines.With(sf =>
                {
                    var ifldBoundary  = sf.EditAddField("isBoundary", FieldType.STRING_FIELD, 1, 1);
                    var iFldDirection = sf.EditAddField("RowOrCol", FieldType.STRING_FIELD, 1, 1);
                    _ifldLineType     = sf.EditAddField("LineType", FieldType.STRING_FIELD, 1, 2);

                    var ht  = (int)Math.Abs(_minorGridExtents.yMax - _minorGridExtents.yMin);
                    var wdt = (int)Math.Abs(_minorGridExtents.xMax - _minorGridExtents.xMin);

                    if (extentIsMaxExtent)
                    {
                        _minorGridMBRHeight = ht;
                        _minorGridMBRWidth  = wdt;
                    }
                    else
                    {
                        if (_grid25MajorGrid.GridIsDefinedFromLayout || EnsureSize)
                        {
                            _minorGridMBRHeight = ((ht / CELLSIDE) * CELLSIDE);
                            _minorGridMBRWidth  = ((wdt / CELLSIDE) * CELLSIDE);
                        }
                        else
                        {
                            _minorGridMBRHeight = ((ht / CELLSIDE) * CELLSIDE) + CELLSIDE;
                            _minorGridMBRWidth  = ((wdt / CELLSIDE) * CELLSIDE) + CELLSIDE;
                        }

                        if (_isIntersect)
                        {
                            if (_minorGridMBRWidth - wdt == CELLSIDE)
                            {
                                _minorGridMBRWidth = wdt;
                            }

                            if (_minorGridMBRHeight - ht == CELLSIDE)
                            {
                                _minorGridMBRHeight = ht;
                            }
                        }
                    }

                    _minorGridRows    = (int)_minorGridMBRHeight / CELLSIDE;
                    _minorGridColumns = (int)_minorGridMBRWidth / CELLSIDE;
                    _minorGridOriginX = (int)(_minorGridExtents.xMin / CELLSIDE) * CELLSIDE;
                    _minorGridOriginY = (int)(_minorGridExtents.yMin / CELLSIDE) * CELLSIDE;

                    _minorGridExtents.SetBounds(_minorGridOriginX, _minorGridOriginY, 0, _minorGridMBRWidth, _minorGridMBRHeight, 0);

                    //now construct the row lines of the minor grid
                    var shpIndex = -1;
                    if (_grid25MajorGrid.HasSubgrid)
                    {
                        AddSubgrid(SubGridType.Row, 0, iFldDirection, ifldBoundary, _ifldLineType);
                        AddSubgrid(SubGridType.Column, 0, iFldDirection, ifldBoundary, _ifldLineType);
                    }
                    for (int row = 1; row < _minorGridRows; row++)
                    {
                        Shape shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POLYLINE))
                        {
                            var ptX = _minorGridOriginX;
                            var ptY = (row * CELLSIDE) + _minorGridOriginY;
                            shp.AddPoint(ptX, ptY);

                            ptX = _minorGridOriginX + _minorGridMBRWidth;
                            ptY = (row * CELLSIDE) + _minorGridOriginY;
                            shp.AddPoint(ptX, ptY);

                            shpIndex = _shapefileMinorGridLines.EditAddShape(shp);
                            if (shpIndex >= 0)
                            {
                                _shapefileMinorGridLines.EditCellValue(iFldDirection, shpIndex, "R");
                                _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "F");

                                if (!_grid25MajorGrid.HasSubgrid && ptY % FishingGrid.MajorGridSizeMeters == 0)
                                {
                                    _shapefileMinorGridLines.EditCellValue(_ifldLineType, shpIndex, "MG");
                                }
                                else
                                {
                                    _shapefileMinorGridLines.EditCellValue(_ifldLineType, shpIndex, "MG");
                                }

                                if (row == 1)
                                {
                                    _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "T");
                                }

                                if (row == _minorGridRows)
                                {
                                    _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "T");
                                }

                                if (_grid25MajorGrid.HasSubgrid)
                                {
                                    AddSubgrid(SubGridType.Row, row, iFldDirection, ifldBoundary, _ifldLineType);
                                }
                            }
                        }
                    }

                    //construct the column lines
                    for (int col = 1; col < _minorGridColumns; col++)
                    {
                        Shape shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POLYLINE))
                        {
                            var ptX = (col * CELLSIDE) + _minorGridOriginX;
                            var ptY = _minorGridOriginY;
                            shp.AddPoint(ptX, ptY);

                            ptX = (col * CELLSIDE) + _minorGridOriginX;
                            ptY = _minorGridOriginY + _minorGridMBRHeight;
                            shp.AddPoint(ptX, ptY);

                            shpIndex = _shapefileMinorGridLines.EditAddShape(shp);
                            _shapefileMinorGridLines.EditCellValue(iFldDirection, shpIndex, "C");
                            _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "F");

                            if (!_grid25MajorGrid.HasSubgrid && ptX % FishingGrid.MajorGridSizeMeters == 0)
                            {
                                _shapefileMinorGridLines.EditCellValue(_ifldLineType, shpIndex, "MG");
                            }
                            else
                            {
                                _shapefileMinorGridLines.EditCellValue(_ifldLineType, shpIndex, "MG");
                            }

                            if (col == 1)
                            {
                                _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "T");
                            }

                            if (col == _minorGridColumns)
                            {
                                _shapefileMinorGridLines.EditCellValue(ifldBoundary, shpIndex, "T");
                            }

                            if (_grid25MajorGrid.HasSubgrid)
                            {
                                AddSubgrid(SubGridType.Column, col, iFldDirection, ifldBoundary, _ifldLineType);
                            }
                        }
                    }

                    success = true;
                });
            }

            return(success);
        }
示例#22
0
        public static Shapefile CreateGrid25MajorGrid()
        {
            var   sf = new Shapefile();
            Shape shp;
            Point pt;
            var   xOrigin       = 0;
            var   yOrigin       = 0;
            var   cols          = 0;
            var   rows          = 0;
            var   gridNumber    = 0;
            var   iFld          = 0;
            var   offsetColumns = 0;
            var   iShp          = 0;

            if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON))
            {
                iFld = sf.EditAddField("Grid_no", FieldType.INTEGER_FIELD, 1, 4);
                sf.EditAddField("toGrid", FieldType.STRING_FIELD, 1, 1);
                sf.GeoProjection.SetWgs84Projection(GeoProjecction);

                //set the origin, rows and columns
                //yOrigin = FishingGrid.Grid25.MajorGridYOrigin;
                //xOrigin = FishingGrid.Grid25.MajorGridXOrigin;
                switch (GeoProjecction)
                {
                case tkWgs84Projection.Wgs84_UTM_zone_50N:
                    xOrigin = 300000;
                    //yOrigin = 800000;
                    yOrigin       = 400000;
                    cols          = 15;
                    rows          = 21;
                    offsetColumns = 0;
                    gridNumber    = 1;
                    break;

                case tkWgs84Projection.Wgs84_UTM_zone_51N:
                    xOrigin       = 0;
                    yOrigin       = 350000;
                    cols          = 20;
                    rows          = 41;
                    offsetColumns = 10;
                    gridNumber    = 11;
                    break;
                }

                //build the major grids
                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                        shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POLYGON))
                        {
                            for (int n = 0; n < 5; n++)
                            {
                                pt = new Point();
                                switch (n)
                                {
                                case 0:
                                    pt.x = xOrigin + (col * GRIDSIZE);
                                    pt.y = yOrigin + (row * GRIDSIZE);
                                    break;

                                case 1:
                                    pt.x = xOrigin + (col * GRIDSIZE);
                                    pt.y = yOrigin + GRIDSIZE + (row * GRIDSIZE);
                                    break;

                                case 2:
                                    pt.x = xOrigin + GRIDSIZE + (col * GRIDSIZE);
                                    pt.y = yOrigin + GRIDSIZE + (row * GRIDSIZE);
                                    break;

                                case 3:
                                    pt.x = xOrigin + GRIDSIZE + (col * GRIDSIZE);
                                    pt.y = yOrigin + (row * GRIDSIZE);
                                    break;

                                case 4:
                                    pt.x = xOrigin + (col * GRIDSIZE);
                                    pt.y = yOrigin + (row * GRIDSIZE);
                                    break;
                                }
                                shp.AddPoint(pt.x, pt.y);
                            }
                            iShp = sf.EditAddShape(shp);

                            if (iShp >= 0)
                            {
                                sf.EditCellValue(iFld, iShp, gridNumber);
                            }

                            gridNumber++;
                        }
                    }
                    gridNumber += offsetColumns;
                }
            }

            if (sf.NumShapes > 0)
            {
                MajorGrid = sf;
                ConfigureGridAppearance();
            }
            return(sf);
        }
        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);
            }
        }
示例#24
0
        /// <summary>
        /// Functionality to build the graticule.Input parameters are actually from the  extent of a map control
        /// </summary>
        /// <param name="xMax"></param>
        /// <param name="yMax"></param>
        /// <param name="xMin"></param>
        /// <param name="yMin"></param>
        private void ComputeGraticule(double xMax, double yMax, double xMin, double yMin)
        {
            double titleX           = 0;
            double titleY           = 0;
            var    coordinateString = "";
            var    coord            = new ISO_Classes.Coordinate();
            var    tempW            = 0D;
            var    tempH            = 0D;

            _mapExtents = new Extents();
            _mapExtents.SetBounds(xMin, yMin, 0, xMax, yMax, 0);

            _graticuleExtents = new Extents();

            //0.93 means that the graticule is 93% of the map extent
            tempW = (xMax - xMin) * 0.93;
            tempH = (yMax - yMin) * 0.93;

            //compute the origin of the graticule
            _xOrigin = (xMin + ((xMax - xMin) / 2)) - (tempW / 2);
            _yOrigin = (yMin + ((yMax - yMin) / 2)) - (tempH / 2);

            tempH = (yMax - yMin) * 0.87;

            var ticLength = Math.Abs(xMin - _xOrigin) / 4;

            _graticuleExtents.SetBounds(_xOrigin, _yOrigin, 0, _xOrigin + tempW, _yOrigin + tempH, 0);

            //boundary extent is used in calculating the mask. The mask hides parts of the map control between the edge of the map control and the boundary
            _boundaryExtents = new Extents();
            _boundaryExtents.SetBounds(_xOrigin, _yOrigin, 0, _xOrigin + tempW, _yOrigin + tempH, 0);

            var graticuleShape = _graticuleExtents.ToShape();

            //build the Border of the graticule
            Point pt1, pt2;
            Shape shp;

            for (int n = 0; n < 4; n++)
            {
                pt1   = new Point();
                pt2   = new Point();
                pt1.x = graticuleShape.Point[n].x;
                pt1.y = graticuleShape.Point[n].y;
                pt2.x = graticuleShape.Point[n + 1].x;
                pt2.y = graticuleShape.Point[n + 1].y;
                shp   = new Shape();
                if (shp.Create(ShpfileType.SHP_POLYLINE))
                {
                    shp.AddPoint(pt1.x, pt1.y);
                    shp.AddPoint(pt2.x, pt2.y);
                    var iShp = _sfGraticule.EditAddShape(shp);
                    _sfGraticule.EditCellValue(_ifldPart, iShp, "Border");
                    if (n == 1)
                    {
                        //_sfGraticule.EditCellValue(_ifldLabel, iShp, MapTitle);
                        titleX = pt1.x;
                        titleY = pt1.y;
                    }
                }
            }

            xMax        = graticuleShape.Extents.xMax;
            yMax        = graticuleShape.Extents.yMax;
            xMin        = graticuleShape.Extents.xMin;
            yMin        = graticuleShape.Extents.yMin;
            _gridHeight = yMax - yMin;
            _gridWidth  = xMax - xMin;

            var sideLength = _gridHeight;

            if (_gridWidth > _gridHeight)
            {
                sideLength = _gridWidth;
            }

            var factor = 60;

            _intervalSize = (sideLength / (NumberOfGridlines - 1)) * factor;
            var roundTo = (int)(_intervalSize / 5) * 5;

            if (roundTo == 0)
            {
                factor        = 60 * 60;
                _intervalSize = (sideLength / (NumberOfGridlines - 1)) * factor;
                roundTo       = (int)(_intervalSize / 5) * 5;
            }

            roundTo = SetInterval((int)roundTo);

            //setup label categories
            _sfGraticule.Labels.AddCategory("Top");
            _sfGraticule.Labels.AddCategory("Bottom");
            _sfGraticule.Labels.AddCategory("Right");
            _sfGraticule.Labels.AddCategory("Left");
            _sfGraticule.Labels.AddCategory("Title");

            //setup display options of labels
            for (int n = 0; n < _sfGraticule.Labels.NumCategories; n++)
            {
                _sfGraticule.Labels.Category[n].FontBold        = BoldLabels;
                _sfGraticule.Labels.Category[n].FontSize        = LabelFontSize;
                _sfGraticule.Labels.Category[n].FrameVisible    = false;
                _sfGraticule.Labels.Category[n].LineOrientation = tkLineLabelOrientation.lorPerpindicular;
                _sfGraticule.Labels.AvoidCollisions             = false;
                switch (_sfGraticule.Labels.Category[n].Name)
                {
                case "Top":
                    _sfGraticule.Labels.Category[n].Alignment = tkLabelAlignment.laTopCenter;
                    break;

                case "Bottom":
                    _sfGraticule.Labels.Category[n].Alignment = tkLabelAlignment.laBottomCenter;
                    break;

                case "Left":
                case "Right":
                    _sfGraticule.Labels.Category[n].Alignment = tkLabelAlignment.laCenter;
                    break;

                case "Title":
                    _sfGraticule.Labels.AddLabel(MapTitle, titleX, titleY + ((_axMap.Extents.yMax - titleY) / 2), Category: n);
                    _sfGraticule.Labels.Category[n].Alignment = tkLabelAlignment.laTopRight;
                    _sfGraticule.Labels.Category[n].FontSize  = 16;
                    _sfGraticule.Labels.Category[n].FontBold  = true;
                    break;
                }
            }

            //set interval size which determines spacing of gridlines
            _intervalSize = (int)(_intervalSize / roundTo) * roundTo;

            if (_intervalSize >= 1)
            {
                _intervalSize /= factor;
                double baseX = ((int)(_xOrigin - (int)_xOrigin) * factor);
                if (baseX / roundTo != (baseX / 10))
                {
                    baseX = ((baseX / roundTo) + 1) * roundTo;
                }
                baseX = (int)_xOrigin + (baseX / factor);

                _sfGraticule.Labels.AddCategory("Top");
                while (baseX < xMax)
                {
                    if (baseX > xMin)
                    {
                        shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POLYLINE))
                        {
                            //Build the vertical gridlines
                            shp.AddPoint(baseX, yMin);
                            shp.AddPoint(baseX, yMax);
                            var iShp = _sfGraticule.EditAddShape(shp);
                            _sfGraticule.EditCellValue(_ifldPart, iShp, "Gridline");

                            //set tics on the bottom side
                            if (BottomHasLabel)
                            {
                                shp = new Shape();
                                if (shp.Create(ShpfileType.SHP_POLYLINE))
                                {
                                    shp.AddPoint(baseX, yMin);
                                    shp.AddPoint(baseX, yMin - ticLength);
                                    iShp = _sfGraticule.EditAddShape(shp);
                                    _sfGraticule.EditCellValue(_ifldPart, iShp, "tic");

                                    //we input the tic's location to the coordinate class
                                    coord.SetD((float)shp.Center.y, (float)shp.Center.x);

                                    //coordinate string is the formatted coordinate of the tic label
                                    coordinateString = coord.ToString(false, CoordFormat);

                                    _sfGraticule.EditCellValue(_ifldLabel, iShp, coordinateString);
                                    _sfGraticule.EditCellValue(_ifldSide, iShp, "B");
                                    _sfGraticule.Labels.AddLabel(coordinateString, baseX, yMin - ticLength, 0, 1);
                                }
                            }

                            //set tics on the top side
                            if (TopHasLabel)
                            {
                                shp = new Shape();
                                if (shp.Create(ShpfileType.SHP_POLYLINE))
                                {
                                    shp.AddPoint(baseX, yMax);
                                    shp.AddPoint(baseX, yMax + ticLength);
                                    iShp = _sfGraticule.EditAddShape(shp);
                                    _sfGraticule.EditCellValue(_ifldPart, iShp, "tic");
                                    coord.SetD((float)shp.Center.y, (float)shp.Center.x);
                                    coordinateString = coord.ToString(false, CoordFormat);
                                    _sfGraticule.EditCellValue(_ifldLabel, iShp, coordinateString);
                                    _sfGraticule.EditCellValue(_ifldSide, iShp, "T");
                                    _sfGraticule.Labels.AddLabel(coordinateString, baseX, yMax + ticLength, 0, 0);
                                }
                            }
                        }
                    }
                    baseX += _intervalSize;
                }

                double baseY = (int)((_yOrigin - (int)_yOrigin) * factor);
                if (baseY / roundTo != (int)(baseY / roundTo))
                {
                    baseY = ((int)(baseY / roundTo) + 1) * roundTo;
                }
                baseY = (int)_yOrigin + (baseY / factor);

                while (baseY < yMax)
                {
                    if (baseY > yMin)
                    {
                        shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POLYLINE))
                        {
                            //build the horizontal gridlines
                            shp.AddPoint(xMin, baseY);
                            shp.AddPoint(xMax, baseY);
                            var iShp = _sfGraticule.EditAddShape(shp);
                            _sfGraticule.EditCellValue(_ifldPart, iShp, "GridLine");
                        }

                        //set tics on the left side
                        if (LeftHasLabel)
                        {
                            shp = new Shape();
                            if (shp.Create(ShpfileType.SHP_POLYLINE))
                            {
                                shp.AddPoint(xMin, baseY);
                                shp.AddPoint(xMin - ticLength, baseY);
                                var iShp = _sfGraticule.EditAddShape(shp);
                                _sfGraticule.EditCellValue(_ifldPart, iShp, "tic");
                                coord.SetD((float)shp.Center.y, (float)shp.Center.x);
                                coordinateString = coord.ToString(isYcoord: true, format: CoordFormat);
                                _sfGraticule.EditCellValue(_ifldLabel, iShp, coordinateString);
                                _sfGraticule.EditCellValue(_ifldSide, iShp, "L");

                                //we add tic label and rotate the label 270 degrees
                                _sfGraticule.Labels.AddLabel(coordinateString, xMin - (ticLength * 2), baseY, 270, 3);
                            }
                        }

                        //set tics on the right side
                        if (RightHasLabel)
                        {
                            shp = new Shape();
                            if (shp.Create(ShpfileType.SHP_POLYLINE))
                            {
                                shp.AddPoint(xMax, baseY);
                                shp.AddPoint(xMax + ticLength, baseY);
                                var iShp = _sfGraticule.EditAddShape(shp);
                                _sfGraticule.EditCellValue(_ifldPart, iShp, "tic");
                                coord.SetD((float)shp.Center.y, (float)shp.Center.x);
                                coordinateString = coord.ToString(isYcoord: true, format: CoordFormat);
                                _sfGraticule.EditCellValue(_ifldLabel, iShp, coordinateString);
                                _sfGraticule.EditCellValue(_ifldSide, iShp, "R");

                                //we add tic label and rotate the label 90 degrees
                                _sfGraticule.Labels.AddLabel(coordinateString, xMax + (ticLength * 2), baseY, 90, 2);
                            }
                        }
                    }

                    baseY += _intervalSize;
                }

                //sets up appearance of the various lines that make up the graticule
                if (_sfGraticule.Categories.Generate(_ifldPart, tkClassificationType.ctUniqueValues, 1))
                {
                    for (int n = 0; n < _sfGraticule.Categories.Count; n++)
                    {
                        var category = _sfGraticule.Categories.Item[n];
                        switch (category.Expression)
                        {
                        case @"[Part] = ""Border""":
                        case @"[Part] = ""tic""":
                            category.DrawingOptions.LineWidth = BorderWidth;
                            category.DrawingOptions.LineColor = BorderColor;
                            break;

                        default:
                            category.DrawingOptions.VerticesColor = new Utils().ColorByName(tkMapColor.Gray);
                            category.DrawingOptions.LineWidth     = GridlinesWidth;
                            category.DrawingOptions.LineVisible   = GridVisible;
                            break;
                        }
                    }

                    _sfGraticule.Categories.ApplyExpressions();
                }
            }
            else
            {
                throw new Exception("Graticule: Interval size is invalid");
            }
        }
        private static void AddToPolygonSf(IShapefile sfPolygons, Helper.Coordinate coordinate1_1,
                                           Helper.Coordinate coordinate1_2, Helper.Coordinate coordinate2_1, Helper.Coordinate coordinate2_2)
        {
            var shp = new Shape();

            if (!shp.Create(ShpfileType.SHP_POLYGON))
            {
                throw new Exception("Error in creating shape. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (shp.AddPoint(coordinate1_1.X, coordinate1_1.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (shp.AddPoint(coordinate1_2.X, coordinate1_2.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (shp.AddPoint(coordinate2_1.X, coordinate2_1.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (shp.AddPoint(coordinate2_2.X, coordinate2_2.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            // Closing:
            if (shp.AddPoint(coordinate1_1.X, coordinate1_1.Y) < 0)
            {
                throw new Exception("Error in adding point. Error: " + shp.ErrorMsg[shp.LastErrorCode]);
            }
            if (!shp.PartIsClockWise[0])
            {
                shp.ReversePointsOrder(0);
            }
            if (!shp.IsValid)
            {
                shp = shp.FixUp2(tkUnitsOfMeasure.umMeters);
                if (shp == null)
                {
                    return;
                }
                if (!shp.IsValid)
                {
                    throw new Exception("Error: shape is not valid. " + shp.IsValidReason);
                }
            }

            // Check if this new shape is overlapping other shapes,
            // if so clip and add that version instead:
            var numShapes = sfPolygons.NumShapes;

            for (var i = 0; i < numShapes; i++)
            {
                var shpTesting = sfPolygons.Shape[i];
                // If within, don't add again:
                if (shp.Within(shpTesting))
                {
                    Debug.WriteLine("Shape is within " + i);
                    return;
                }
                // If overlaps, add only new part:
                if (shp.Overlaps(shpTesting))
                {
                    Debug.WriteLine(i + " overlaps. Touches: " + shp.Touches(shpTesting));
                    // TODO: Returns wrong part:
                    //shp = shpTesting.Clip(shp, tkClipOperation.clDifference);
                    //if (shp == null) return;
                }
            }

            if (shp.ShapeType2D != ShpfileType.SHP_POLYGON)
            {
                return;
            }

            if (!shp.PartIsClockWise[0])
            {
                shp.ReversePointsOrder(0);
            }
            if (!shp.IsValid)
            {
                shp = shp.FixUp2(tkUnitsOfMeasure.umMeters);
                if (shp == null)
                {
                    return;
                }
                if (!shp.IsValid)
                {
                    throw new Exception("Error: shape is not valid. " + shp.IsValidReason);
                }
            }


            if (shp.ShapeType2D != ShpfileType.SHP_POLYGON)
            {
                return;
            }
            if (sfPolygons.EditAddShape(shp) < 0)
            {
                throw new Exception("Error in adding shape. Error: " + sfPolygons.ErrorMsg[sfPolygons.LastErrorCode]);
            }
        }
        public bool MapSamplingFishingGround(string samplingGuid, fadUTMZone utmZone, string layerName)
        {
            var           success = false;
            string        refNo   = "";
            List <string> fg      = new List <string>();
            DataTable     dt      = new DataTable();

            using (var conection = new OleDbConnection(global.ConnectionString))
            {
                try
                {
                    conection.Open();
                    var sql     = $"Select RefNo from tblSampling WHERE SamplingGUID = {{{samplingGuid}}}";
                    var adapter = new OleDbDataAdapter(sql, conection);
                    adapter.Fill(dt);
                    DataRow dr = dt.Rows[0];
                    refNo = dr["RefNo"].ToString();

                    sql = $@"SELECT FishingGround FROM tblSampling WHERE SamplingGUID={{{samplingGuid}}}
                        UNION ALL
                        SELECT GridName from tblGrid
                        WHERE SamplingGUID={{{samplingGuid}}}";

                    dt.Rows.Clear();
                    adapter = new OleDbDataAdapter(sql, conection);
                    adapter.Fill(dt);

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dr = dt.Rows[i];
                        fg.Add(dr["FishingGround"].ToString());
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex.Message, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name);
                }
            }

            if (fg.Count > 0)
            {
                var sf = new Shapefile();
                if (sf.CreateNew("", ShpfileType.SHP_POINT))
                {
                    MapLayersHandler.RemoveLayer(layerName);
                    sf.GeoProjection = _geoProjection;
                    var ifldLabel = sf.EditAddField("Label", FieldType.STRING_FIELD, 1, 15);
                    sf.FieldByName["Label"].Alias = "Fishing ground";
                    var ifldRefNo = sf.EditAddField("RefNo", FieldType.STRING_FIELD, 1, 20);
                    sf.FieldByName["RefNo"].Alias = "Reference number";
                    foreach (var item in fg)
                    {
                        var shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POINT))
                        {
                            var iShp   = 0;
                            var result = FishingGrid.Grid25ToLatLong(item, utmZone);
                            iShp = shp.AddPoint(result.longitude, result.latitude);

                            if (iShp >= 0 && sf.EditInsertShape(shp, 0))
                            {
                                sf.EditCellValue(ifldLabel, iShp, item);
                                sf.EditCellValue(ifldRefNo, iShp, refNo);
                                sf.CollisionMode = tkCollisionMode.AllowCollisions;
                            }
                        }
                    }
                    sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsCircle);
                    sf.DefaultDrawingOptions.FillColor   = new Utils().ColorByName(tkMapColor.Red);
                    sf.DefaultDrawingOptions.PointSize   = 7;
                    sf.DefaultDrawingOptions.LineVisible = false;
                    success = MapLayersHandler.AddLayer(sf, layerName, true, true) >= 0;
                    if (MapControl == null)
                    {
                        MapControl = global.MappingForm.MapControl;
                    }
                    if (!MapControl.Extents.ToShape().Contains(sf.Extents.ToShape()))
                    {
                        Point   pt  = sf.Extents.ToShape().Center;
                        Extents ext = MapControl.Extents;
                        ext.MoveTo(pt.x, pt.y);
                        MapControl.Extents = ext;
                    }
                }
            }
            return(success);
        }
示例#27
0
        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);
        }
示例#28
0
        private bool SpeciesOccurenceMapping()
        {
            string sql = "";

            if (Aggregate)
            {
                if (MapInSelectedTargetArea)
                {
                    sql = $@"SELECT tblAOI.AOIName,
                                tblSampling.FishingGround,
                                Count(tblSampling.SamplingGUID) AS n,
                                tblAOI.UTMZone
                            FROM (tblSampling INNER JOIN
                                tblAOI ON
                                tblSampling.AOI = tblAOI.AOIGuid) INNER JOIN
                                tblCatchComp ON tblSampling.SamplingGUID = tblCatchComp.SamplingGUID
                            WHERE tblCatchComp.NameGUID = {{{ItemToMapGuid}}} AND
                                Year([SamplingDate]) In ({YearsToCSV()}) AND
                                tblSampling.FishingGround Is Not Null AND
                                tblAOI.UTMZone Is Not Null AND
                                tblAOI.AOIGuid={{{SelectedTargetAreaGuid}}}
                            GROUP BY tblAOI.AOIName,
                                tblSampling.FishingGround,
                                tblAOI.UTMZone";
                }
                else
                {
                    sql = $@"SELECT tblAOI.AOIName,
                              tblSampling.FishingGround,
                              Count(tblSampling.SamplingGUID) AS n,
                              tblAOI.UTMZone
                            FROM (tblSampling INNER JOIN
                              tblCatchComp ON
                              tblSampling.SamplingGUID = tblCatchComp.SamplingGUID) INNER JOIN
                              tblAOI ON tblSampling.AOI = tblAOI.AOIGuid
                            WHERE Year([SamplingDate]) In ({YearsToCSV()}) AND
                              tblSampling.FishingGround Is Not Null AND
                              tblAOI.UTMZone Is Not Null AND
                              tblCatchComp.NameGUID={{{ItemToMapGuid}}}
                            GROUP BY tblAOI.AOIName,
                              tblSampling.FishingGround,
                              tblAOI.UTMZone";
                }
            }
            else
            {
                if (MapInSelectedTargetArea)
                {
                    sql = $@"SELECT tblAOI.AOIName,
                                tblEnumerators.EnumeratorName,
                                tblSampling.*,
                                tblLandingSites.LSName,
                                tblGearClass.GearClassName,
                                tblGearVariations.Variation,
                                tblAOI.UTMZone
                            FROM tblEnumerators
                                RIGHT JOIN ((tblAOI INNER JOIN tblLandingSites ON
                                tblAOI.AOIGuid = tblLandingSites.AOIGuid) INNER JOIN
                                ((tblGearClass INNER JOIN tblGearVariations ON
                                tblGearClass.GearClass = tblGearVariations.GearClass) INNER JOIN
                                (tblSampling INNER JOIN tblCatchComp ON
                                tblSampling.SamplingGUID = tblCatchComp.SamplingGUID) ON
                                tblGearVariations.GearVarGUID = tblSampling.GearVarGUID) ON
                                tblLandingSites.LSGUID = tblSampling.LSGUID) ON
                                tblEnumerators.EnumeratorID = tblSampling.Enumerator
                            WHERE tblSampling.AOI={{{SelectedTargetAreaGuid}}} AND
                                tblAOI.UTMZone Is Not Null AND
                                tblCatchComp.NameGUID={{{ItemToMapGuid}}} AND
                                Year([SamplingDate]) In ({YearsToCSV()}) AND
                                tblSampling.FishingGround Is Not Null
                            ORDER BY tblAOI.AOIName,
                                tblGearClass.GearClassName,
                                tblGearVariations.Variation,
                                tblSampling.SamplingDate";
                }
                else
                {
                    sql = $@"SELECT tblAOI.AOIName,
                                tblEnumerators.EnumeratorName,
                                tblSampling.*,
                                tblLandingSites.LSName,
                                tblGearClass.GearClassName,
                                tblGearVariations.Variation,
                                tblAOI.UTMZone
                            FROM tblEnumerators
                                RIGHT JOIN ((tblAOI INNER JOIN tblLandingSites ON
                                tblAOI.AOIGuid = tblLandingSites.AOIGuid) INNER JOIN
                                ((tblGearClass INNER JOIN tblGearVariations ON
                                tblGearClass.GearClass = tblGearVariations.GearClass) INNER JOIN
                                (tblSampling INNER JOIN tblCatchComp ON
                                tblSampling.SamplingGUID = tblCatchComp.SamplingGUID) ON
                                tblGearVariations.GearVarGUID = tblSampling.GearVarGUID) ON
                                tblLandingSites.LSGUID = tblSampling.LSGUID) ON
                                tblEnumerators.EnumeratorID = tblSampling.Enumerator
                            WHERE tblCatchComp.NameGUID={{{ItemToMapGuid}}} AND
                                Year([SamplingDate]) In ({YearsToCSV()}) AND
                                tblSampling.FishingGround Is Not Null AND
                                tblAOI.UTMZone Is Not Null
                            ORDER BY tblAOI.AOIName,
                                tblGearClass.GearClassName,
                                tblGearVariations.Variation,
                                tblSampling.SamplingDate";
                }
            }
            try
            {
                var sf = new Shapefile();
                if (sf.CreateNew("", ShpfileType.SHP_POINT))
                {
                    sf.GeoProjection = MapControl.GeoProjection;
                    var ifldTargetArea      = -1;
                    var ifldCount           = -1;
                    var ifldFishingGround   = -1;
                    var ifldSpeciesName     = -1;
                    var ifldGearClass       = -1;
                    var ifldGearVariation   = -1;
                    var ifldCatchWt         = -1;
                    var ifldReferenceNumber = -1;
                    var ifldSamplingDate    = -1;
                    var ifldVesselType      = -1;
                    var ifldLandindSite     = -1;
                    var ifldEnumerator      = -1;
                    if (Aggregate)
                    {
                        ifldTargetArea    = sf.EditAddField("TargetArea", FieldType.STRING_FIELD, 1, 100);
                        ifldFishingGround = sf.EditAddField("FG", FieldType.STRING_FIELD, 1, 8);
                        ifldSpeciesName   = sf.EditAddField("Species", FieldType.STRING_FIELD, 1, 100);
                        ifldCount         = sf.EditAddField("n", FieldType.INTEGER_FIELD, 1, 4);
                    }
                    else
                    {
                        ifldReferenceNumber = sf.EditAddField("RefNo", FieldType.STRING_FIELD, 1, 20);
                        ifldEnumerator      = sf.EditAddField("Enumerator", FieldType.STRING_FIELD, 1, 30);
                        ifldSpeciesName     = sf.EditAddField("Species", FieldType.STRING_FIELD, 1, 100);
                        ifldTargetArea      = sf.EditAddField("TargetArea", FieldType.STRING_FIELD, 1, 100);
                        ifldLandindSite     = sf.EditAddField("LandingSite", FieldType.STRING_FIELD, 1, 50);
                        ifldSamplingDate    = sf.EditAddField("SamplingDate", FieldType.DATE_FIELD, 1, 1);
                        ifldGearClass       = sf.EditAddField("GearClass", FieldType.STRING_FIELD, 1, 25);
                        ifldGearVariation   = sf.EditAddField("GearVariation", FieldType.STRING_FIELD, 1, 35);
                        ifldFishingGround   = sf.EditAddField("FishingGround", FieldType.STRING_FIELD, 1, 8);
                        ifldCatchWt         = sf.EditAddField("CatchWeight", FieldType.DATE_FIELD, 2, 10);
                        ifldVesselType      = sf.EditAddField("Vessel", FieldType.STRING_FIELD, 1, 25);
                    }

                    using (OleDbConnection conn = new OleDbConnection(global.ConnectionString))
                    {
                        conn.Open();
                        var       adapter = new OleDbDataAdapter(sql, conn);
                        DataTable dt      = new DataTable();
                        adapter.Fill(dt);
                        if (dt.Rows.Count > 0)
                        {
                            for (int n = 0; n < dt.Rows.Count; n++)
                            {
                                DataRow    dr      = dt.Rows[n];
                                var        fg      = dr["FishingGround"].ToString();
                                var        zone    = dr["UTMZone"].ToString();
                                fadUTMZone utmZone = FishingGrid.ZoneFromZoneName(zone);
                                FishingGrid.UTMZone = utmZone;
                                var latlong = FishingGrid.Grid25ToLatLong(fg, utmZone);
                                var shp     = new Shape();
                                if (shp.Create(ShpfileType.SHP_POINT) && shp.AddPoint(latlong.longitude, latlong.latitude) >= 0)
                                {
                                    var iShp = sf.EditAddShape(shp);
                                    if (Aggregate)
                                    {
                                        if (sf.EditCellValue(ifldTargetArea, iShp, dr["AOIName"].ToString()))
                                        {
                                            sf.EditCellValue(ifldCount, iShp, (int)dr["n"]);
                                            sf.EditCellValue(ifldSpeciesName, iShp, ItemName);
                                            sf.EditCellValue(ifldFishingGround, iShp, fg);
                                        }
                                    }
                                    else
                                    {
                                        sf.EditCellValue(ifldSpeciesName, iShp, ItemName);
                                        sf.EditCellValue(ifldEnumerator, iShp, dr["EnumeratorName"].ToString());
                                        sf.EditCellValue(ifldTargetArea, iShp, dr["AOIName"].ToString());
                                        sf.EditCellValue(ifldFishingGround, iShp, fg);
                                        sf.EditCellValue(ifldGearClass, iShp, dr["GearClassName"].ToString());
                                        sf.EditCellValue(ifldGearVariation, iShp, dr["Variation"].ToString());
                                        sf.EditCellValue(ifldReferenceNumber, iShp, dr["RefNo"].ToString());
                                        sf.EditCellValue(ifldSamplingDate, iShp, string.Format("{0:MMM-dd-yyyy}", (DateTime)dr["SamplingDate"]));
                                        sf.EditCellValue(ifldCatchWt, iShp, (double)dr["WtCatch"]);
                                        sf.EditCellValue(ifldVesselType, iShp, FishingVessel.VesselTypeFromVesselTypeNumber((int)dr["VesType"]));
                                        sf.EditCellValue(ifldLandindSite, iShp, dr["LSName"].ToString());
                                    }
                                }
                            }
                        }
                    }
                    sf.DefaultDrawingOptions.PointShape = tkPointShapeType.ptShapeCircle;
                    ClassificationType classificationType = ClassificationType.None;
                    if (Aggregate)
                    {
                        ShapefileLayerHelper.CategorizeNumericPointLayer(sf, ifldCount);
                        sf.DefaultDrawingOptions.LineVisible = true;
                        sf.DefaultDrawingOptions.LineColor   = new Utils().ColorByName(tkMapColor.White);
                        sf.CollisionMode   = tkCollisionMode.AllowCollisions;
                        classificationType = ClassificationType.JenksFisher;
                    }
                    else
                    {
                        sf.DefaultDrawingOptions.PointSize = 8;
                    }

                    var h = MapLayersHandler.AddLayer(sf, $"Species mapping: {ItemName} ({YearsToCSV()})", mappingMode: fad3MappingMode.occurenceMappingSpeciesAggregated);
                    MapLayersHandler[h].ClassificationType = classificationType;
                    MapControl.Redraw();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message, "OcuurenceMapping", "SpeciesOccurence");
            }
            return(true);
        }
示例#29
0
        /// <summary>
        /// Creates minor grid cells inside major grids intersected with land shapefiles
        /// </summary>
        private static void PopulateMinorGrid()
        {
            MinorGridsShapefile.EditClear();
            FishingGrid.UTMZone = UTMZone;

            int ifldGridNo = Grid25Shapefile.FieldIndexByName["grid_no"];
            var gridNumber = 0;

            //enumerate all intersected major grids
            for (int n = 0; n < _intersectedMajorGrids.Length; n++)
            {
                gridNumber = (int)Grid25Shapefile.CellValue[Grid25Shapefile.FieldIndexByName["grid_no"], _intersectedMajorGrids[n]];

                //get the origin of the current major grid
                var origin = FishingGrid.MajorGridOrigin(gridNumber);

                //build a minor grid, a point at a time. Here we will be creating 5 points, one point for each corner of the grid.
                //The 5th point is needed to close the polygon.
                for (int row = 25; row > 0; row--)
                {
                    for (int col = 0; col < 25; col++)
                    {
                        var shp = new Shape();
                        if (shp.Create(ShpfileType.SHP_POLYGON))
                        {
                            for (int pt = 0; pt < 5; pt++)
                            {
                                switch (pt)
                                {
                                case 0:
                                case 4:
                                    shp.AddPoint(origin.x + (col * 2000), origin.y + ((25 - row) * 2000));
                                    break;

                                case 1:
                                    shp.AddPoint(origin.x + (col * 2000) + 2000, origin.y + ((25 - row) * 2000));
                                    break;

                                case 2:
                                    shp.AddPoint(origin.x + (col * 2000) + 2000, origin.y + ((25 - row) * 2000) + 2000);
                                    break;

                                case 3:
                                    shp.AddPoint(origin.x + (col * 2000), origin.y + ((25 - row) * 2000) + 2000);
                                    break;
                                }
                            }

                            //add the new shape to the shapefile. iShp is the index of the newest added shape
                            var iShp = MinorGridsShapefile.EditAddShape(shp);

                            //a new shape will have an index (iShp) of zero or greater
                            if (iShp >= 0)
                            {
                                //name the cell
                                MinorGridsShapefile.EditCellValue(_iFldName, iShp, $"{gridNumber.ToString()}-{(char)('A' + col)}{row}");

                                //set the inland attribute to false
                                MinorGridsShapefile.EditCellValue(_iFldInland, iShp, false);
                            }
                        }
                    }
                }
            }

            //raise the event that minor grids were created
            if (StatusUpdate != null)
            {
                CreateInlandGridEventArgs e = new CreateInlandGridEventArgs();
                e.Status    = "Minor grids created";
                e.GridCount = MinorGridsShapefile.NumShapes;
                StatusUpdate(e);
            }
        }
        /// <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);
        }