Example #1
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);
        }
Example #2
0
        private static void OnExentCreated(MapInterActionHandler s, LayerEventArg e)
        {
            if (EnableMapInteraction)
            {
                if (_hAOI >= 0)
                {
                    MapWindowManager.MapLayersHandler.RemoveLayer(_hAOI);
                }
                else
                {
                    AOIName = "New AOI";
                }

                _sfAOI = new Shapefile();
                if (_sfAOI.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON))
                {
                    if (_sfAOI.EditAddShape(e.SelectionExtent.ToShape()) >= 0)
                    {
                        _hAOI = MapWindowManager.MapLayersHandler.AddLayer(_sfAOI, AOIName);
                        if (_hAOI >= 0)
                        {
                            var fldName = _sfAOI.EditAddField("Name", FieldType.STRING_FIELD, 1, 1);
                            _sfAOI.Key = "aoi";
                            FormatAOI(_sfAOI);
                        }
                    }
                }
            }
        }
Example #3
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");
            }
        }
Example #4
0
        public void EditAddShapeTest()
        {
            // https://mapwindow.discourse.group/t/system-accessviolationexception-after-editaddshape/196
            var pnt = new Point {
                x = 6.7369281, y = 53.1603648
            };

            var shp = new Shape();

            shp.Create(ShpfileType.SHP_POLYGON);
            shp.InsertPoint(pnt, 0);

            var sf     = new Shapefile();
            var result = sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);

            Assert.IsTrue(result, "CreateNewWithShapeID failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            var shpIndex = sf.EditAddShape(shp);

            Assert.IsTrue(shpIndex > -1, "EditAddShape failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            sf.InteractiveEditing = true;
            Assert.IsTrue(sf.InteractiveEditing, "InteractiveEditing failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            var layerIndex = _axMap1.AddLayer(sf, true);

            Assert.IsTrue(layerIndex > -1, "AddLayer failed: " + sf.ErrorMsg[sf.LastErrorCode]);

            result = _axMap1.ShapeEditor.StartEdit(layerIndex, shpIndex);
            Assert.IsTrue(result, "ShapeEditor.StartEdit failed: " + sf.ErrorMsg[sf.LastErrorCode]);
        }
Example #5
0
        public static void CreatePointShapefile(AxMap Map, List <GisPoint>[] ListData, int num)
        {
            var  sf     = new Shapefile();                                         //创建一个新的shp文件
            bool result = sf.CreateNewWithShapeID("", ShpfileType.SHP_MULTIPOINT); //初始化shp文件

            for (int j = 0; j < num - 1; j++)
            {
                Shape shp = new Shape(); //创建shp图层
                shp.Create(ShpfileType.SHP_MULTIPOINT);
                for (int i = 0; i < ListData[j].Count; i++)
                {
                    var pnt = new Point();
                    pnt.x   = ListData[j][i].X;
                    pnt.y   = ListData[j][i].Y;
                    pnt.Key = "fang";
                    int index = 0;
                    shp.InsertPoint(pnt, ref index);
                }
                sf.EditAddShape(shp);
                if (j == 0)
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("0");
                    ct.DrawingOptions.FillType  = tkFillType.ftGradient;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Green);
                    sf.set_ShapeCategory(0, 0);
                }
                else if (j == 1)
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("1");
                    ct.DrawingOptions.FillType  = tkFillType.ftStandard;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Blue);
                    sf.set_ShapeCategory(1, 1);
                }
                else if (j == 2)
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("2");
                    ct.DrawingOptions.FillType  = tkFillType.ftStandard;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Yellow);
                    sf.set_ShapeCategory(2, 2);
                }
                else
                {
                    var utils            = new Utils();
                    ShapefileCategory ct = sf.Categories.Add("3");
                    ct.DrawingOptions.FillType  = tkFillType.ftStandard;
                    ct.DrawingOptions.FillColor = utils.ColorByName(tkMapColor.Red);
                    sf.set_ShapeCategory(3, 3);
                }
            }
            sf.DefaultDrawingOptions.SetDefaultPointSymbol(tkDefaultPointSymbol.dpsTriangleUp);
            Map.AddLayer(sf, true);
            Map.SendMouseMove = true;
        }
