Exemple #1
0
        private void writePx(MapWinGIS.Grid gr, MapWinGIS.GridDataType grType,
                             GridPixel pix, object val, MapWinGIS.ICallback cback)
        {
            switch (grType)
            {
            case GridDataType.ShortDataType:
                short v1 = Convert.ToInt16(val);
                gr.set_Value(pix.col, pix.row, v1);
                break;

            case GridDataType.LongDataType:
                int v2 = Convert.ToInt32(val);
                gr.set_Value(pix.col, pix.row, v2);
                break;

            case GridDataType.FloatDataType:
                float v3 = Convert.ToSingle(val);
                gr.set_Value(pix.col, pix.row, v3);
                break;

            case GridDataType.DoubleDataType:
                double v4 = Convert.ToDouble(val);
                gr.set_Value(pix.col, pix.row, v4);
                break;

            default:
                reportError("the grid data type " + grType.ToString() + "is not supported.", cback);
                break;
            }
        }
Exemple #2
0
        /// <summary>
        /// Adds boxes from grid row number rowNum of length length
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="rowNum"></param>
        /// <param name="length"></param>
        public void addGridRow(MapWinGIS.Grid grid, int rowNum, int length)
        {
            GridRow gr = new GridRow(grid, rowNum);

            addRow(new Row(gr.Row), rowNum, length, (int)((double)grid.Header.NodataValue));
            if (gr.readError)
            {
                lastError = "Grid does not seem to be an integer grid";
            }
        }
        /// <summary>
        /// Reprojects a grid
        /// </summary>
        /// <param name="grid">Grid object to reproject</param>
        /// <param name="inPlace">Whether reprojected file should replace the initial one</param>
        /// <returns>True on success and false otherwise</returns>
        public static TestingResult Reproject(MapWinGIS.Grid grid, out MapWinGIS.Grid gridNew, MapWinGIS.GeoProjection projection, frmTesterReport report)
        {
            string sourcePrj    = grid.Header.GeoProjection.ExportToProj4();
            string targetPrj    = projection.ExportToProj4();
            string origFilename = grid.Filename;

            MapWinGIS.ICallback callback = grid.GlobalCallback;
            gridNew = null;

            LayerSource obj    = new LayerSource(grid);
            LayerSource objNew = null;

            if (CoordinateTransformation.SeekSubstituteFile(obj, projection, out objNew))
            {
                gridNew = objNew.Grid;
                return(TestingResult.Substituted);
            }

            string newFilename = CoordinateTransformation.FilenameWithProjectionSuffix(origFilename, grid.Header.GeoProjection, projection);

            newFilename = CoordinateTransformation.GetSafeNewName(newFilename);

            // setting callback
            if (report != null)
            {
                if (!report.Visible)
                {
                    report.InitProgress(projection);
                }

                report.ShowFilename(grid.Filename);
            }

            bool result = MapWinGIS.GeoProcess.SpatialReference.ProjectGrid(ref sourcePrj, ref targetPrj, ref origFilename, ref newFilename, true, report);

            if (report != null)
            {
                report.ClearFilename();
            }

            if (!result)
            {
                return(TestingResult.Error);
            }

            // TODO: no need to open it if only a name is supposed to be returned
            gridNew = new MapWinGIS.Grid();
            gridNew.Open(newFilename, MapWinGIS.GridDataType.UnknownDataType, false, MapWinGIS.GridFileType.UseExtension, callback);
            gridNew.AssignNewProjection(projection.ExportToProj4());

            return(TestingResult.Ok);
        }
