Beispiel #1
0
        // <summary>
        // This function creates a number of parallel polylines (segments)
        // </summary>
        private Shapefile CreateLines()
        {
            Shapefile sf = new Shapefile();

            sf.CreateNew("", ShpfileType.SHP_POLYLINE);

            int width = 500;
            int step  = 50;

            for (int i = 0; i < 3; i++)
            {
                Shape shp = new Shape();
                shp.Create(ShpfileType.SHP_POLYLINE);

                Point pnt = new Point();
                pnt.x = 0;
                pnt.y = i * step;
                int index = shp.numPoints;
                shp.InsertPoint(pnt, ref index);

                pnt   = new Point();
                pnt.x = width;
                pnt.y = i * step;
                index = shp.numPoints;
                shp.InsertPoint(pnt, ref index);

                index = sf.NumShapes;
                sf.EditInsertShape(shp, ref index);
            }
            return(sf);
        }
Beispiel #2
0
        public classDrawLine(AxMap map)
        {
            sf = new Shapefile();
            sf.CreateNew("", ShpfileType.SHP_POLYLINE);

            this.map = map;
        }
Beispiel #3
0
        private void CreateShape(string path, DataTable dataTable)
        {
            Shapefile myShapefile;

            try
            {
                myShapefile = new Shapefile();
                string fileName     = Path.GetFileNameWithoutExtension(txtBox_excel.Text);
                string shapeilePath = Path.GetDirectoryName(path) + "\\" + fileName + ".shp";

                Directory.CreateDirectory(Path.GetDirectoryName(shapeilePath));

                myShapefile.CreateNew(shapeilePath, ShpfileType.SHP_POINT);
                //Create new field
                MapWinGIS.Field myField = new Field();
                //Set the field properties
                myField.Name  = "ID";
                myField.Type  = FieldType.INTEGER_FIELD;
                myField.Width = 10;
                //Add the filed for the shapefile table
                int intFieldIndex = 1;
                myShapefile.EditInsertField(myField, ref intFieldIndex, null);
                int myCounter    = 0;
                int myShapeIndex = 0;

                //First Create header
                CreateHeader(dataTable.Columns, myShapefile);
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    MapWinGIS.Shape myShape = new Shape();
                    myShape.Create(ShpfileType.SHP_POINT);
                    MapWinGIS.Point myPoint = new MapWinGIS.Point();
                    myPoint.x = Convert.ToDouble(dataTable.Rows[i][x_Index]);
                    myPoint.y = Convert.ToDouble(dataTable.Rows[i][y_Index]);
                    object fld_Value    = dataTable.Rows[i][0];
                    int    myPointIndex = 0;
                    myShape.InsertPoint(myPoint, ref myPointIndex);
                    myShapefile.EditInsertShape(myShape, ref myShapeIndex);
                    myShapefile.EditCellValue(0, myShapeIndex, fld_Value);
                    CreatePointData(dataTable, myShapefile, myShapeIndex, i);
                    myShapeIndex++;
                    myCounter++;
                }
                GeoProjection proj = new GeoProjection();
                // EPSG code
                proj.ImportFromEPSG(4326);  // WGS84

                myShapefile.GeoProjection = proj;
                myShapefile.StopEditingShapes(true, true, null);
                myShapefile.Close();
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #4
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);
        }
Beispiel #5
0
        public void RemoveLayer()
        {
            if (layerHandle != -1)
            {
                map.RemoveLayer(layerHandle);

                sf = new Shapefile();
                sf.CreateNew("", ShpfileType.SHP_POLYLINE);
                layerHandle = -1;
            }
        }
        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);
        }
Beispiel #7
0
 /// <summary>
 /// Sets up the polyline shapefile that makes the graticule
 /// </summary>
 private void SetupShapefile()
 {
     _sfGraticule = new Shapefile();
     if (_sfGraticule.CreateNew("", ShpfileType.SHP_POLYLINE))
     {
         _ifldPart  = _sfGraticule.EditAddField("Part", FieldType.STRING_FIELD, 1, 25);
         _ifldLabel = _sfGraticule.EditAddField("Label", FieldType.STRING_FIELD, 1, 25);
         _ifldSide  = _sfGraticule.EditAddField("Side", FieldType.STRING_FIELD, 1, 1);
         _sfGraticule.GeoProjection = _geoProjection;
         GraticuleLoaded?.Invoke(this, EventArgs.Empty);
     }
 }