Example #6
0
        public int ComputeFishingFrequency()
        {
            int counter = 0;


            //if the field exists, we delete it so that the old data is also deleted
            var fldIndex = AOI.SubGrids.FieldIndexByName["Hits"];

            if (fldIndex >= 0)
            {
                AOI.SubGrids.EditDeleteField(fldIndex);
            }

            //then we add the Hits field, with emtpy data
            fldIndex = AOI.SubGrids.EditAddField("Hits", FieldType.INTEGER_FIELD, 1, 1);

            if (fldIndex >= 0)
            {
                foreach (var shp in SelectedTracks)
                {
                    var sf = new Shapefile();
                    if (sf.CreateNew("", ShpfileType.SHP_POLYLINE))
                    {
                        sf.GeoProjection = MapWindowManager.ExtractedTracksShapefile.GeoProjection;
                        var idx = sf.EditAddShape(shp);
                        if (idx >= 0)
                        {
                            var selected = new object();
                            AOI.SubGrids.SelectByShapefile(sf, tkSpatialRelation.srIntersects, false, ref selected);
                            var selected2 = (int[])selected;
                            if (selected2.Count() > 0)
                            {
                                for (int x = 0; x < selected2.Count(); x++)
                                {
                                    var cellHit = AOI.SubGrids.CellValue[fldIndex, selected2[x]];
                                    if (cellHit == null)
                                    {
                                        AOI.SubGrids.EditCellValue(fldIndex, selected2[x], 1);
                                    }
                                    else
                                    {
                                        AOI.SubGrids.EditCellValue(fldIndex, selected2[x], (int)cellHit + 1);
                                    }
                                    counter++;
                                }
                            }
                        }
                    }
                }
            }
            HasGriddedData            = true;
            IsFishingInternsityMapped = counter > 0;
            return(counter);
        }
Example #7
0
        private Shapefile CreateCarShapefile(CarService service)
        {
            var sf = new Shapefile();

            sf.CreateNew("", ShpfileType.SHP_POINT);
            sf.DefaultDrawingOptions.AlignPictureByBottom = false;

            var ct  = sf.Categories.Add("Police");
            var opt = ct.DrawingOptions;

            opt.PointType = tkPointSymbolType.ptSymbolPicture;
            opt.Picture   = IconManager.GetIcon(CarType.Police);

            ct            = sf.Categories.Add("Taxi");
            opt           = ct.DrawingOptions;
            opt.PointType = tkPointSymbolType.ptSymbolPicture;
            opt.Picture   = IconManager.GetIcon(CarType.Taxi);

            ct            = sf.Categories.Add("Ambulance");
            opt           = ct.DrawingOptions;
            opt.PointType = tkPointSymbolType.ptSymbolPicture;
            opt.Picture   = IconManager.GetIcon(CarType.Ambulance);

            // general settings for labels should be applied before creating categories
            sf.Labels.FrameVisible      = true;
            sf.Labels.TextRenderingHint = tkTextRenderingHint.ClearTypeGridFit;

            var utils = new Utils();
            var lb    = sf.Labels.AddCategory("Busy");

            lb.FrameBackColor = utils.ColorByName(tkMapColor.Yellow);

            lb = sf.Labels.AddCategory("Available");
            lb.FrameBackColor = utils.ColorByName(tkMapColor.Green);

            lb = sf.Labels.AddCategory("OutOfService");
            lb.FrameBackColor = utils.ColorByName(tkMapColor.Gray);

            Debug.Print("Num categories: " + sf.Labels.NumCategories);

            for (int i = 0; i < service.Cars.Count; i++)
            {
                var car = service.Cars[i];
                var shp = new Shape();
                shp.Create(ShpfileType.SHP_POINT);
                shp.AddPoint(car.X, car.Y);
                sf.EditAddShape(shp);
                sf.ShapeCategory[i] = (int)car.CarType;
                sf.Labels.AddLabel(car.ToString(), car.X, car.Y);
                sf.Labels.Label[i, 0].Category = (int)(car.State);
            }
            return(sf);
        }
Example #8
0
        public static Shapefile AOIShapefileFromAOI(AOI aoi)
        {
            var sf = new Shapefile();

            if (sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON))
            {
                var extent = new Extents();
                extent.SetBounds(aoi.UpperLeftX, aoi.LowerRightY, 0, aoi.LowerRightX, aoi.UpperLeftY, 0);
                if (sf.EditAddShape(extent.ToShape()) >= 0)
                {
                    sf.DefaultDrawingOptions.FillTransparency = 0.25F;
                    return(sf);
                }
            }
            return(null);
        }