Exemple #4
0
        public void AddTest12()
        {
            MapWindow.Interfaces.Layers target = new Layers(); // TODO: Initialize to an appropriate value
            MapWinGIS.Grid GridObject          = null;         // TODO: Initialize to an appropriate value
            MapWinGIS.Grid GridObjectExpected  = null;         // TODO: Initialize to an appropriate value
            string         LayerName           = string.Empty; // TODO: Initialize to an appropriate value

            MapWindow.Interfaces.Layer expected = null;        // TODO: Initialize to an appropriate value
            MapWindow.Interfaces.Layer actual;
            actual = target.Add(ref GridObject, LayerName);
            Assert.AreEqual(GridObjectExpected, GridObject);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemple #5
0
        private bool Multipoint2Grid(MapWinGIS.Shapefile MultipointSf, int FldID, MapWinGIS.Grid Newgrd,
                                     MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback)
        {
            //count the number of shapes
            int s, p;

            MapWinGIS.Shape shp;
            MapWinGIS.Point pt;
            ArrayList       pixels = new ArrayList();
            object          val;
            GridPixel       px;
            int             nShps    = MultipointSf.NumShapes;
            int             nPts     = 0;
            int             perc     = 1;
            int             shpsPerc = NumPercentShapes(perc, nShps); //percent of progress

            for (s = 0; s < nShps; ++s)
            {
                //get the shape
                shp = MultipointSf.get_Shape(s);

                //exclude shapes which are completely outside of the grid extents
                if (!IsGridContainsShape(shp, header))
                {
                    continue;
                }

                //get the shape's value
                val = GetCellValue(MultipointSf, FldID, s, header.NodataValue);

                nPts = shp.numPoints;
                for (p = 0; p < nPts; ++p)
                {
                    //write pixel values
                    pt = shp.get_Point(p);
                    Newgrd.ProjToCell(pt.x, pt.y, out px.col, out px.row);
                    pixels.Add(px);
                    writePxList(Newgrd, grType, pixels, val, cback);
                }

                //report the progress
                if (s >= shpsPerc)
                {
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                }
            }
            return(true);
        }
Exemple #6
0
        /// <summary>
        /// convert point shapefile to grid
        /// </summary>
        private bool Point2Grid(MapWinGIS.Shapefile PointSf, int FldID, MapWinGIS.Grid Newgrd,
                                MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback)
        {
            //count the number of shapes
            int s;

            MapWinGIS.Shape shp;
            MapWinGIS.Point pt = new MapWinGIS.Point();
            object          val;
            GridPixel       px;
            int             nShps    = PointSf.NumShapes;
            int             perc     = 1;
            int             shpsPerc = NumPercentShapes(perc, nShps); //percent of progress

            for (s = 0; s < nShps; ++s)
            {
                //get the point
                shp = PointSf.get_Shape(s);

                //exclude shapes which are completely outside of the grid extents
                if (!IsGridContainsShape(shp, header))
                {
                    continue;
                }

                if (shp.numPoints > 0)
                {
                    pt = shp.get_Point(0);
                    if (pt != null)
                    {
                        //return the shape's value and write the pixel
                        val = GetCellValue(PointSf, FldID, s, header.NodataValue);
                        Newgrd.ProjToCell(pt.x, pt.y, out px.col, out px.row);
                        writePx(Newgrd, grType, px, val, cback);
                    }
                }

                //report the progress
                if (s >= shpsPerc)
                {
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                }
            }
            return(true);
        }
Exemple #7
0
        /// <summary>
        /// writes the pixel values from arrayList to grid
        /// </summary>
        /// <param name="gr"></param>
        /// <param name="pxList"></param>
        /// <param name="val"></param>
        /// <param name="cback"></param>
        private void writePxList(MapWinGIS.Grid gr, MapWinGIS.GridDataType grType,
                                 System.Collections.ArrayList pxList, object val, MapWinGIS.ICallback cback)
        {
            switch (grType)
            {
            case GridDataType.ShortDataType:
                short v1 = Convert.ToInt16(val);
                foreach (GridPixel pix in pxList)
                {
                    gr.set_Value(pix.col, pix.row, v1);
                }
                break;

            case GridDataType.LongDataType:
                int v2 = Convert.ToInt32(val);
                foreach (GridPixel pix in pxList)
                {
                    gr.set_Value(pix.col, pix.row, v2);
                }
                break;

            case GridDataType.FloatDataType:
                float v3 = Convert.ToSingle(val);
                foreach (GridPixel pix in pxList)
                {
                    gr.set_Value(pix.col, pix.row, v3);
                }
                break;

            case GridDataType.DoubleDataType:
                double v4 = Convert.ToDouble(val);
                foreach (GridPixel pix in pxList)
                {
                    gr.set_Value(pix.col, pix.row, v4);
                }
                break;

            default:
                reportError("the grid data type " + grType.ToString() + "is not supported.", cback);
                break;
            }

            pxList.Clear();
        }
Exemple #8
0
        /// <summary>
        /// populate all the grid cells between two consecutive intersections with shape's value
        /// </summary>
        private bool ScanLine2(System.Collections.ArrayList vettore, double xref,
                               ref System.Collections.ArrayList pixels, ref MapWinGIS.Grid gr, MapWinGIS.GridHeader header,
                               object value, MapWinGIS.ICallback cback)
        {
            bool   result = false;
            bool   control;
            double yll, ystart, yend, ycellstart;
            double pxsize;
            int    c, r, v;

            r = 0;
            GridPixel curPx;

            control = false;
            yll     = header.YllCenter;
            pxsize  = header.dX;

            ystart = 0;
            for (v = vettore.Count - 1; v >= 0; --v)
            {
                if (control == false)
                {
                    ystart  = (double)vettore[v];
                    control = true;
                }
                else
                {
                    yend       = (double)vettore[v];
                    ycellstart = FirstLineXY(ystart, yll, pxsize, -1);

                    do
                    {
                        gr.ProjToCell(xref, ycellstart, out c, out r);
                        curPx.col = c;
                        curPx.row = r;
                        pixels.Add(curPx);
                        ycellstart = ycellstart - pxsize;
                    }while (ycellstart >= yend);
                    control = false;
                }
            }
            return(result);
        }
        /// <summary>
        /// Reprojects layer of undefined type
        /// </summary>
        /// <param name="filename">Filename of layer to reproject. A changed name will be returned when new file was created</param>
        /// <param name="projection">New projection</param>
        /// <param name="inPlace">Whether new files should be written</param>
        /// <param name="report">A reference to report form</param>
        /// <returns>True on success and false otherwise</returns>
        public static TestingResult ReprojectLayer(LayerSource layer, out LayerSource newLayer, MapWinGIS.GeoProjection projection, frmTesterReport report)
        {
            newLayer = null;
            TestingResult result = TestingResult.Error;

            switch (layer.Type)
            {
            case LayerSourceType.Shapefile:
                MapWinGIS.Shapefile sfNew = null;
                result = CoordinateTransformation.Reproject(layer.Shapefile, out sfNew, projection, report);
                if (sfNew != null)
                {
                    newLayer = new LayerSource(sfNew);
                }
                break;

            case LayerSourceType.Grid:
                MapWinGIS.Grid gridNew = null;
                result = CoordinateTransformation.Reproject(layer.Grid, out gridNew, projection, report);
                if (gridNew != null)
                {
                    newLayer = new LayerSource(gridNew);
                }
                break;

            case LayerSourceType.Image:
                MapWinGIS.Image imageNew = null;
                result = CoordinateTransformation.Reproject(layer.Image, out imageNew, projection, report);
                if (imageNew != null)
                {
                    newLayer = new LayerSource(imageNew);
                }
                break;

            default:
                System.Diagnostics.Debug.Print("Coordinate transformation: unsupported interface");
                break;
            }
            return(result);
        }
Exemple #10
0
/// <summary>
        /// converts a Line shapefile to grid using Bresenham algorithm
        /// </summary>
        /// <param name="PolySf">Polygon shapefile object</param>
        /// <param name="FldID">Field index</param>
        /// <param name="Newgrd">New grid object</param>
        /// <param name="header">Grid header</param>
        /// <param name="nodatavalue"></param>
        /// <param name="cback">optional, for reporting progress</param>
        /// <returns>true if successful</returns>

        private bool Line2Grid(MapWinGIS.Shapefile LineSf, int FldID, MapWinGIS.Grid Newgrd,
                               MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback)
        {
            int numParts, numPoints;
            int curPartStart, curPartEnd, vertexCol, vertexRow, lastCol, lastRow;
            int nShps    = LineSf.NumShapes;
            int perc     = 1;
            int shpsPerc = NumPercentShapes(perc, nShps); //percent of progress
            int s        = 0;                             //shape number
            int p        = 0;                             //part number
            int k        = 0;                             //point number

            MapWinGIS.Shape LineShp = new MapWinGIS.Shape();
            MapWinGIS.Point curPoint;
            //Rasterization ras = new Rasterization(); //rasterization class, contains the code of
            //lineToGrid methods independent on MapWinGIS functions
            ArrayList vertices = new ArrayList(); //list of line vertex points
            ArrayList pixels   = new ArrayList(); //list of calculated pixels on the line
            GridPixel px;

            object val; //the shape's value


            for (s = 0; s < nShps; ++s)
            {
                LineShp   = LineSf.get_Shape(s);
                numParts  = LineShp.NumParts;
                numPoints = LineShp.numPoints;

                //exclude shapes which are completely outside of the grid extents
                if (!IsGridContainsShape(LineShp, header))
                {
                    continue;
                }

                //get the shape's value
                val = GetCellValue(LineSf, FldID, s, header.NodataValue);

                //process each part of the polyline
                curPartStart = 0;
                for (p = 0; p < numParts; ++p)
                {
                    vertices.Clear();
                    pixels.Clear();

                    curPartStart = LineShp.get_Part(p);

                    // check for multi-part lines
                    if (p < numParts - 1)
                    {
                        curPartEnd = LineShp.get_Part(p + 1) - 1;
                    }
                    else
                    {
                        curPartEnd = numPoints - 1;
                    }

                    //go to next part if there's zero points
                    if (numPoints <= 0)
                    {
                        continue;
                    }

                    // add all points of current part to rasterization list
                    // always add the first point of the part (convert its coordinates to
                    // grid row and column)
                    curPoint = LineShp.get_Point(curPartStart);
                    Newgrd.ProjToCell(curPoint.x, curPoint.y,
                                      out vertexCol, out vertexRow);
                    px.col = vertexCol;
                    px.row = vertexRow;
                    vertices.Add(px);
                    lastCol = vertexCol; lastRow = vertexRow;

                    // add all other points with different grid coordinates
                    for (k = curPartStart + 1; k <= curPartEnd; ++k)
                    {
                        // (check if it has a different row or column than the previous point)
                        curPoint = LineShp.get_Point(k);
                        Newgrd.ProjToCell(curPoint.x, curPoint.y,
                                          out vertexCol, out vertexRow);
                        if (vertexCol != lastCol || vertexRow != lastRow)
                        {
                            px.col = vertexCol;
                            px.row = vertexRow;
                            vertices.Add(px);
                            lastCol = vertexCol;
                            lastRow = vertexRow;
                        }
                    }

                    // convert the polyline and write pixels to grid
                    LineBresenham(vertices, pixels);
                    writePxList(Newgrd, grType, pixels, val, cback);
                }

                //report the progress
                if (s >= shpsPerc)
                {
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                }
            }
            return(true);
        }
Exemple #11
0
        /// <summary>
        /// Handles the opening of map layer files from a file open dialog
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public (bool success, string errMsg) FileOpenHandler(string fileName, string layerName = "", bool reproject = false)
        {
            var success = false;
            var errMsg  = "";
            var fm      = new FileManager();

            if (!fm.get_IsSupported(fileName))
            {
                errMsg = "Datasource isn't supported by MapWinGIS";
            }
            else
            {
                var obj = fm.Open(fileName, tkFileOpenStrategy.fosAutoDetect, null);
                if (fm.LastOpenIsSuccess)
                {
                    if (fm.LastOpenStrategy == tkFileOpenStrategy.fosVectorLayer)
                    {
                        var shapefile = obj as Shapefile;
                        success = shapefile != null;
                        if (success)
                        {
                            if (reproject)
                            {
                                int reprojectCount = 0;
                                var sf             = shapefile.Reproject(MapControl.GeoProjection, reprojectCount);
                                if (reprojectCount > 0 || sf.NumShapes > 0)
                                {
                                    shapefile = sf;
                                }
                            }
                            if (AddLayer(shapefile, layerName) < 0)
                            {
                                success = false;
                                errMsg  = "Failed to add layer to map";
                            }
                        }
                    }
                    else if (fm.LastOpenStrategy == tkFileOpenStrategy.fosRgbImage)
                    {
                        var folderPath = Path.GetDirectoryName(fileName);
                        var file       = Path.GetFileNameWithoutExtension(fileName);
                        var ext        = Path.GetExtension(fileName);
                        var prjFile    = $@"{folderPath}\{file}.prj";
                        var worldFile  = $@"{folderPath}\{file}.{WorldfileExtension(ext)}";

                        if (File.Exists(prjFile) || File.Exists(worldFile))
                        {
                            var image = obj as MapWinGIS.Image;
                            success = image != null;
                            if (success)
                            {
                                if (AddLayer(image) < 0)
                                {
                                    success = false;
                                    errMsg  = "Failed to add layer to map";
                                }
                            }
                        }
                        else
                        {
                            errMsg = $"{fileName} does not have a projection or world file";
                        }
                    }
                    else if (fm.LastOpenStrategy == tkFileOpenStrategy.fosDirectGrid ||
                             fm.LastOpenStrategy == tkFileOpenStrategy.fosProxyForGrid)
                    {
                        var grid = new MapWinGIS.Grid();
                        success = grid.Open(fileName, GridDataType.DoubleDataType, false, GridFileType.UseExtension, null);
                        if (success)
                        {
                            AddLayer(grid, Path.GetFileName(fileName), true, true);
                        }
                    }
                }
                else
                {
                    errMsg = "Failed to open datasource: " + fm.get_ErrorMsg(fm.LastErrorCode);
                }
            }
            if (success)
            {
                //save directory to the registry
                RegistryTools.SaveSetting("FAD3", "LastOpenedLayerDirectory", Path.GetDirectoryName(fileName));
            }
            return(success, errMsg);
        }
Exemple #12
0
        /// <summary>
        /// 'Copyright (C) 2008  Enrico Antonio Chiaradia, UNIMI
        ///'This program is free software; you can redistribute it and/or
        ///'modify it under the terms of the GNU General Public License 
        ///'version 2, 1991 as published by the Free Software Foundation.
        ///'This program is distributed in the hope that it will be useful,
        ///'but WITHOUT ANY WARRANTY; without even the implied warranty of
        ///'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        ///'GNU General Public License for more details.
        ///'A copy of the full GNU General Public License is available at:
        ///'http://www.gnu.org/copyleft/gpl.html
        ///'or from:
        ///'The Free Software Foundation, Inc., 59 Temple Place - Suite 330, 
        ///'Boston, MA  02111-1307, USA.
        ///'If you wish to use or incorporate this program (or parts of it) into 
        ///'other software that does not meet the GNU General Public License 
        ///'conditions contact the author to request permission.
        ///'If you have any question or suggestion, please contact the author.
        ///'Enrico A. Chiaradia
        ///'University of Milan
        ///'Ist. di Idraulica Agraria
        ///'via Celoria 2
        ///'20133, Milan, Italy
        ///'email:  [email protected]
        /// </summary>
        /// <param name="sfPath">the name of the shapefile</param>
        /// <param name="resultGridPath">the name of the new grid</param>
        /// <param name="gridFileType">file type of the new grid</param>
        /// <param name="gridDataType">data format of the new grid</param>
        /// <param name="sfValueField">the name of the field that contains data</param>
        /// <param name="resultGridHeader">contains information about dimension of the new grid</param>
        /// <param name="callback">(optional) reports progress and error messages</param>
        /// <returns></returns>
        public bool ShapefileToGrid2(string SfNm, string GrdName,
            MapWinGIS.GridFileType GrdFileType, MapWinGIS.GridDataType GrdDataType,
            string Fldname, MapWinGIS.GridHeader GrdHd,
            MapWinGIS.ICallback cback)
        {
            int i;
            bool flg;
            string projStr;

            //open the shapefile
            MapWinGIS.Shapefile MySf = new MapWinGIS.Shapefile();
            flg = MySf.Open(SfNm, cback);
            if (flg == false)
            {
                reportError("ERROR in opening shapefile: " + SfNm, cback);
                MySf.Close();
                return false;
            }

            //get the handle for the field
            MapWinGIS.Field field;
            int FldId = -1;
            int LayFldNum = MySf.NumFields;

            i = 0;
            for (i = 0; i < LayFldNum; ++i)
            {
                field = MySf.get_Field(i);
                if (field.Name.ToLower() == Fldname.ToLower())
                {
                    FldId = i;
                    break;
                }
            }
            if (FldId < 0)
            {
                reportError("The shapefile " + SfNm + " doesn't have a field " + Fldname, cback);
                MySf.Close();
                return false;
            }

            //copy shapefile projection
            projStr = MySf.Projection;
            if (!MapWinUtility.Strings.IsEmpty(projStr))
            {
                GrdHd.Projection = projStr;
            }

            //create a new grid and a new gridheader
            MapWinGIS.Grid NewGrd = new MapWinGIS.Grid();
            flg = NewGrd.CreateNew(GrdName, GrdHd, GrdDataType, GrdHd.NodataValue, false, GrdFileType, cback);
            if (flg == false)
            {
                reportError("ERROR in grid initialization: " + GrdName, cback);
                NewGrd.Close();
                MySf.Close();
            }

            //verify the type of shapefile and call rasterization function
            MapWinGIS.ShpfileType SfType = new MapWinGIS.ShpfileType();
            SfType = MySf.ShapefileType;
            switch (SfType)
            {
                case ShpfileType.SHP_POLYGON:
                case ShpfileType.SHP_POLYGONM:
                case ShpfileType.SHP_POLYGONZ:
                    flg = Poly2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                    break;
                case ShpfileType.SHP_POLYLINE:
                case ShpfileType.SHP_POLYLINEM:
                case ShpfileType.SHP_POLYLINEZ:
                    flg = Line2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                    break;
                case ShpfileType.SHP_POINT:
                case ShpfileType.SHP_POINTM:
                case ShpfileType.SHP_POINTZ:
                    flg = Point2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                    break;
                case ShpfileType.SHP_MULTIPOINT:
                case ShpfileType.SHP_MULTIPOINTM:
                case ShpfileType.SHP_MULTIPOINTZ:
                    flg = Multipoint2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                    break;
                default:
                    reportError("The shapefile type " + SfType.ToString() + "is not supported.", cback);
                    NewGrd.Close();
                    MySf.Close();
                    flg = false;
                    break;
            }

            //save and close the grid, close shapefile
            NewGrd.Save(GrdName, GrdFileType, cback);
            NewGrd.Close();
            MySf.Close();
            return flg;
        }
Exemple #13
0
        /// <summary>
        /// 'Copyright (C) 2008  Enrico Antonio Chiaradia, UNIMI
        ///'This program is free software; you can redistribute it and/or
        ///'modify it under the terms of the GNU General Public License
        ///'version 2, 1991 as published by the Free Software Foundation.

        ///'This program is distributed in the hope that it will be useful,
        ///'but WITHOUT ANY WARRANTY; without even the implied warranty of
        ///'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        ///'GNU General Public License for more details.

        ///'A copy of the full GNU General Public License is available at:
        ///'http://www.gnu.org/copyleft/gpl.html
        ///'or from:
        ///'The Free Software Foundation, Inc., 59 Temple Place - Suite 330,
        ///'Boston, MA  02111-1307, USA.

        ///'If you wish to use or incorporate this program (or parts of it) into
        ///'other software that does not meet the GNU General Public License
        ///'conditions contact the author to request permission.

        ///'If you have any question or suggestion, please contact the author.

        ///'Enrico A. Chiaradia
        ///'University of Milan
        ///'Ist. di Idraulica Agraria
        ///'via Celoria 2
        ///'20133, Milan, Italy
        ///'email:  [email protected]
        /// </summary>
        /// <param name="sfPath">the name of the shapefile</param>
        /// <param name="resultGridPath">the name of the new grid</param>
        /// <param name="gridFileType">file type of the new grid</param>
        /// <param name="gridDataType">data format of the new grid</param>
        /// <param name="sfValueField">the name of the field that contains data</param>
        /// <param name="resultGridHeader">contains information about dimension of the new grid</param>
        /// <param name="callback">(optional) reports progress and error messages</param>
        /// <returns></returns>
        public bool ShapefileToGrid2(string SfNm, string GrdName,
                                     MapWinGIS.GridFileType GrdFileType, MapWinGIS.GridDataType GrdDataType,
                                     string Fldname, MapWinGIS.GridHeader GrdHd,
                                     MapWinGIS.ICallback cback)
        {
            int    i;
            bool   flg;
            string projStr;

            //open the shapefile
            MapWinGIS.Shapefile MySf = new MapWinGIS.Shapefile();
            flg = MySf.Open(SfNm, cback);
            if (flg == false)
            {
                reportError("ERROR in opening shapefile: " + SfNm, cback);
                MySf.Close();
                return(false);
            }

            //get the handle for the field
            MapWinGIS.Field field;
            int             FldId     = -1;
            int             LayFldNum = MySf.NumFields;

            i = 0;
            for (i = 0; i < LayFldNum; ++i)
            {
                field = MySf.get_Field(i);
                if (field.Name.ToLower() == Fldname.ToLower())
                {
                    FldId = i;
                    break;
                }
            }
            if (FldId < 0)
            {
                reportError("The shapefile " + SfNm + " doesn't have a field " + Fldname, cback);
                MySf.Close();
                return(false);
            }

            //copy shapefile projection
            projStr = MySf.Projection;
            if (!MapWinUtility.Strings.IsEmpty(projStr))
            {
                GrdHd.Projection = projStr;
            }

            //create a new grid and a new gridheader
            MapWinGIS.Grid NewGrd = new MapWinGIS.Grid();
            flg = NewGrd.CreateNew(GrdName, GrdHd, GrdDataType, GrdHd.NodataValue, false, GrdFileType, cback);
            if (flg == false)
            {
                reportError("ERROR in grid initialization: " + GrdName, cback);
                NewGrd.Close();
                MySf.Close();
            }

            //verify the type of shapefile and call rasterization function
            MapWinGIS.ShpfileType SfType = new MapWinGIS.ShpfileType();
            SfType = MySf.ShapefileType;
            switch (SfType)
            {
            case ShpfileType.SHP_POLYGON:
            case ShpfileType.SHP_POLYGONM:
            case ShpfileType.SHP_POLYGONZ:
                flg = Poly2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                break;

            case ShpfileType.SHP_POLYLINE:
            case ShpfileType.SHP_POLYLINEM:
            case ShpfileType.SHP_POLYLINEZ:
                flg = Line2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                break;

            case ShpfileType.SHP_POINT:
            case ShpfileType.SHP_POINTM:
            case ShpfileType.SHP_POINTZ:
                flg = Point2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                break;

            case ShpfileType.SHP_MULTIPOINT:
            case ShpfileType.SHP_MULTIPOINTM:
            case ShpfileType.SHP_MULTIPOINTZ:
                flg = Multipoint2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback);
                break;

            default:
                reportError("The shapefile type " + SfType.ToString() + "is not supported.", cback);
                NewGrd.Close();
                MySf.Close();
                flg = false;
                break;
            }

            //save and close the grid, close shapefile
            NewGrd.Save(GrdName, GrdFileType, cback);
            NewGrd.Close();
            MySf.Close();
            return(flg);
        }