Beispiel #8
0
        public static void Main(string[] args)
        {
            //Create new shapefile
            Shapefile myShapefile = new Shapefile();

            //Define the path of the new shapefile and geometry type
            myShapefile.CreateNew(@"D:\GISLesson04\road.shp", ShpfileType.SHP_POINT);
            //Create new field
            MapWinGIS.Field myField = new Field();
            //Set the field properties
            myField.Name  = "ID";
            myField.Type  = FieldType.INTEGER_FIELD;
            myField.Width = 10;
            //Add the filed for the shapefile table
            int intFieldIndex = 0;

            myShapefile.EditInsertField(myField, ref intFieldIndex, null);

            int    myCounter    = 0;
            int    myShapeIndex = 0;
            string myLine;

            // Read the file and display it line by line.
            System.IO.StreamReader myFile =
                new System.IO.StreamReader(@"D:\GISLesson04\road.csv");
            // Using while loop to read csv file line by line
            while ((myLine = myFile.ReadLine()) != null)
            {
                if (myCounter > 0)
                {
                    MapWinGIS.Shape myShape = new Shape();
                    myShape.Create(ShpfileType.SHP_POINT);
                    MapWinGIS.Point myPoint = new Point();
                    myPoint.x = GetX(myLine);
                    myPoint.y = GetY(myLine);
                    int myPointIndex = 0;
                    myShape.InsertPoint(myPoint, ref myPointIndex);
                    myShapefile.EditInsertShape(myShape, ref myShapeIndex);
                    myShapeIndex++;
                }

                myCounter++;
            }
            myShapefile.StopEditingShapes(true, true, null);
            myFile.Close();


            Console.ReadKey();
        }
Beispiel #9
0
        /// <summary>
        /// Opens ESRI shapefile datasource, reads it into memory breaks any connection with the source.
        /// </summary>
        public static FeatureSet OpenAsInMemoryDatasource(string filename)
        {
            var sf = new Shapefile();

            sf.CreateNew(string.Empty, ShpfileType.SHP_POLYGON);

            // reading projection
            string prjFilename = PathHelper.GetFullPathWithoutExtension(filename) + ".prj";

            if (File.Exists(prjFilename))
            {
                sf.GeoProjection.ReadFromFile(prjFilename);
            }

            return(sf.LoadDataFrom(filename) ? new FeatureSet(sf) : null);
        }
Beispiel #10
0
        /// <summary>
        /// Creates featureset with the same projection and set of fields, but differnt geometry type.
        /// </summary>
        public IFeatureSet Clone(GeometryType newType, ZValueType zValue = ZValueType.None)
        {
            var sf        = new Shapefile();
            var shapeType = GeometryHelper.GeometryType2ShpType(newType, zValue);

            sf.CreateNew(string.Empty, shapeType);

            sf.GeoProjection.CopyFrom(_shapefile.GeoProjection);

            var fs = new FeatureSet(sf);

            foreach (var fld in Fields)
            {
                fs.Fields.Add(fld.Clone());
            }

            return(fs);
        }
Beispiel #11
0
        /// <summary>
        /// Creates a new in-memory FeatureSet not bound to any datasource.
        /// </summary>
        public FeatureSet(GeometryType geomType, ZValueType zValue = ZValueType.None, bool addShapeIdField = true)
        {
            if (geomType == GeometryType.None)
            {
                throw new ArgumentException("Invalid geometry type.");
            }

            var shpType = GeometryHelper.GeometryType2ShpType(geomType, zValue);

            _shapefile = new Shapefile();

            if (!addShapeIdField)
            {
                _shapefile.CreateNew("", shpType);
            }
            else
            {
                _shapefile.CreateNewWithShapeID("", shpType);
            }
        }
        /// <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);
        }
Beispiel #13
0
        /// <summary>
        /// Creates a new disk-based shapefile and open it as new feature set.
        /// </summary>
        /// <returns>Feature set for newly created shapefile.</returns>
        public static IFeatureSet CreateShapefile(string filename, GeometryType geomType,
                                                  ZValueType zValue = ZValueType.None)
        {
            if (geomType == GeometryType.None)
            {
                throw new ArgumentException("Invalid geometry type.");
            }

            var shpType = GeometryHelper.GeometryType2ShpType(geomType, zValue);

            var sf = new Shapefile();

            if (!sf.CreateNew(filename, shpType))
            {
                throw new ApplicationException("Failed to create shapefile: " + sf.ErrorMessage());
            }

            var fs = new FeatureSet(sf);

            return(fs);
        }
Beispiel #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;
        }
Beispiel #15
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);
        }
Beispiel #16
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;
                    }
                }
            }
        }
        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);
        }
Beispiel #18
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);
        }
Beispiel #19
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);
        }