Example #9
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);
        }
        private static MergeResult Merge(int layerHandle, Shapefile sf)
        {
            // merging
            Shape shp = null;

            for (int i = 0; i < sf.NumShapes; i++)
            {
                if (sf.ShapeSelected[i])
                {
                    shp = shp == null ? sf.Shape[i].Clone() : shp.Clip(sf.Shape[i], tkClipOperation.clUnion);
                }
            }

            if (shp == null)
            {
                return(MergeResult.Failed);
            }

            // TODO: request for attributes

            // registering in undo list
            var undoList = App.Map.UndoList;

            undoList.BeginBatch();

            for (int i = sf.NumShapes - 1; i >= 0; i--)
            {
                if (sf.ShapeSelected[i])
                {
                    undoList.Add(tkUndoOperation.uoRemoveShape, layerHandle, i);
                    sf.EditDeleteShape(i);
                }
            }
            int shapeIndex = sf.EditAddShape(shp);

            if (shapeIndex != -1)
            {
                undoList.Add(tkUndoOperation.uoAddShape, layerHandle, shapeIndex);
            }

            undoList.EndBatch();

            return(MergeResult.Ok);
        }
Example #11
0
 private void AxMap1_MeasuringChanged(object sender, _DMapEvents_MeasuringChangedEvent e)
 {
     if (e.action == tkMeasuringAction.PointAdded)
     {
     }
     if (e.action == tkMeasuringAction.MesuringStopped)
     {
         if (btnAnotation.Checked)
         {
             Shape shp = new Shape();
             shp.Create(ShpfileType.SHP_POLYGON);
             //shp_tmp.EditAddShape()
             double x, y;
             //Debug.WriteLine("Measured points (in map units.): " + axMap1.Measuring.PointCount);
             for (int i = 0; i < axMap1.Measuring.PointCount; i++)
             {
                 if (axMap1.Measuring.get_PointXY(i, out x, out y))
                 {
                     //var c = 0;
                     MapWinGIS.Point ptn = new MapWinGIS.Point();
                     ptn.Set(x, y);
                     shp.InsertPoint(ptn, ref i);
                     //Debug.WriteLine("x={0}; y={1}", x, y);
                 }
             }
             tmpLayer.EditAddShape(shp);
             axMap1.Redraw();
         }
         if (btnVP.Checked)
         {
             double x, y;
             axMap1.Measuring.get_PointXY(0, out x, out y);
             MapWinGIS.Point pt1 = new Point();
             pt1.Set(x, y);
             axMap1.Measuring.get_PointXY(1, out x, out y);
             MapWinGIS.Point pt2 = new Point();
             pt2.Set(x, y);
             MapWinGIS.Image         DEMImg = axMap1.get_Image(idxLayerRaster);
             Vertical_Profiling_Form vpf    = new Vertical_Profiling_Form(DEMImg, pt1, pt2);
             vpf.Show(this);
             axMap1.Redraw();
         }
     }
 }
        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]);
            }
        }
        public PasteResult Paste(int layerHandle, Shapefile sf)
        {
            if (sf == null || IsEmpty)
            {
                return(PasteResult.NoInput);
            }
            if (!sf.InteractiveEditing)
            {
                return(PasteResult.NoInput);
            }
            if (IsEmpty)
            {
                return(PasteResult.NoInput);
            }

            if (_buffer.ShapefileType != sf.ShapefileType)
            {
                return(PasteResult.ShapeTypeMismatch);
            }

            var fieldMap = _buffer.BuildFieldMap(sf);

            var undoList = App.Map.UndoList;

            undoList.BeginBatch();

            sf.SelectNone();

            for (int i = 0; i < _buffer.NumShapes; i++)
            {
                int shapeIndex = sf.EditAddShape(_buffer.Shape[i].Clone()); // don't create a copy, buffer won't be used any more
                _buffer.CopyAttributes(i, sf, shapeIndex, fieldMap);        // TODO: don't use field map for the same shapefile
                undoList.Add(tkUndoOperation.uoAddShape, layerHandle, shapeIndex);
                sf.ShapeSelected[shapeIndex] = true;
            }

            undoList.EndBatch();

            Clear();
            return(PasteResult.Ok);
        }
Example #14
0
        /// <summary>
        ///Creates a mask that will hide features that fall outside the extent of the fishing grid
        /// </summary>
        /// <returns></returns>
        private void SetMask()
        {
            _shapeFileMask = new Shapefile();
            var sf = new Shapefile();

            if (sf.CreateNew("", ShpfileType.SHP_POLYGON))
            {
                var ext = _axMap.Extents;

                //ef is expansion factor
                var ef = (ext.xMax - ext.xMin) * 0.01;

                ext.SetBounds(ext.xMin - ef, ext.yMin - ef, 0, ext.xMax + ef, ext.yMax + ef, 0);

                var shp = ext.ToShape().Clip(_axMap.get_Shapefile(_handleGridBoundary).Extents.ToShape(), tkClipOperation.clDifference);
                sf.EditAddShape(shp);
                sf.DefaultDrawingOptions.LineVisible = false;
                sf.DefaultDrawingOptions.FillColor   = new Utils().ColorByName(tkMapColor.White);
            }

            _shapeFileMask = sf;
        }