Exemple #14
0
 public int AddLayer(MapWinGIS.Grid grid, bool visible)
 {
     return(base.AddLayer(grid, visible));
 }
Exemple #15
0
        /// <summary>
        /// This function converts a polygon shapefile to grid. It implements the line-scan algorithm.
        /// <param name="PolySf">The polygon shapefile</param>
        /// <param name="FldID">The field index</param>
        /// <param name="Newgrd">File name of the new grid</param>
        /// <param name="header">Header object of the new grid</param>
        /// <param name="writePxDeleg">Delegate function for writing the grid pixels</param>
        /// <param name="nodatavalue">'no data' value</param>
        /// <param name="cback">can be used to report progress (optional)</param>
        /// <returns>true if successful</returns>
        //
        // AUTHOR NAME: Enrico A. Chiaradia
        //       FROM: University of Milan (Italy)
        //     e.mail: [email protected]
        //
        // For details about the line-scan algorithm,
        // please refer to http://www.profc.udec.cl/~gabriel/tutoriales/giswb/vol1/cp3/cp3-6.htm
        //
        // for each shape in PolySf
        // 0) get the shape value (in the shapefile table)
        // 1) load all the borders in a matrix composed by x(startpoint), x(endpoint), slope and share
        // 2) define x of first scan line
        // for each scan lines
        // 3) calculate intersections with polygon border
        // 4) sort intersections from lower Y to the higther
        // 5) convert line space between two consecutive intersection to raster

        private bool Poly2Grid(MapWinGIS.Shapefile PolySf, int FldID, MapWinGIS.Grid Newgrd,
                               MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType,
                               MapWinGIS.ICallback cback)
        {
            double xMin, xMax;
            double x0, x1, x2, y0, y1, y2, m, q;
            int    nShps, nVs, i, s, nP, p, tempn, v, b;
            object val;
            bool   flg;
            bord   brd;                          //struct to keep a border

            System.Collections.ArrayList bordi2; //list of borders
            int perc = 1;                        //percent shapes done
            int shpsPerc;

            MapWinGIS.Shape PolyShp; //the polygon shape

            //count the number of shapes
            nShps    = PolySf.NumShapes;
            shpsPerc = NumPercentShapes(perc, nShps); //percent of progress

            for (s = 0; s < nShps; ++s)
            {
                //for each shape, determine the extent and the number of parts
                i       = 0;
                PolyShp = PolySf.get_Shape(s);
                nP      = PolyShp.NumParts;

                xMin = PolyShp.Extents.xMin;
                //yMin = PolyShp.Extents.yMin;
                xMax = PolyShp.Extents.xMax;
                //yMax = PolyShp.Extents.yMax;

                //exclude shapes which are completely outside of the grid extents
                if (!IsGridContainsShape(PolyShp, header))
                {
                    continue;
                }

                //return the shape's value
                val = GetCellValue(PolySf, FldID, s, header.NodataValue);

                //load polygon borders
                nVs    = PolyShp.numPoints - 1;
                bordi2 = new System.Collections.ArrayList(nVs + 1);

                b     = -1;
                tempn = 0;

                for (p = 0; p < nP; ++p)
                {
                    x0 = PolyShp.get_Point(tempn).x;
                    y0 = PolyShp.get_Point(tempn).y;

                    for (v = tempn; v < nVs; ++v)
                    {
                        x1 = PolyShp.get_Point(v).x;
                        x2 = PolyShp.get_Point(v + 1).x;
                        y1 = PolyShp.get_Point(v).y;
                        y2 = PolyShp.get_Point(v + 1).y;

                        if (x1 != x2) // no vertical lines
                        {
                            m = (y2 - y1) / (x2 - x1);
                            q = y1 - (m * x1);

                            //add border to the list
                            b      = b + 1;
                            brd    = new bord();
                            brd.x1 = x1;
                            brd.x2 = x2;
                            brd.m  = m;
                            brd.q  = q;
                            bordi2.Add(brd);
                        }

                        //in case of multi-parts polygon
                        if ((x2 == x0) && (y2 == y0))
                        {
                            tempn = v + 2;
                            break;
                        }
                    } //Next v
                }     // next p

                //define the first line-scan
                double xstart;

                //    20 nov 07 added by Enrico A. Chiaradia
                //necessary if grid extentions differ from shapefile extentions
                if (xMin >= header.XllCenter)
                {
                    xstart = FirstLineXY(xMin, header.XllCenter, header.dX, 1);
                }
                else
                {
                    xstart = FirstLineXY(xMin, header.XllCenter, header.dX, -1);
                }

                // the list of intersection y-values
                System.Collections.ArrayList y_int  = new System.Collections.ArrayList();
                System.Collections.ArrayList pixels = new System.Collections.ArrayList();

                do
                {
                    flg    = Interseca(bordi2, y_int, xstart);
                    flg    = SortArray(y_int);
                    flg    = ScanLine2(y_int, xstart, ref pixels, ref Newgrd, header, val, cback);
                    xstart = xstart + header.dX;
                }while (xstart <= xMax);

                writePxList(Newgrd, grType, pixels, val, cback);

                //report the progress
                if (s >= shpsPerc)
                {
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                }
            } // next shape

            reportProgress(100, 100, "shapefile to grid", cback); //100 % shapes done
            return(true);
        }
