Beispiel #1
0
        private void AddLayerInicial(string file)
        {
            MapWinGIS.Shapefile shpfileOpen;
            shpfileOpen = new MapWinGIS.ShapefileClass();

            try
            {
                //open the shapefile
                shpfileOpen.Open(file, null);

                //add the shapefile to the map and legend
                //handle = axMap1.AddLayer(shpfileOpen, true); //sin control legend
                handle = legend1.Layers.Add(shpfileOpen, true);
                legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(shpfileOpen.Filename));
                handleMap.Add(handle);
                string oldProj = shpfileOpen.Projection;

                // bool status = MapWinGeoProc.SpatialReference.ProjectShapefile(sourceProj, destProj, inputSF, resultSF)
                this.flagMapaAbierto = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Informacion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Beispiel #2
0
        private void AddLayer()
        {
            MapWinGIS.Shapefile shpfileOpen;
            string[] fileNombres;

            MapWinGIS.Grid grid;
            MapWinGIS.GridColorScheme gridScheme;
            MapWinGIS.Image image;
            MapWinGIS.Utils utils;

            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Multiselect = true;

            int handle;
            string ext;

            //initialize dialog
            openDlg.Filter = "Supported Formats|*.shp;*.bgd;*asc;*.jpg|Shapefile (*.shp)|*.shp|Binary Grids (*.bgd)|*.bgd|ASCII Grids (*.asc)|*.asc |World File (*.jpg)|*.jpg";
            openDlg.CheckFileExists = true;

            if (openDlg.ShowDialog(this) == DialogResult.OK)
            {
                fileNombres = openDlg.FileNames;
                int totalNombres = fileNombres.Length;
                for (int j = 0; j < totalNombres; j++)
                {

                    //get the extension of the file
                    ext = System.IO.Path.GetExtension(openDlg.FileNames[j]);

                    if (ext == ".bgd" || ext == ".asc" || ext == ".jpg")
                    {
                        if (ext == ".jpg")
                        {
                            image = new MapWinGIS.Image();

                            // open image world file
                            image.Open(openDlg.FileNames[j], MapWinGIS.ImageType.JPEG_FILE, true, null);
                            handle = legend1.Layers.Add(image, true);
                            legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(image.Filename));
                            //handle = axMap1.AddLayer(image, true);
                            handleMap.Add(handle);

                        }
                        else
                        {

                            utils = new MapWinGIS.UtilsClass();
                            gridScheme = new MapWinGIS.GridColorScheme();
                            grid = new MapWinGIS.GridClass();

                            //open the grid
                            grid.Open(openDlg.FileName, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null);

                            //create a coloring scheme for the image
                            gridScheme.UsePredefined(System.Convert.ToDouble(grid.Minimum), System.Convert.ToDouble(grid.Maximum), MapWinGIS.PredefinedColorScheme.SummerMountains);

                            //convert the grid to a image
                            image = utils.GridToImage(grid, gridScheme, null);

                            //add the image to the legend and map
                            handle = axMap1.AddLayer(image, true);
                            handleMap.Add(handle);

                            grid.Close();

                            //utils = new MapWinGIS.UtilsClass();
                            //gridScheme = new MapWinGIS.GridColorScheme();
                            //grid = new MapWinGIS.GridClass();

                            ////open the grid
                            //grid.Open(openDlg.FileName, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null);

                            ////create a coloring scheme for the image
                            //gridScheme.UsePredefined(System.Convert.ToDouble(grid.Minimum), System.Convert.ToDouble(grid.Maximum), MapWinGIS.PredefinedColorScheme.SummerMountains);

                            ////convert the grid to a image
                            //image = utils.GridToImage(grid, gridScheme, null);

                            ////add the image to the legend and map
                            //handle = axMap1.AddLayer(image, true);
                            ////handle = legend1.Layers.Add(image, true);

                            //if (legend1.Layers.IsValidHandle(handle))
                            //{
                            //    //set the layer name
                            //    legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(grid.Filename));

                            //    //set's the legend layer type, this displays a default icon in the legend (line shapefile, point shapefile,polygon shapefile,grid,image)
                            //    legend1.Layers.ItemByHandle(handle).Type = MapWindow.Interfaces.eLayerType.Grid;

                            //    //set coloring scheme
                            //    //when applying a coloring scheme to a shapfile use axMap1.ApplyLegendColors(ShapefileColorScheme)
                            //    //when applying a coloring scheme for a grid or image use axMap1.SetImageLayerColorScheme(handle,GridColorScheme);
                            //    axMap1.SetImageLayerColorScheme(legend1.SelectedLayer, gridScheme);
                            //    legend1.Layers.ItemByHandle(legend1.SelectedLayer).Refresh();
                            //}

                            //close the grid
                            //grid.Close();
                        }

                    }
                    else if (ext == ".shp")
                    {
                        shpfileOpen = new MapWinGIS.ShapefileClass();

                        //open the shapefile
                        shpfileOpen.Open(openDlg.FileNames[j], null);

                        //add the shapefile to the map and legend
                        handle = legend1.Layers.Add(shpfileOpen, true);
                        legend1.Map.set_LayerName(handle, System.IO.Path.GetFileNameWithoutExtension(shpfileOpen.Filename));
                        //handle = axMap1.AddLayer(shpfileOpen, true);
                        handleMap.Add(handle);
                        string oldProj = shpfileOpen.Projection;

                        // bool status = MapWinGeoProc.SpatialReference.ProjectShapefile(sourceProj, destProj, inputSF, resultSF)
                        this.flagMapaAbierto = true;

                    }
                }

            }
        }
        /// <summary>
        /// Returns a shapefile of points from the input shapefile that fall within the polygon.
        /// </summary>
        /// <param name="pointSFPath">Full path to the point shapefile.</param>
        /// <param name="polygon">The polygon used for clipping the point shapefile.</param>
        /// <param name="resultSFPath">Full path to where the resulting point shapefile should be saved.</param>
        /// <param name="copyAttributes">True if copying attributes over</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ClipPointSFWithPolygon(ref string pointSFPath, ref MapWinGIS.Shape polygon, ref string resultSFPath, bool copyAttributes)
        {
            MapWinUtility.Logger.Dbg("ClipPointSFWithPolygon(pointSFPath: " + pointSFPath + ",\n" +
                                     "                       polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                       resultSFPath: " + resultSFPath.ToString() + ",\n" +
                                     "                       copyAttributes: " + copyAttributes.ToString() + ")");

            MapWinGIS.Shapefile resultSF = new MapWinGIS.ShapefileClass();
            MapWinGIS.Shapefile pointSF  = new MapWinGIS.ShapefileClass();
            int    shpIndex = 0;          //all new shapes will be placed at the beginning of the shapefile
            string tmpName;

            if (pointSF.Open(pointSFPath, null) == false)
            {
                gErrorMsg = "Failure to open input shapefile: " + pointSF.get_ErrorMsg(pointSF.LastErrorCode);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            MapWinGIS.ShpfileType sfType = pointSF.ShapefileType;

            //make sure we are dealing with a valid shapefile type
            if (sfType == MapWinGIS.ShpfileType.SHP_POINT || sfType == MapWinGIS.ShpfileType.SHP_POINTM || sfType == MapWinGIS.ShpfileType.SHP_POINTZ)
            {
                if (Globals.PrepareResultSF(ref resultSFPath, ref resultSF, sfType, copyAttributes) == false)
                {
                    return(false);
                }

                if (copyAttributes)
                {
                    MapWinGIS.Field tmpField, pointField;
                    for (int f = 0; f <= pointSF.NumFields - 1; f++)
                    {
                        tmpField   = new MapWinGIS.Field();
                        pointField = pointSF.get_Field(f);
                        tmpName    = pointField.Name;
                        if (tmpName.Contains("MWShapeID"))
                        {
                            tmpField.Name = "Last_" + tmpName;
                        }
                        else
                        {
                            tmpField.Name = tmpName;
                        }
                        tmpField.Width     = pointField.Width;
                        tmpField.Type      = pointField.Type;
                        tmpField.Precision = pointField.Precision;

                        tmpField.Key = pointField.Key;
                        if (!resultSF.EditInsertField(tmpField, ref f, null))
                        {
                            return(false);
                        }
                    }
                }

                int             numTargetPoints = pointSF.NumShapes;
                MapWinGIS.Point targetPoint     = new MapWinGIS.PointClass();
                //MapWinGIS.Utils utils = new MapWinGIS.UtilsClass();
                int numParts = polygon.NumParts;
                if (numParts == 0)
                {
                    numParts = 1;
                }
                Globals.Vertex[][] polyVertArray = new Globals.Vertex[numParts][];
                Globals.ConvertPolyToVertexArray(ref polygon, out polyVertArray);

                for (int i = 0; i <= numTargetPoints - 1; i++)
                {
                    targetPoint = pointSF.QuickPoint(i, 0);

                    if (Utils.PointInPoly(ref polyVertArray, ref targetPoint) == true)
                    {
                        resultSF.EditInsertShape(pointSF.get_Shape(i), ref shpIndex);
                        if (copyAttributes)
                        {
                            for (int f = 0; f <= pointSF.NumFields - 1; f++)
                            {
                                bool tmpbool = resultSF.EditCellValue(f, shpIndex, pointSF.get_CellValue(f, i));
                            }
                        }
                    }
                }

                MapWinGIS.Field ID = new MapWinGIS.FieldClass();
                ID.Name = "MWShapeID";
                ID.Type = MapWinGIS.FieldType.INTEGER_FIELD;
                int fieldIndex = 0;
                if (resultSF.EditInsertField(ID, ref fieldIndex, null) == false)
                {
                    gErrorMsg = "Problem inserting field into .dbf table: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                    Debug.WriteLine(gErrorMsg);
                    Error.SetErrorMsg(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }

                int numIDs = resultSF.NumShapes;
                for (int i = 0; i <= numIDs - 1; i++)
                {
                    if (resultSF.EditCellValue(fieldIndex, i, i) == false)
                    {
                        gErrorMsg = "Problem inserting value into .dbf table for shape " + i + ": " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                        Debug.WriteLine(gErrorMsg);
                        Error.SetErrorMsg(gErrorMsg);
                        MapWinUtility.Logger.Dbg(gErrorMsg);
                        return(false);
                    }
                }

                if (resultSF.StopEditingShapes(true, true, null) == false)
                {
                    gErrorMsg = "Problem with StopEditingShapes: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                    Debug.WriteLine(gErrorMsg);
                    Error.SetErrorMsg(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }

                resultSF.Close();
                pointSF.Close();
                MapWinUtility.Logger.Dbg("Finished ClipPointSFWithPolygon");
            }
            else
            {
                pointSF.Close();
                gErrorMsg = "Shapefile type is incorrect. Must be of type Point.";
                Debug.WriteLine(gErrorMsg);
                MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Occurs when a user clicks on a toolbar button or menu item.
        /// </summary>
        /// <param name="ItemName">The name of the item clicked on.</param>
        /// <param name="Handled">Reference parameter.  Setting Handled to true prevents other plugins from receiving this event.</param>
        public void ItemClicked(string ItemName, ref bool Handled)
        {
            try
            {
                switch (ItemName)
                {
                case "Load Features":
                    string exePath    = Application.ExecutablePath;
                    string pluginPath = exePath.Substring(0, exePath.LastIndexOf("\\")) + "\\ApplicationPlugins\\database\\";
                    Environment.SetEnvironmentVariable("path", pluginPath + ";" + Environment.GetEnvironmentVariable("path"));

                    System.Console.WriteLine("Load Featuer ............");
                    Database.Forms.Connect2Database frmConnect = new Database.Forms.Connect2Database();
                    frmConnect.ShowDialog();

                    if (frmConnect.SqlConnection == null)
                    {
                        System.Windows.Forms.MessageBox.Show("database is not connected");
                        return;
                    }
                    string tempPath = System.Environment.GetEnvironmentVariable("TEMP") + "\\" + DateTime.Now.Millisecond.ToString() + "\\";
                    System.IO.Directory.CreateDirectory(tempPath);

                    Database.Forms.ChoseLayer frmChoseLayer = new Database.Forms.ChoseLayer(frmConnect, tempPath);
                    frmChoseLayer.ShowDialog();


                    string[] shpFiles = System.IO.Directory.GetFiles(tempPath, "*.shp");
                    foreach (string shpFileName in shpFiles)
                    {
                        MapWinGIS.Shapefile sf = new MapWinGIS.ShapefileClass();
                        sf.Open(shpFileName, null);
                        string fullLayerName = sf.Filename.Substring(sf.Filename.LastIndexOf("\\") + 1, sf.Filename.Length - sf.Filename.LastIndexOf("\\") - 1);
                        string layerName     = fullLayerName.Substring(0, fullLayerName.Length - 4);

                        MapWin.Layers.Add(ref sf, layerName);
                    }
                    break;

                case "Export Database to Shapefiles":
                    //Connect to geodatabase:
                    frmConnect = new Database.Forms.Connect2Database();
                    frmConnect.ShowDialog();

                    if (frmConnect.SqlConnection == null)
                    {
                        System.Windows.Forms.MessageBox.Show("database is not connected");
                        return;
                    }
                    frmChoseLayer
                        = new Database.Forms.ChoseLayer(frmConnect, null);
                    frmChoseLayer.ShowDialog();
                    break;

                case "Import Shapefile into Database":
                    //Connect to geodatabase:
                    frmConnect = new Database.Forms.Connect2Database();
                    frmConnect.ShowDialog();

                    if (frmConnect.SqlConnection == null)
                    {
                        System.Windows.Forms.MessageBox.Show("database is not connected");
                        return;
                    }
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.Filter = "Shape Files|*.shp";
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {    //Do the import
                        string fileName      = dlg.FileName;
                        string shortFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                        string tableName     = shortFileName.Substring(0, shortFileName.Length - 4);
                        string strCmd        = " -c \"" + fileName + "\" " + tableName;

                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.FileName               = "shp2pgsql.exe";
                        info.Arguments              = strCmd;
                        info.CreateNoWindow         = true;
                        info.UseShellExecute        = false;
                        info.RedirectStandardOutput = true;
                        System.Diagnostics.Process proc = new System.Diagnostics.Process();
                        proc.StartInfo = info;
                        proc.Start();
                        System.IO.StreamReader    reader  = proc.StandardOutput;
                        System.Text.StringBuilder builder = new System.Text.StringBuilder();
                        IDbCommand daPgsql;

                        while (reader.Peek() >= 0)
                        {
                            string sqlSegment = reader.ReadLine();
                            builder.Append(sqlSegment);
                            if (builder.Length > 1000)
                            {
                                daPgsql = new Npgsql.NpgsqlCommand(builder.ToString(), (Npgsql.NpgsqlConnection)frmConnect.SqlConnection);
                                try
                                {
                                    daPgsql.ExecuteNonQuery();
                                    builder = new StringBuilder();
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.ToString());
                                    return;
                                }
                            }
                        }
                        //Excute the last sql you just got:
                        if (builder.Length > 0)
                        {
                            daPgsql = new Npgsql.NpgsqlCommand(builder.ToString(), (Npgsql.NpgsqlConnection)frmConnect.SqlConnection);
                            try
                            {
                                daPgsql.ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                        }
                    }
                    else
                    {
                        return;
                    }


                    break;

                case "":


                    break;

                default:
                    break;
                }
            }
            catch (System.Exception ex)
            {
                log.Debug(ex.ToString());
            }
        }
        /// <summary>
        /// Returns all portions of the shapefile polygons that fall within the clipper polygon.
        /// </summary>
        /// <param name="polySFPath">The full path to the shapefile of polygons to be clipped.</param>
        /// <param name="polygon">The polygon used for clipping the shapefile.</param>
        /// <param name="resultSFPath">The full path to the result file for where the clipped polygons should be saved.</param>
        /// <param name="copyAttributes">True if copying attrs</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ClipPolygonSFWithPolygon(ref string polySFPath, ref MapWinGIS.Shape polygon, ref string resultSFPath, bool copyAttributes)
        {
            MapWinUtility.Logger.Dbg("ClipPolygonSFWithPolygon(polySFPath: " + polySFPath + ",\n " +
                                     "                         polygon: + " + Macro.ParamName(polygon) + ",\n" +
                                     "                         resultsSFPath: " + resultSFPath + ",\n" +
                                     "                         copyAttributes: " + copyAttributes + ",\n");

            MapWinGIS.Shapefile resultSF = new MapWinGIS.ShapefileClass();
            MapWinGIS.Shapefile polySF   = new MapWinGIS.ShapefileClass();
            polySF.Open(polySFPath, null);
            MapWinGIS.ShpfileType sfType = polySF.ShapefileType;
            int    shapeIndex            = 0;//insert new shapes at the beginning of the shapefile
            string tmpName;

            if (Globals.PrepareResultSF(ref resultSFPath, ref resultSF, sfType, copyAttributes) == false)
            {
                polySF.Close();
                return(false);
            }

            if (copyAttributes)
            {
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= polySF.NumFields - 1; f++)
                {
                    tmpField  = new MapWinGIS.Field();
                    currField = polySF.get_Field(f);
                    tmpName   = currField.Name;
                    if (tmpName.Contains("MWShapeID"))
                    {
                        tmpField.Name = "Last_" + tmpName;
                    }
                    else
                    {
                        tmpField.Name = tmpName;
                    }

                    tmpField.Width     = currField.Width;
                    tmpField.Type      = currField.Type;
                    tmpField.Precision = currField.Precision;
                    tmpField.Key       = currField.Key;
                    resultSF.EditInsertField(tmpField, ref f, null);
                }
            }

            if (sfType == MapWinGIS.ShpfileType.SHP_POLYGON || sfType == MapWinGIS.ShpfileType.SHP_POLYGONM || sfType == MapWinGIS.ShpfileType.SHP_POLYGONZ)
            {
                MapWinGIS.Shape   resultShape = new MapWinGIS.ShapeClass();
                MapWinGIS.Extents shpExtents  = new MapWinGIS.ExtentsClass();
                int  numShapes       = polySF.NumShapes;
                bool boundsIntersect = false;

                for (int i = 0; i <= numShapes - 1; i++)
                {
                    MapWinGIS.Shape currPoly = new MapWinGIS.ShapeClass();
                    currPoly = polySF.get_Shape(i);
                    //check to see if bounds intersect before sending shape to GPC clip function
                    boundsIntersect = Globals.CheckBounds(ref currPoly, ref polygon);

                    if (boundsIntersect == true)
                    {
                        //find the shape resulting from intersection
                        resultShape = SpatialOperations.Intersection(currPoly, polygon);
                        if (resultShape.numPoints != 0)
                        {
                            //save the new shape to the result shapefile
                            if (resultSF.EditInsertShape(resultShape, ref shapeIndex) == false)
                            {
                                gErrorMsg = "Problem inserting shape: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                                Debug.WriteLine(gErrorMsg);
                                Error.SetErrorMsg(gErrorMsg);
                                MapWinUtility.Logger.Dbg(gErrorMsg);
                                return(false);
                            }
                            if (copyAttributes)
                            {
                                for (int f = 0; f <= polySF.NumFields - 1; f++)
                                {
                                    bool tmpbool = resultSF.EditCellValue(f, shapeIndex, polySF.get_CellValue(f, i));
                                }
                            }
                        }
                    }
                }
            }
            if (copyAttributes)
            {
                MapWinGIS.Field ID = new MapWinGIS.FieldClass();
                ID.Name = "MWShapeID";
                ID.Type = MapWinGIS.FieldType.INTEGER_FIELD;
                int fieldIndex = 0;
                if (resultSF.EditInsertField(ID, ref fieldIndex, null) == false)
                {
                    gErrorMsg = "Problem inserting field into .dbf table: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                    Debug.WriteLine(gErrorMsg);
                    Error.SetErrorMsg(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }
            }
            int numIDs = resultSF.NumShapes;

            for (int i = 0; i <= numIDs - 1; i++)
            {
                if (resultSF.EditCellValue(0, i, i) == false)
                {
                    gErrorMsg = "Problem inserting value into .dbf table for shape " + i + ": " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                    Debug.WriteLine(gErrorMsg);
                    Error.SetErrorMsg(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }
            }
            if (resultSF.StopEditingShapes(true, true, null) == false)
            {
                gErrorMsg = "Problem with StopEditingShapes: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                Debug.WriteLine(gErrorMsg);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            resultSF.Close();
            polySF.Close();
            MapWinUtility.Logger.Dbg("Finished ClipPolygonSFWithPolygon");
            return(true);
        }