Example #15
0
        private void BtnImport_Click(object sender, EventArgs e)
        {
            if (idxLayerTmp >= 0)
            {
                axMap1.RemoveLayer(idxLayerTmp);
            }
            OpenFileDialog sfd = new OpenFileDialog();

            sfd.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            sfd.FilterIndex      = 0;
            sfd.RestoreDirectory = true;

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamWriter = new StreamReader(sfd.FileName);
                tmpLayer = new Shapefile();
                tmpLayer.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);

                while (!streamWriter.EndOfStream)
                {
                    var   line    = streamWriter.ReadLine();
                    var   listPtn = line.Split(' ');
                    Shape shp     = new Shape();
                    shp.Create(ShpfileType.SHP_POLYGON);
                    for (int i = 1; i < listPtn.Length - 1; i++)
                    {
                        var             xy  = listPtn[i].Remove(listPtn[i].Length - 1).Replace('(', ' ').Replace(')', ' ').Split(';');
                        MapWinGIS.Point ptn = new MapWinGIS.Point();
                        ptn.Set(Convert.ToDouble(xy[0]), Convert.ToDouble(xy[1]));
                        shp.InsertPoint(ptn, ref i);
                    }
                    tmpLayer.EditAddShape(shp);
                }
                streamWriter.Close();
                MessageBox.Show("Done!!");
                idxLayerTmp = axMap1.AddLayer(tmpLayer, true);
            }
        }
Example #16
0
 private void mapControl_MeasuringChanged(object sender, _DMapEvents_MeasuringChangedEvent e)
 {
     if (e.action == tkMeasuringAction.MesuringStopped)
     {
         Shape shp = new Shape();
         shp.Create(ShpfileType.SHP_POLYGON);
         //shp_tmp.EditAddShape()
         double x, y;
         for (int i = 0; i < mapControl.Measuring.PointCount; i++)
         {
             if (mapControl.Measuring.get_PointXY(i, out x, out y))
             {
                 MapWinGIS.Point ptn = new MapWinGIS.Point();
                 ptn.Set(x, y);
                 shp.InsertPoint(ptn, ref i);
             }
         }
         Shapefile sfTmp = mapControl.get_Shapefile(currentLayerIndex);
         sfTmp.EditAddShape(shp);
         MessageBox.Show(sfTmp.NumShapes.ToString());
         mapControl.Redraw();
     }
 }
Example #17
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);
        }
Example #18
0
        public static Shapefile CreateSfFromWkt(string wkt, int epsgCode)
        {
            var sf = new Shapefile();

            if (!sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON))
            {
                throw new Exception("Can't create shapefile. Error: " + sf.ErrorMsg[sf.LastErrorCode]);
            }

            var shp = new Shape();

            if (!shp.ImportFromWKT(wkt))
            {
                throw new Exception("Could not import wkt" + shp.ErrorMsg[shp.LastErrorCode]);
            }

            if (sf.EditAddShape(shp) == -1)
            {
                throw new Exception("Can't EditAddShape. Error: " + sf.ErrorMsg[sf.LastErrorCode]);
            }

            var geoProjection = new GeoProjection();

            if (!geoProjection.ImportFromEPSG(epsgCode))
            {
                throw new Exception("Can't ImportFromEPSG Error: " + geoProjection.ErrorMsg[geoProjection.LastErrorCode]);
            }
            sf.GeoProjection = geoProjection;

            if (sf.HasInvalidShapes())
            {
                throw new Exception("Shapefile has invalid shapes");
            }

            return(sf);
        }