Beispiel #20
0
        /// <summary>
        /// Get the closest point
        /// </summary>
        /// <param name="inputShapefile">
        /// The input shapefile.
        /// </param>
        /// <param name="searchShapefile">
        /// The search shapefile.
        /// </param>
        /// <param name="theForm">
        /// The form.
        /// </param>
        /// <returns>
        /// True on success
        /// </returns>
        private static bool ClosestPoint(string inputShapefile, string searchShapefile, Form1 theForm)
        {
            try
            {
                // Check inputs:
                if (!Helper.CheckShapefileLocation(inputShapefile, theForm))
                {
                    return(false);
                }

                if (!Helper.CheckShapefileLocation(searchShapefile, theForm))
                {
                    return(false);
                }

                // Open the sf:
                var inputSf = Fileformats.OpenShapefile(inputShapefile, theForm);
                if (inputSf == null)
                {
                    theForm.Error(string.Empty, "Opening input shapefile was unsuccessful");
                    return(false);
                }

                var searchSf = Fileformats.OpenShapefile(searchShapefile, theForm);
                if (searchSf == null)
                {
                    theForm.Error(string.Empty, "Opening search shapefile was unsuccessful");
                    return(false);
                }

                // Create resulting shapefile:
                var linksSf = new Shapefile {
                    GlobalCallback = theForm
                };
                linksSf.CreateNew(string.Empty, ShpfileType.SHP_POLYLINE);
                var fieldIndex = linksSf.EditAddField("FoundId", FieldType.INTEGER_FIELD, 0, 0);

                // Get a random shape
                var index            = new Random().Next(inputSf.NumShapes - 1);
                var randomInputShape = inputSf.Shape[index];

                // Select the shape:
                var utils = new Utils {
                    GlobalCallback = theForm
                };
                inputSf.SelectionColor       = utils.ColorByName(tkMapColor.Yellow);
                inputSf.ShapeSelected[index] = true;

                // Load the files:
                MyAxMap.RemoveAllLayers();
                MyAxMap.AddLayer(searchSf, true);
                MyAxMap.AddLayer(inputSf, true);

                // To store the lenght and index:
                var minLength    = double.MaxValue;
                var closestIndex = -1;

                // Search around the location until at least on shape is found.
                // To optimize searching make sure a spatial index is used:
                if (!searchSf.HasSpatialIndex)
                {
                    searchSf.CreateSpatialIndex(searchSf.Filename);
                }

                searchSf.UseSpatialIndex = true;

                // create start search box:
                var searchExtent = randomInputShape.Extents;

                // Make the start tolerance depending on the projection:
                var tolerance = 2D;
                if (searchSf.GeoProjection.IsGeographic)
                {
                    tolerance = 0.01;
                }

                var    foundShapeId = -1;
                object results      = null;

                // Search in increasing circles:
                var notFound = true;

                // TODO: Add continious loop prevention
                while (notFound)
                {
                    if (searchSf.SelectShapes(searchExtent, tolerance, SelectMode.INTERSECTION, ref results))
                    {
                        var shapeIds = results as int[];

                        // Use the first one:
                        if (shapeIds != null)
                        {
                            foreach (var shapeId in shapeIds)
                            {
                                foundShapeId = shapeId;

                                // When the shapes intersect you get wrong values:
                                var intersects = randomInputShape.Intersects(searchSf.Shape[foundShapeId]);

                                if (intersects)
                                {
                                    continue;
                                }

                                // stop searching:
                                notFound = false;
                                break;
                            }
                        }
                    }

                    // increase tolerance:
                    tolerance = tolerance + tolerance;
                }

                if (foundShapeId == -1)
                {
                    theForm.Error(string.Empty, "Error! Could not find any shapes");
                    return(false);
                }

                // Select the found shape:
                searchSf.SelectionColor = utils.ColorByName(tkMapColor.Red);
                searchSf.ShapeSelected[foundShapeId] = true;

                var link = randomInputShape.ClosestPoints(searchSf.Shape[foundShapeId]);
                if (link != null && link.numPoints > 1)
                {
                    if (link.IsValid)
                    {
                        var shapeId = linksSf.EditAddShape(link);
                        linksSf.EditCellValue(fieldIndex, shapeId, foundShapeId);
                        if (minLength > link.Length)
                        {
                            minLength    = link.Length;
                            closestIndex = foundShapeId;
                        }
                    }
                    else
                    {
                        theForm.Error(string.Empty, "Found link line is invalid: " + link.IsValidReason);
                        return(false);
                    }
                }
                else
                {
                    theForm.Error(string.Empty, "pointShp.ClosestPoints() could not find anything");
                    return(false);
                }

                linksSf.DefaultDrawingOptions.LineColor = utils.ColorByName(tkMapColor.Black);
                linksSf.DefaultDrawingOptions.LineWidth = 2;
                MyAxMap.AddLayer(linksSf, true);
                linksSf.GenerateLabels(fieldIndex, tkLabelPositioning.lpMiddleSegment);
                linksSf.Labels.OffsetX = 10;
                linksSf.Labels.OffsetY = 10;

                MyAxMap.ZoomToMaxExtents();

                // Wait to show the map:
                Application.DoEvents();

                theForm.Progress(
                    string.Format(
                        "The closest shape is {0}, has a value of {1} and a length of {2}",
                        closestIndex,
                        searchSf.CellValue[0, closestIndex],
                        minLength));

                // Save result:
                var newFilename = inputSf.Filename.Replace(".shp", "-Closest.shp");
                Helper.DeleteShapefile(newFilename);
                if (!linksSf.SaveAs(newFilename, theForm))
                {
                    return(false);
                }

                theForm.Progress(string.Empty, 100, "The resulting shapefile has been saved as " + newFilename);
            }
            catch (Exception exception)
            {
                theForm.Error(string.Empty, "Exception: " + exception.Message);
                return(false);
            }

            return(true);
        }
        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 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);
        }