Exemple #16
0
        public void PopulateForm(bool ShowAfterward, MapWinGIS.Grid grid, string layerName, MapWinGIS.Extents ex, int LyrHandle)
        {
            m_HavePanel = !ShowAfterward;

            try
            {
                SetTitle(layerName);
                MapWinGIS.Extents extents = null;

                //clear the list view
                dgv.DataSource = null;

                System.Data.DataSet ds = new System.Data.DataSet();
                ds.Tables.Add();
                ds.Tables[0].Columns.Add("Value", typeof(string));
                ds.Tables[0].Columns.Add("Count", typeof(long));

                if (m_hDraw != -1)
                {
                    m_parent.m_MapWin.View.Draw.ClearDrawing(m_hDraw);
                    m_hDraw = -1;
                }

                //recalculates the extents if needed
                extents = GetMaxExtents(ex, grid.Header);

                extents = ex;

                if (extents != null)
                {
                    //set the map cursor to a wait cursor
                    MapWinGIS.tkCursor m_PreviousCursor = m_parent.m_MapWin.View.MapCursor;
                    m_parent.m_MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrWait;

                    //populate all the values and counts
                    PopulateLV(ref ds, grid, extents, LyrHandle);

                    //set the cursor back to the Identifier cursor
                    m_parent.m_MapWin.View.MapCursor = m_PreviousCursor;
                }
                else
                {
                    lbHighValue.Text = "No Data";
                    lbLowValue.Text  = "No Data";
                }

                SkipDisplayValues = true;
                if (m_hDraw != -1)
                {
                    m_parent.m_MapWin.View.Draw.ClearDrawing(m_hDraw);
                }

                dgv.DataSource = ds.Tables[0];

                if (dgv.SelectedRows.Count > 0)
                {
                    dgv.SelectedRows[0].Selected = false;
                }

                SkipDisplayValues = false;

                m_Extents = extents;
                m_Grid    = grid;

                if (ShowAfterward)
                {
                    this.Show();
                }
            }
            catch (System.Exception exception)
            {
                ShowErrorBox("PopulateForm()", exception.Message);
            }
        }
Exemple #17
0
 public GridRow(MapWinGIS.Grid grid, int rowNum)
 {
     this.grid   = grid;
     this.rowNum = rowNum;
 }
Exemple #18
0
 public void Unitialize()
 {
     m_parent.m_MapWin.View.Draw.ClearDrawing(m_hDraw);
     m_Grid  = null;
     m_hDraw = -1;
 }