Example #19
0
        /// <summary>
        /// Creates a shapefile mask that hides features outside the extent of the graticule
        /// </summary>
        /// <returns></returns>
        public Shapefile Mask()
        {
            var sf = new Shapefile();

            if (sf.CreateNew("", ShpfileType.SHP_POLYGON))
            {
                var shp = new Shape();
                if (shp.Create(ShpfileType.SHP_POLYGON))
                {
                    //ef is expansion factor
                    var ef = (_mapExtents.xMax - _mapExtents.xMin) * 0.01;

                    _mapExtents.SetBounds(_mapExtents.xMin - ef, _mapExtents.yMin - ef, 0, _mapExtents.xMax + ef, _mapExtents.yMax + (ef), 0);

                    shp = _mapExtents.ToShape().Clip(_boundaryExtents.ToShape(), tkClipOperation.clDifference);
                    var iShp = sf.EditAddShape(shp);
                    sf.DefaultDrawingOptions.LineVisible = false;
                    sf.DefaultDrawingOptions.FillColor   = new Utils().ColorByName(tkMapColor.White);
                    return(sf);
                }
                return(null);
            }
            return(null);
        }
Example #20
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;
                }
            }
        }
Example #21
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);
        }
        // <summary>
        // Performs a segmentation of shapes by regular grid
        // </summary>
        public void Segmentation(AxMap axMap1, string dataPath)
        {
            axMap1.Projection             = tkMapProjection.PROJECTION_NONE;
            axMap1.GrabProjectionFromData = true;

            string[] filenames = new string[2];
            filenames[0] = dataPath + "natural.shp";
            filenames[1] = dataPath + "landuse.shp";

            if (!File.Exists(filenames[0]) || !File.Exists(filenames[1]))
            {
                MessageBox.Show("Couldn't file the files (natural.shp, landuse.shp): " + dataPath);
                return;
            }

            List <Shapefile> layers = new List <Shapefile>();

            for (int i = 0; i < filenames.Length; i++)
            {
                Shapefile sf = new Shapefile();
                sf.Open(filenames[i], null);
                layers.Add(sf);
                axMap1.AddLayer(layers[i], true);
            }

            int     count = 4;
            Extents ext   = axMap1.MaxExtents as Extents;
            double  xStep = (ext.xMax - ext.xMin) / count;
            double  yStep = (ext.yMax - ext.yMin) / count;

            Shapefile sfGrid = new Shapefile();

            sfGrid.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);
            sfGrid.GeoProjection.CopyFrom(layers[0].GeoProjection);

            ColorScheme scheme = new ColorScheme();

            scheme.SetColors2(tkMapColor.Orange, tkMapColor.Yellow);

            for (int i = 0; i < layers.Count; i++)
            {
                string name       = Path.GetFileNameWithoutExtension(layers[i].Filename);
                int    fieldIndex = sfGrid.EditAddField(name, FieldType.DOUBLE_FIELD, 10, 12);
                uint   color      = scheme.GraduatedColor[(i + 1) / (double)layers.Count];
                sfGrid.Charts.AddField2(fieldIndex, color);
            }

            for (int i = 0; i < count; i++)
            {
                for (int j = 0; j < count; j++)
                {
                    Shape shp = new Shape();
                    shp.Create(ShpfileType.SHP_POLYGON);
                    shp.AddPoint(ext.xMin + i * xStep, ext.yMin + j * yStep);
                    shp.AddPoint(ext.xMin + i * xStep, ext.yMin + (j + 1) * yStep);
                    shp.AddPoint(ext.xMin + (i + 1) * xStep, ext.yMin + (j + 1) * yStep);
                    shp.AddPoint(ext.xMin + (i + 1) * xStep, ext.yMin + j * yStep);
                    shp.AddPoint(ext.xMin + i * xStep, ext.yMin + j * yStep);
                    int shapeIndex = sfGrid.EditAddShape(shp);

                    for (int layer = 0; layer < layers.Count; layer++)
                    {
                        Shapefile sf   = layers[layer];
                        double    area = 0.0;
                        for (int n = 0; n < sf.NumShapes; n++)
                        {
                            Shape shp2 = sf.Shape[n];
                            if (shp.Intersects(shp2))
                            {
                                Shape shpResult = shp2.Clip(shp, tkClipOperation.clIntersection);
                                if (shpResult != null)
                                {
                                    area += shpResult.Area;
                                }
                            }
                        }

                        // divide by 10000.0 to convert square meters to hectars
                        bool success = sfGrid.EditCellValue(layer + 1, shapeIndex, area / 10000.0);
                    }
                }
            }

            // generating charts
            Charts charts = sfGrid.Charts;

            charts.Generate(tkLabelPositioning.lpCenter);
            charts.ChartType     = tkChartType.chtPieChart;
            charts.PieRadius     = 18;
            charts.Thickness     = 10;
            charts.ValuesVisible = true;
            charts.Visible       = true;

            ShapeDrawingOptions options = sfGrid.DefaultDrawingOptions;

            options.FillVisible = false;
            options.LineWidth   = 2;
            options.LineStipple = tkDashStyle.dsDash;
            options.LineColor   = 255;

            axMap1.AddLayer(sfGrid, true);
            axMap1.ZoomToMaxExtents();
        }
Example #23
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);
        }
Example #24
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);
        }
        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);
            }
        }
        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);
            }
        }
Example #27
0
        public void ShapefileDataTest()
        {
            var tempFolder        = Path.GetTempPath();
            var tempFilename      = Path.Combine(tempFolder, "ShapefileDataTest.shp");
            var esriShapefilePath = @"C:\dev\MapWinGIS\unittests\MapWinGISTests\Testdata\Issues\MWGIS-48-68\EsriShapefile.shp";

            Helper.DeleteShapefile(tempFilename);

            bool result;
            // Create shapefile
            var sf = new Shapefile {
                GlobalCallback = this
            };

            try
            {
                result = sf.CreateNewWithShapeID(tempFilename, ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create shapefile");

                Assert.IsTrue(sf.EditingShapes, "Shapefile is not in edit shapes mode");
                Assert.IsTrue(sf.EditingTable, "Shapefile is not in edit table mode");

                // Add fields of each data type:
                var fieldIndex = sf.EditAddField("intField", FieldType.INTEGER_FIELD, 0, 10);
                Assert.AreEqual(1, fieldIndex, "Could not add Integer field");
                var width = sf.Field[fieldIndex].Width;
                Assert.AreEqual(9, width, "Integer field did not shrink to 9 digits");
                fieldIndex = sf.EditAddField("dateField", FieldType.DATE_FIELD, 0, 6);
                Assert.AreEqual(2, fieldIndex, "Could not add Date field");
                width = sf.Field[fieldIndex].Width;
                Assert.AreEqual(8, width, "Date field did not expand to 8 digits");
                fieldIndex = sf.EditAddField("boolField", FieldType.BOOLEAN_FIELD, 0, 3);
                Assert.AreEqual(3, fieldIndex, "Could not add Boolean field");
                width = sf.Field[fieldIndex].Width;
                Assert.AreEqual(1, width, "Boolean field did not shrink to 1 character");
                //
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                result = sf.Save();
                Assert.IsTrue(result, "Could not save shapefile");
                Assert.AreEqual(fieldIndex + 1, sf.NumFields, "Number of fields are incorrect");

                // Create shape:
                var shp = new Shape();
                result = shp.Create(ShpfileType.SHP_POINT);
                Assert.IsTrue(result, "Could not create point shape");
                var idx = sf.EditAddShape(shp);
                // Add data:
                result = sf.EditCellValue(sf.FieldIndexByName["intField"], idx, 99);
                Assert.IsTrue(result, "Could not edit intField");
                DateTime dt = System.DateTime.Now;
                result = sf.EditCellValue(sf.FieldIndexByName["dateField"], idx, dt);
                Assert.IsTrue(result, "Could not edit dateField");
                result = sf.EditCellValue(sf.FieldIndexByName["boolField"], idx, true);
                Assert.IsTrue(result, "Could not edit boolField");

                result = sf.StopEditingShapes();
                Assert.IsTrue(result, "Could not stop editing shapefile");

                // Read back data:
                for (idx = 0; idx < sf.NumShapes; idx++)
                {
                    int iField = (int)sf.CellValue[sf.FieldIndexByName["intField"], idx];
                    Assert.AreEqual(iField, 99, "intField value of 99 was not returned");
                    DateTime dField = (DateTime)sf.CellValue[sf.FieldIndexByName["dateField"], idx];
                    Assert.IsTrue(DateTime.Now.DayOfYear.Equals(((DateTime)dField).DayOfYear), "dateField value of Now was not returned");
                    bool bField = (bool)sf.CellValue[sf.FieldIndexByName["boolField"], idx];
                    Assert.AreEqual(bField, true, "boolField value of True was not returned");
                }
            }
            finally
            {
                // Close the shapefile:
                result = sf.Close();
                Assert.IsTrue(result, "Could not close shapefile");
            }

            // although the default setting, indicate intent to interpret Y/N OGR String fields as Boolean
            GlobalSettings gs = new GlobalSettings();

            gs.OgrInterpretYNStringAsBoolean = true;  // setting to false results in exception reading boolField below

            // open as OGRLayer
            OgrDatasource _datasource = new OgrDatasource();

            _datasource.GlobalCallback = this;

            if (_datasource.Open(tempFilename)) // "ESRI Shapefile:" +
            {
                // read layer through OGR library
                IOgrLayer ogrLayer = _datasource.GetLayer(0);
                sf = ogrLayer.GetBuffer();
                for (int idx = 0; idx < sf.NumShapes; idx++)
                {
                    int iField = (int)sf.CellValue[sf.FieldIndexByName["intField"], idx];
                    Assert.AreEqual(iField, 99, "intField value of 99 was not returned");
                    DateTime dField = (DateTime)sf.CellValue[sf.FieldIndexByName["dateField"], idx];
                    Assert.IsTrue(DateTime.Now.DayOfYear.Equals(((DateTime)dField).DayOfYear), "dateField value of Now was not returned");
                    bool bField = (bool)sf.CellValue[sf.FieldIndexByName["boolField"], idx];
                    Assert.AreEqual(bField, true, "boolField value of True was not returned");
                }
                sf.Close();
            }

            // open and read a Shapefile created by ESRI MapObjects, including a Boolean and Date field
            // table has a Boolean 'Inspected' field, and a Date 'InspDate' field
            Assert.IsTrue(sf.Open(esriShapefilePath, this));
            for (int fld = 0; fld < sf.NumFields; fld++)
            {
                Console.WriteLine(string.Format("Field({0}): Name = '{1}', Fieldtype = {2}", fld, sf.Field[fld].Name, sf.Field[fld].Type));
            }
            for (int idx = 0; idx < sf.NumShapes; idx++)
            {
                // read 'Inspected' value as object
                object inspected = sf.CellValue[sf.FieldIndexByName["Inspected"], idx];
                // verify that it's a bool
                Assert.IsTrue(inspected is bool);
                // watch for Inspected rows (there aren't many)
                if ((bool)inspected == true)
                {
                    // read 'InspDate' value as object
                    object dt = sf.CellValue[sf.FieldIndexByName["InspDate"], idx];
                    // verify that it's a Date
                    Assert.IsTrue(dt is DateTime);
                    Console.WriteLine(string.Format("idx = {0}, Inspected = true, Inspection Date = {1}", idx, (DateTime)dt));
                }
            }
            sf.Close();
        }
Example #28
0
        /// <summary>
        /// add the MBR of a target area as a new map layer
        /// </summary>
        /// <param name="moveMapToMBRCenter"></param>
        public void AddMBRLayer(TargetArea targetArea, bool moveMapToMBRCenter = false)
        {
            var sf = new Shapefile();

            if (sf.CreateNew("", ShpfileType.SHP_POLYGON))
            {
                GeoProjection gp = new GeoProjection();
                gp.SetWgs84();
                sf.GeoProjection = gp;

                int ifldTargetArea = sf.EditAddField("Target area", FieldType.STRING_FIELD, 1, 30);
                int ifldyMax       = sf.EditAddField("yMax", FieldType.DOUBLE_FIELD, 10, 12);
                int ifldxMin       = sf.EditAddField("xMin", FieldType.DOUBLE_FIELD, 10, 12);
                int ifldyMin       = sf.EditAddField("yMin", FieldType.DOUBLE_FIELD, 10, 12);
                int ifldxMax       = sf.EditAddField("xMax", FieldType.DOUBLE_FIELD, 10, 12);
                int ifldWidth      = sf.EditAddField("Width", FieldType.DOUBLE_FIELD, 10, 12);
                int ifldHeight     = sf.EditAddField("Height", FieldType.DOUBLE_FIELD, 10, 12);
                int ifldArea       = sf.EditAddField("Area", FieldType.DOUBLE_FIELD, 15, 17);
                var ext            = new Extents();
                //ext.SetBounds(FishingGrid.LowerRighttExtent.X,
                //    FishingGrid.LowerRighttExtent.Y,
                //    0,
                //    FishingGrid.UpperLeftExtent.X,
                //    FishingGrid.UpperLeftExtent.Y,
                //    0);
                ext.SetBounds(targetArea.UpperLeftPointLL.X, targetArea.LowerRightPointLL.Y, 0,
                              targetArea.LowerRightPointLL.X, targetArea.UpperLeftPointLL.Y, 0);
                var shp  = ext.ToShape();
                int iShp = sf.EditAddShape(shp);
                if (iShp >= 0)
                {
                    sf.EditCellValue(ifldTargetArea, iShp, targetArea.TargetAreaName);
                    if (sf.Labels.Generate("[Target area]", tkLabelPositioning.lpCenter, true) > 0)
                    {
                        sf.Labels.FontSize     = 13;
                        sf.Labels.FrameVisible = false;
                        sf.Labels.Visible      = true;
                        sf.Labels.FontBold     = true;
                    }

                    sf.EditCellValue(ifldyMax, iShp, ext.yMax);
                    sf.EditCellValue(ifldxMin, iShp, ext.xMin);
                    sf.EditCellValue(ifldyMin, iShp, ext.yMin);
                    sf.EditCellValue(ifldxMax, iShp, ext.xMax);

                    sf.EditCellValue(ifldWidth, iShp, targetArea.Width);

                    sf.EditCellValue(ifldHeight, iShp, targetArea.Height);

                    sf.EditCellValue(ifldArea, iShp, targetArea.Area);

                    sf.DefaultDrawingOptions.FillVisible = false;
                    sf.DefaultDrawingOptions.LineColor   = new Utils().ColorByName(tkMapColor.Blue);
                    sf.DefaultDrawingOptions.LineWidth   = 2;
                    AddLayer(sf, "MBR", true, true);
                    if (moveMapToMBRCenter)
                    {
                        ext = MapControl.Extents;
                        ext.MoveTo(sf.Extents.Center.x, sf.Extents.Center.y);
                        MapControl.Extents = ext;
                    }
                }
            }
        }
Example #29
0
        // Missing data [TestMethod, Timeout(5 * 60 * 1000)]
        public void ClipPolygon()
        {
            var settings = new GlobalSettings {
                OgrShareConnection = true
            };
            const string folder = @"D:\dev\GIS-Data\Issues\ClipGridWithPolygon\";

            // Create new in-memory shapefile:
            var sf     = new Shapefile();
            var retVal = sf.CreateNewWithShapeID("", ShpfileType.SHP_POLYGON);

            Assert.IsTrue(retVal, "Could not CreateNewWithShapeID: " + sf.ErrorMsg[sf.LastErrorCode]);

            // Assign projection:
            var projection = new GeoProjection();

            retVal = projection.ImportFromEPSG(4326);
            Assert.IsTrue(retVal, "Could not ImportFromEPSG(4326): " + projection.ErrorMsg[projection.LastErrorCode]);
            sf.GeoProjection = projection;

            // Create shape:
            var shp = new Shape();

            retVal = shp.Create(ShpfileType.SHP_POLYGON);
            Assert.IsTrue(retVal, "Could not shp.Create: " + shp.ErrorMsg[shp.LastErrorCode]);

            // Add point of polygon:
            var numPoints = 0;

            shp.InsertPoint(new Point {
                y = 38.25853, x = 15.7033983
            }, ref numPoints);
            shp.InsertPoint(new Point {
                y = 38.248108, x = 15.7033983
            }, ref numPoints);
            shp.InsertPoint(new Point {
                y = 38.248108, x = 15.7245293
            }, ref numPoints);
            shp.InsertPoint(new Point {
                y = 38.25853, x = 15.7245293
            }, ref numPoints);
            // Make sure the polygon is closed by adding the first point as last:
            shp.InsertPoint(new Point {
                y = 38.25853, x = 15.7033983
            }, ref numPoints);
            Assert.IsTrue(shp.IsValid, "Shape is invalid: " + shp.IsValidReason);

            // Add shape to shapefile:
            sf.EditAddShape(shp);

            // Save to file:
            Helper.SaveAsShapefile(sf, Path.Combine(folder, "ClippingArea-4326.shp"));

            // Clip grid, using Utils.ClipGridWithPolygon fails on the LandSat data, probably because it is in UInt16.
            var input = Path.Combine(folder, "LC08_L1TP_188033_20170919_20170920_01_RT_B4.TIF");

            Assert.IsTrue(File.Exists(input), "Input file does not exists");
            var output = Path.Combine(folder, "clipped.tif");

            if (File.Exists(output))
            {
                File.Delete(output);
            }
            var cutline = Path.Combine(folder, "ClippingArea-4326.shp");

            Assert.IsTrue(File.Exists(cutline), "Cutline file does not exists");

            var options = new[]
            {
                "-overwrite",
                "-crop_to_cutline",
                "-cutline", cutline
            };

            retVal = _gdalUtils.GdalRasterWarp(input, output, options);
            Assert.IsTrue(retVal, "Could not ClipGridWithPolygon: " + _gdalUtils.ErrorMsg[_gdalUtils.LastErrorCode] + " Detailed error: " + _gdalUtils.DetailedErrorMsg);
            Assert.IsTrue(File.Exists(output), "Output file does not exists");
            Debug.WriteLine(output);
        }
Example #30
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();
        }