private void AddRectangle(double LeftmostX, double LowestY, double RightmostX, double HighestY)
        {
            MapWinGIS.Shape newPolygon = new MapWinGIS.Shape();

            int partIndex = 0;

            newPolygon.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
            newPolygon.InsertPart(0, ref partIndex);

            int shpIndex = 0;

            MapWinGIS.Point newPt = new MapWinGIS.Point();
            newPt.x = LeftmostX;
            newPt.y = HighestY;
            newPt.Z = 0;
            newPolygon.InsertPoint(newPt, ref shpIndex);

            newPt   = new MapWinGIS.Point();
            newPt.x = RightmostX;
            newPt.y = HighestY;
            newPt.Z = 0;
            newPolygon.InsertPoint(newPt, ref shpIndex);

            newPt   = new MapWinGIS.Point();
            newPt.x = RightmostX;
            newPt.y = LowestY;
            newPt.Z = 0;
            newPolygon.InsertPoint(newPt, ref shpIndex);

            newPt   = new MapWinGIS.Point();
            newPt.x = LeftmostX;
            newPt.y = LowestY;
            newPt.Z = 0;
            newPolygon.InsertPoint(newPt, ref shpIndex);

            // Finalize -- add it.
            MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)g.MapWin.Layers[g.MapWin.Layers.CurrentLayer].GetObject();
            if (!sf.EditingShapes || !sf.EditingTable)
            {
                sf.StartEditingShapes(true, null);
            }

            int addedShapes = sf.NumShapes;

            sf.EditInsertShape(newPolygon, ref addedShapes);

            g.CreateUndoPoint();

            sf.StopEditingShapes(true, true, null);

            // Release memory used by point reallocations above
            GC.Collect();

            // And show it:
            g.UpdateView();

            g.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + g.MapWin.Layers.CurrentLayer.ToString() + ": New Shape Added");
        }
Пример #2
0
        /// <summary>
        /// Assignes selected projection and displays results
        /// </summary>
        public bool Assign(string filename, MapWinGIS.GeoProjection proj)
        {
            MapWinGIS.GeoProjection projWGS84 = new MapWinGIS.GeoProjection();
            if (!projWGS84.ImportFromEPSG(4326))
            {
                MessageBox.Show("Failed to initialize WGS84 coordinate system.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            bool sameProj = proj.get_IsSame(projWGS84);
            int  count    = 0;

            bool success  = false;
            int  rowIndex = dgv.Rows.Add();

            m_shapefile = new MapWinGIS.Shapefile();
            if (m_shapefile.Open(filename, m_mapWin.Layers as MapWinGIS.ICallback))
            {
                this.Text = "Assigning projection: " + System.IO.Path.GetFileName(filename);
                this.lblProjection.Text = "Projection: " + proj.Name;

                // it will be faster to assing new instance of class
                // as ImportFromEPSG() is slow according to GDAL documentation
                m_shapefile.GeoProjection = proj;

                if (!sameProj)
                {
                    // we can't show preview on map without reprojection
                    if ((m_shapefile.StartEditingShapes(true, null)))
                    {
                        if (m_shapefile.ReprojectInPlace(projWGS84, ref count))
                        {
                            success = true;
                        }
                    }
                }
                else
                {
                    success = true;
                }
            }

            if (success)
            {
                this.AddShapefile(m_shapefile);
                return(true);
            }
            else
            {
                // no success in reprojection
                m_shapefile.Close();
                return(false);
            }
        }
Пример #3
0
        private void ResizeShapes()
        {
            try
            {
                System.Collections.SortedList arr = new System.Collections.SortedList();
                for (int i = 0; i < g.MapWin.View.SelectedShapes.NumSelected; i++)
                {
                    arr.Add(g.MapWin.View.SelectedShapes[i].ShapeIndex, g.MapWin.View.SelectedShapes[i].ShapeIndex);
                }

                if (arr.Count > 0)
                {
                    MapWinGIS.Shapefile sf = g.CurrentLayer;
                    if (sf.StartEditingShapes(true, null))
                    {
                        System.Diagnostics.Debug.WriteLine(sf.get_ErrorMsg(sf.LastErrorCode));
                        bool allCancelled = false;
                        for (int j = arr.Count - 1; j >= 0; j--)
                        {
                            // Show the dialog to get input -- resize amount
                            // Actual resizing done here also
                            Forms.ResizeShapeForm dlg = new Forms.ResizeShapeForm(g);

                            dlg.Shape = (int)arr.GetByIndex(j);
                            dlg.sf    = sf;

                            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                            {
                                allCancelled = true;
                                break;
                            }
                        }

                        if (!allCancelled)
                        {
                            g.CreateUndoPoint();
                            if (sf.StopEditingShapes(true, true, null) == false)
                            {
                                MapWinUtility.Logger.Message("Failed to save the changes that were made.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
                            }
                        }
                        else
                        {
                            sf.StopEditingShapes(false, true, null);
                            MapWinUtility.Logger.Message("Shape resizing has been cancelled - no changes were saved.", "Cancelled", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.DialogResult.OK);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
            }
        }
Пример #4
0
        /// <summary>
        /// Actually engages the append shapes process
        /// </summary>
        public void DoMergeShapefiles()
        {
            MapWinUtility.Logger.Dbg("DoMergeShapefiles()");
            string errorMessage;

            _inSF1 = new MapWinGIS.Shapefile();
            _inSF2 = new MapWinGIS.Shapefile();
            _outSF = new MapWinGIS.Shapefile();

            GetFilenames();

            if (OpenFiles(out errorMessage) == false)
            {
                MapWinUtility.Logger.Message(errorMessage, "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK);
                return;
            }


            if (_outSF.StartEditingShapes(true, null) == false)
            {
                CloseMessage(_outSF.get_ErrorMsg(_outSF.LastErrorCode));
                return;
            }

            // Determine a list of unique fields to add to the output shapefile.
            if (CombineFields(out errorMessage) == false)
            {
                CloseMessage(errorMessage);
                return;
            }

            if (AddShapes(_inSF1, out errorMessage) == false)
            {
                CloseMessage(errorMessage);
                return;
            }

            if (AddShapes(_inSF2, out errorMessage) == false)
            {
                CloseMessage(errorMessage);
                return;
            }

            _inSF2.Close();
            _inSF1.Close();
            if (_outSF.StopEditingShapes(true, true, null) == false)
            {
                MapWinUtility.Logger.Message(_outSF.get_ErrorMsg(_outSF.LastErrorCode), "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK);
                return;
            }

            _outSF.Close();
            MapWinUtility.Logger.Message("Finished Merging Shapes", "File Error", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK);
        }
        private void AddEllipse(double LeftmostX, double LowestY, double RightmostX, double HighestY)
        {
            MapWinGIS.Shape newPolygon = new MapWinGIS.Shape();

            int partIndex = 0;

            newPolygon.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
            newPolygon.InsertPart(0, ref partIndex);

            int shpIndex = 0;

            double t, a, b, tinc, centx, centy;

            a     = RightmostX - LeftmostX;
            b     = HighestY - LowestY;
            tinc  = Math.PI * 2 / (a + b);
            centx = (LeftmostX + RightmostX) * .5;
            centy = (LowestY + HighestY) * .5;

            MapWinGIS.Point newPt = new MapWinGIS.Point();
            newPt.x = centx + a;
            newPt.y = centy;
            newPt.Z = 0;
            newPolygon.InsertPoint(newPt, ref shpIndex);

            for (t = 0; t < Math.PI * 2; t += tinc)
            {
                MapWinGIS.Point nextPt = new MapWinGIS.Point();
                nextPt.x = centx + a * Math.Cos(t);
                nextPt.y = centy - b * Math.Sin(t);
                nextPt.Z = 0;
                newPolygon.InsertPoint(nextPt, ref shpIndex);
            }

            // Finalize -- add it.
            MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)g.MapWin.Layers[g.MapWin.Layers.CurrentLayer].GetObject();
            if (!sf.EditingShapes || !sf.EditingTable)
            {
                sf.StartEditingShapes(true, null);
            }

            int addedShapes = sf.NumShapes;

            sf.EditInsertShape(newPolygon, ref addedShapes);

            g.CreateUndoPoint();

            sf.StopEditingShapes(true, true, null);

            // And show it:
            g.UpdateView();

            g.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + g.MapWin.Layers.CurrentLayer.ToString() + ": New Shape Added");
        }
        }         // End of 'public void ItemClickedEvent(string ItemName, ref bool Handled)'

        private void RemoveShapes()
        {
            try
            {
                System.Collections.SortedList arr = new System.Collections.SortedList();
                for (int i = 0; i < g.MapWin.View.SelectedShapes.NumSelected; i++)
                {
                    arr.Add(g.MapWin.View.SelectedShapes[i].ShapeIndex, g.MapWin.View.SelectedShapes[i].ShapeIndex);
                }

                if (arr.Count > 0)
                {
                    if (MapWinUtility.Logger.Message("Do you wish to permanently remove the selected shapes?", "Confirm delete", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.DialogResult.Yes) == System.Windows.Forms.DialogResult.Yes)
                    {
                        // Deletion has been confirmed.
                        // actually delete the shapes now
                        g.MapWin.View.ClearSelectedShapes();
                        MapWinGIS.Shapefile sf = g.CurrentLayer;

                        g.CreateUndoPoint();

                        if (sf.StartEditingShapes(true, null))
                        {
                            System.Diagnostics.Debug.WriteLine(sf.get_ErrorMsg(sf.LastErrorCode));
                            for (int j = arr.Count - 1; j >= 0; j--)
                            {
                                if (sf.EditDeleteShape((int)arr.GetByIndex(j)) == false)
                                {
                                    System.Diagnostics.Debug.WriteLine(sf.get_ErrorMsg(sf.LastErrorCode));
                                }
                            }

                            if (sf.StopEditingShapes(true, true, null) == false)
                            {
                                MapWinUtility.Logger.Message("Failed to save the changes that were made.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
                            }

                            g.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + g.MapWin.Layers.CurrentLayer.ToString() + ": Shape Deleted");
                        }

                        //added 1/29/2005
                        g.MapWin.Toolbar.ButtonItem("RemoveShapeButton").Enabled = false;
                        g.MapWin.Toolbar.ButtonItem("RemoveShapeButton").Tooltip = "Remove shapes (a shape must be selected)";

                        g.UpdateView();
                    }
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
            }
        } // end void RemoveShapes()
        private void AddRegularPolygon(int sides, double sidelength, double centroidX, double centroidY)
        {
            double pi      = 3.1415926535897932384626433832795;
            double apothem = sidelength / (2 * Math.Tan(pi / sides));
            double radius  = sidelength / (2 * Math.Sin(pi / sides));

            MapWinGIS.Shape newPolygon = new MapWinGIS.Shape();

            int partIndex = 0;

            newPolygon.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
            newPolygon.InsertPart(0, ref partIndex);

            double i        = 0;
            int    shpIndex = 0;

            // Approximate the polygon with n line segments
            double increment = ((2 * pi) / sides);

            for (; i <= 2 * pi; i += increment, shpIndex++)
            {
                MapWinGIS.Point newPt = new MapWinGIS.Point();

                newPt.x = (radius * Math.Cos(i) + centroidX);
                newPt.y = (radius * Math.Sin(i) + centroidY);
                newPt.Z = 0;

                newPolygon.InsertPoint(newPt, ref shpIndex);
            }

            // Finalize -- add it.
            MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)g.MapWin.Layers[g.MapWin.Layers.CurrentLayer].GetObject();
            if (!sf.EditingShapes || !sf.EditingTable)
            {
                sf.StartEditingShapes(true, null);
            }

            int addedShapes = sf.NumShapes;

            sf.EditInsertShape(newPolygon, ref addedShapes);

            g.CreateUndoPoint();

            sf.StopEditingShapes(true, true, null);

            // And show it:
            g.UpdateView();

            g.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + g.MapWin.Layers.CurrentLayer.ToString() + ": New Shape Added");
        }
Пример #8
0
        private bool AddPointToShapeFile(double x, double y, MapWinGIS.Shapefile shpFile, int shpIndex, int insertIndex)
        {
            try
            {
                MapWinGIS.Point p;

                //start editing shapes
                shpFile.StartEditingShapes(true, null);
                MapWinGIS.Shape shp = shpFile.get_Shape(shpIndex);

                p   = new MapWinGIS.Point();
                p.x = x;
                p.y = y;

                if (!shp.InsertPoint(p, ref insertIndex))
                {
                    return(false);
                }
                else if (shp.NumParts > 1)
                {
                    // Shift up part indices if needed (bugzilla 798)
                    bool shifting = false;
                    for (int i = 0; i < shp.NumParts; i++)
                    {
                        if (shp.get_Part(i) >= insertIndex)
                        {
                            // Shift up this one and all remaining
                            shifting = true;
                        }
                        if (shifting)
                        {
                            shp.set_Part(i, shp.get_Part(i) + 1);
                        }
                    }
                }

                m_Globals.CreateUndoPoint();

                //stop editing and save changes
                shpFile.StopEditingShapes(true, true, null);

                return(true);
            }
            catch (System.Exception ex)
            {
                m_MapWin.ShowErrorDialog(ex);
            }

            return(false);
        }
Пример #9
0
        public void MapMouseUp(int Button, int Shift, int x, int y, ref bool Handled)
        {
            try
            {
                if (m_globals.CurrentMode == GlobalFunctions.Modes.MoveShape)
                {
                    if (m_MapDraging == true)
                    {
                        double projX = 0, projY = 0;
                        m_MapWin.View.PixelToProj((double)x, (double)y, ref projX, ref projY);

                        //get the working shapefile
                        if (m_globals.CurrentLayer == null)
                        {
                            return;
                        }
                        MapWinGIS.Shapefile shpFile = m_globals.CurrentLayer;

                        //start editing the vertex postion
                        shpFile.StartEditingShapes(true, null);



                        //stop editing and save changes
                        shpFile.StopEditingShapes(true, true, null);

                        //set the cursor to move cur
                        m_MapWin.View.UserCursorHandle = (int)m_cursor.Handle;

                        // update snap class
                        m_snapClass = new SnapClass(m_MapWin);
                    }

                    ClearDrawings();
                    m_MapDraging = false;
                    Handled      = true;
                }
            }
            catch (System.Exception ex)
            {
                m_MapWin.ShowErrorDialog(ex);
            }
        }
        private void RemoveVertices(System.Collections.ArrayList lst)
        {
            try
            {
                MapWindow.Interfaces.View v = m_globals.MapWin.View;

                foreach (SnapData data in lst)
                {
                    if (IsSelected(data.shpIndex))
                    {
                        MapWinGIS.Shapefile sf = m_globals.CurrentLayer;
                        sf.StartEditingShapes(true, null);

                        MapWinGIS.Shape shp = sf.get_Shape(data.shpIndex);
                        shp.DeletePoint(data.pointIndex);
                    }
                }
            }
            catch (System.Exception ex)
            {
                m_globals.MapWin.ShowErrorDialog(ex);
            }
        }
Пример #11
0
        private void RemoveSelectedVertex(System.Collections.ArrayList snapPoints, MapWinGIS.Shapefile shpFile)
        {
            try
            {
                //start editing shapes
                shpFile.StartEditingShapes(true, null);

                ShapefileEditor.SnapData snapData;
                int count;

                if (snapPoints.Count == 0)
                {
                    return;
                }

                if (m_globals.AllowSnapingToVertices)
                {
                    count = snapPoints.Count;
                }
                else
                {
                    count = 1;
                }

                //delete all snapPoints
                for (int i = count - 1; i >= 0; i--)
                {
                    snapData = (ShapefileEditor.SnapData)snapPoints[i];

                    MapWinGIS.Shape shp = shpFile.get_Shape(snapData.shpIndex);

                    if (shpFile.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINE)
                    {
                        if (shpFile.get_Shape(snapData.shpIndex).numPoints > 2)
                        {
                            if (shp.DeletePoint(snapData.pointIndex))
                            {
                                ShiftDownVertices(ref shp, snapData.pointIndex);
                            }
                        }
                        else
                        {
                            MapWinUtility.Logger.Message("You can not delete this point from this shape. Line shapes must have at least two points. If you want to delete this shape then use remove shape.", "Error in remove vertex", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, DialogResult.OK);
                        }
                    }
                    else if (shpFile.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYGON)
                    {
                        if (shpFile.get_Shape(snapData.shpIndex).numPoints > 4)
                        {
                            if (shp.DeletePoint(snapData.pointIndex))
                            {
                                ShiftDownVertices(ref shp, snapData.pointIndex);
                            }
                        }
                        else
                        {
                            MapWinUtility.Logger.Message("You can not delete this point from this shape. Polygon shapes must have at least three points. If you want to delete this shape then use remove shape.", "Error in remove vertex", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, DialogResult.OK);
                        }
                    }
                    else if (shpFile.ShapefileType == MapWinGIS.ShpfileType.SHP_POINT)
                    {
                        MapWinUtility.Logger.Message("You can not delete this point from this shape. Point shapes must have at least one point. If you want to delete this shape then use remove shape.", "Error in remove vertex", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, DialogResult.OK);
                    }
                }

                m_globals.CreateUndoPoint();

                //stop editing and save changes
                shpFile.StopEditingShapes(true, true, null);
            }
            catch (System.Exception ex)
            {
                m_MapWin.ShowErrorDialog(ex);
            }
        }
Пример #12
0
        private void RotateShapes()
        {
            try
            {
                System.Collections.SortedList arr = new System.Collections.SortedList();
                for (int i = 0; i < g.MapWin.View.SelectedShapes.NumSelected; i++)
                {
                    arr.Add(g.MapWin.View.SelectedShapes[i].ShapeIndex, g.MapWin.View.SelectedShapes[i].ShapeIndex);
                }

                if (arr.Count > 0)
                {
                    MapWinGIS.Shapefile sf = g.CurrentLayer;
                    if (sf.StartEditingShapes(true, null))
                    {
                        System.Diagnostics.Debug.WriteLine(sf.get_ErrorMsg(sf.LastErrorCode));
                        bool allCancelled = false;
                        for (int j = arr.Count - 1; j >= 0; j--)
                        {
                            // Show the dialog to get input -- rotation amount,
                            // rotate about point, etc. Note that dialog defaults
                            // to rotate about the centroid, which is calculated
                            // when the shape is set.
                            // Actual rotation will be done here as well.
                            dlg = new Forms.RotateShapeForm(g);

                            dlg.sf    = sf;
                            dlg.Shape = sf.get_Shape((int)arr.GetByIndex(j));

                            // Note -- don't show modally; we want the user
                            // to be able to click the map to choose a point if needed
                            dlg.Show(g.MapWindowForm);
                            // However, execution should not proceed until the user has finished...
                            // So we use a really old-style waiting scheme
                            while (dlg.Visible)
                            {
                                System.Windows.Forms.Application.DoEvents();
                            }

                            if (dlg.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                            {
                                allCancelled = true;
                                break;
                            }
                        }

                        if (!allCancelled)
                        {
                            g.CreateUndoPoint();
                            if (sf.StopEditingShapes(true, true, null) == false)
                            {
                                MapWinUtility.Logger.Message("Failed to save the changes that were made.", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK);
                            }
                        }
                        else
                        {
                            sf.StopEditingShapes(false, true, null);
                            MapWinUtility.Logger.Message("Shape resizing has been cancelled - no changes were saved.", "Cancelled", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.DialogResult.OK);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message.ToString());
            }
        }
Пример #13
0
        /// <summary>
        /// Exports the shapes that are selected in the MapWindow view to a new shapefile.
        /// </summary>
        /// <param name="MapWin">A reference to the running MapWindow.</param>
        /// <param name="ExportToSFPath">The full path to where the result shapefile should be saved.</param>
        /// <param name="AddToMap">Indicates that the output should be added to the map view immediately.</param>
        /// <returns>False if an error occurs, true otherwise.</returns>
        public static bool ExportSelectedMWViewShapes(MapWindow.Interfaces.IMapWin MapWin, string ExportToSFPath, bool AddToMap)
        {
            MapWinUtility.Logger.Dbg("ExportSelectedMWViewShapes(MapWin: IMapWin,\n" +
                                     "                           ExportToSFPath: " + ExportToSFPath + ",\n" +
                                     "                           AddToMap: " + AddToMap.ToString() + ")");

            if (MapWin.Layers.NumLayers == 0)
            {
                gErrorMsg = "Please select a layer first.";
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            if (MapWin.View.SelectedShapes.NumSelected == 0)
            {
                gErrorMsg = "There are no selected features to export. Please select a feature first.";
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            MapWinGIS.Shapefile sf     = new MapWinGIS.Shapefile();
            MapWinGIS.Shapefile tollSF = new MapWinGIS.Shapefile();
            MapWinGIS.Field     fld    = new MapWinGIS.Field();
            MapWinGIS.Shape     seg    = new MapWinGIS.Shape();
            int  Segments;
            bool Status;

            Status = sf.Open(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, null);
            if (Status == false)
            {
                gErrorMsg = sf.get_ErrorMsg(sf.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (System.IO.File.Exists(ExportToSFPath))
            {
                try
                {
                    DataManagement.DeleteShapefile(ref ExportToSFPath);
                }
                catch
                {
                    gErrorMsg = "The destination file already exists, but could not be deleted. Please check to make sure the file isn't in use.";
                    Error.SetErrorMsg(gErrorMsg);
                    MapWinUtility.Logger.Dbg(gErrorMsg);
                    return(false);
                }
            }

            Status = tollSF.CreateNew(ExportToSFPath, sf.ShapefileType);

            if (Status == false)
            {
                gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            try
            {
                tollSF.Projection = sf.Projection;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }

            Status = tollSF.StartEditingShapes(true, null);
            if (Status == false)
            {
                gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode);
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            fld.Name  = "MWShapeID";
            fld.Type  = MapWinGIS.FieldType.INTEGER_FIELD;
            fld.Width = 12;
            Segments  = 0;

            // Chris M -- This is already opened above, why open
            // it again here?
            // sf.Open(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, null);

            for (int j = 0; j <= sf.NumFields - 1; j++)
            {
                tollSF.EditInsertField(sf.get_Field(j), ref j, null);
            }
            MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrWait;
            try
            {
                for (int i = 0; i <= MapWin.View.SelectedShapes.NumSelected - 1; i++)
                {
                    seg    = sf.get_Shape(MapWin.View.SelectedShapes[i].ShapeIndex);
                    Status = tollSF.EditInsertShape(seg, ref Segments);
                    if (Status == false)
                    {
                        gErrorMsg = tollSF.get_ErrorMsg(tollSF.LastErrorCode);
                        Error.SetErrorMsg(gErrorMsg);
                        MapWinUtility.Logger.Dbg(gErrorMsg);
                        return(false);
                    }
                    for (int h = 0; h <= sf.NumFields - 1; h++)
                    {
                        tollSF.EditCellValue(h, i, sf.get_CellValue(h, MapWin.View.SelectedShapes[i].ShapeIndex));
                    }
                    Segments = Segments + 1;
                }
                sf.Close();
                tollSF.StopEditingShapes(true, true, null);
            }
            catch (Exception ex)
            {
                gErrorMsg = ex.Message;
                Error.SetErrorMsg(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
            }
            MapWin.View.MapCursor = MapWinGIS.tkCursor.crsrArrow;
            tollSF.Close();
            if (AddToMap)
            {
                MapWin.View.LockMap();
                MapWindow.Interfaces.Layer thelayer;
                thelayer = MapWin.Layers.Add(ExportToSFPath, System.IO.Path.GetFileNameWithoutExtension(ExportToSFPath), true);
                thelayer.ClearLabels();
                MapWin.View.UnlockMap();
            }
            MapWinUtility.Logger.Dbg("Finished ExportSelectedMWViewShapes");
            return(true);
        }
        public void MapMouseUp(int Button, int Shift, int x, int y, ref bool Handled)
        {
            try
            {
                if (m_globals.CurrentMode == GlobalFunctions.Modes.MoveVertex)
                {
                    if (m_MapDraging == true)
                    {
                        double projX = 0, projY = 0;
                        m_MapWin.View.PixelToProj((double)x, (double)y, ref projX, ref projY);

                        //get the working shapefile
                        if (m_globals.CurrentLayer == null)
                        {
                            return;
                        }
                        MapWinGIS.Shapefile shpFile = m_globals.CurrentLayer;

                        //start editing the vertex postion
                        shpFile.StartEditingShapes(true, null);

                        //get all the vertex points that are within tolerance
                        System.Collections.ArrayList snapPoints = new System.Collections.ArrayList();
                        if (m_snapClass.CanSnap(m_globals.CurrentTolerance, projX, projY, ref snapPoints))
                        {
                            DrawAllSnapPoints(snapPoints);
                        }

                        ShapefileEditor.SnapData snapPoint;
                        MapWinGIS.Shape          shp;
                        MapWinGIS.Point          p;

                        //if allow snaping then change all vertex in the snaping tolerance
                        int count;
                        if (m_globals.AllowSnapingToVertices)
                        {
                            count = m_snapPoints.Count;
                        }
                        else
                        {
                            count = Math.Min(m_snapPoints.Count, 1);
                        }

                        for (int i = 0; i < count; i++)
                        {
                            snapPoint = (ShapefileEditor.SnapData)m_snapPoints[i];
                            shp       = shpFile.get_Shape(snapPoint.shpIndex);
                            p         = shp.get_Point(snapPoint.pointIndex);

                            //check to see if were going to snap to a point
                            if (snapPoints.Count > 0 && m_globals.AllowSnapingToVertices)
                            {
                                p.x = ((ShapefileEditor.SnapData)snapPoints[0]).point.x;
                                p.y = ((ShapefileEditor.SnapData)snapPoints[0]).point.y;
                            }
                            else
                            {
                                p.x = projX;
                                p.y = projY;
                            }
                        }

                        m_globals.CreateUndoPoint();

                        //stop editing and save changes
                        shpFile.StopEditingShapes(true, true, null);

                        //set the cursor to move cur
                        m_MapWin.View.UserCursorHandle = (int)m_cursor.Handle;

                        // update snap class
                        m_snapClass = new SnapClass(m_MapWin);
                    }

                    ClearDrawings();
                    m_MapDraging = false;
                    Handled      = true;
                }
            }
            catch (System.Exception ex)
            {
                m_MapWin.ShowErrorDialog(ex);
            }
        }
Пример #15
0
        private void AddShape(ShapeClass s)
        {
            if (m_SFType == MapWindow.Interfaces.eLayerType.LineShapefile)
            {
                if (s.NumPoints < 2)
                {
                    ResetForNew();
                    MapWinUtility.Logger.Message("You must add at least two points for a line.", "Not Enough Points", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, DialogResult.OK);
                    return;
                }
            }
            else if (m_SFType == MapWindow.Interfaces.eLayerType.PolygonShapefile)
            {
                // 3 + 1 for termination point - first must equal last, meaning we have to have 4 for a polygon
                if (s.NumPoints < 4)
                {
                    ResetForNew();
                    MapWinUtility.Logger.Message("You must add at least three points for a polygon.", "Not Enough Points", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, DialogResult.OK);
                    return;
                }
            }

            if (m_sf.EditingShapes == false)
            {
                if (m_sf.StartEditingShapes(true, null) == false)
                {
                    MapWinUtility.Logger.Msg("Could not edit the shapefile.", "Error");
                    if (!GlobalFunctions.m_StayInAddMode)
                    {
                        this.Close();
                    }
                    else
                    {
                        ResetForNew();
                    }
                    return;
                }
            }

            int newIndex = m_sf.NumShapes;

            MapWinGIS.Shape shp = s.ToMWShape(m_sf.ShapefileType);
            //MapWinGIS.ShapefileColorScheme cs = m_globals.MapWin.Layers[m_globals.MapWin.Layers.CurrentLayer].ColoringScheme;
            if (m_sf.EditInsertShape(shp, ref newIndex) == false)
            {
                MapWinUtility.Logger.Msg("Failed to add the new shape to the shapefile.", "Error");
            }
            else
            {
                if (m_snapper != null)
                {
                    m_snapper.AddShapeData(newIndex, m_globals.MapWin.Layers.CurrentLayer);
                }

                // Save
                if (m_sf.EditingShapes == true)
                {
                    m_globals.CreateUndoPoint();
                    m_sf.StopEditingShapes(true, true, null);
                }

                m_globals.MapWin.Plugins.BroadcastMessage("ShapefileEditor: Layer " + m_globals.MapWin.Layers.CurrentLayer.ToString() + ": New Shape Added");
            }
            m_globals.MapWin.View.Draw.ClearDrawing(m_drawHandle);
            if (!GlobalFunctions.m_StayInAddMode)
            {
                this.Close();
            }
            else
            {
                ResetForNew();
            }
        }
Пример #16
0
        private void MovePolygons(int ScreenX, int ScreenY)
        {
            try
            {
                if (m_objShapefile != null && m_selectInfo != null)
                {
                    m_globals.LogWrite("num selected shapes: " + m_selectInfo.NumSelected.ToString());
                    m_dblDestinyX = ScreenX;
                    m_dblDestinyY = ScreenY;
                    double dblProjInitX = 0;
                    double dblProjInitY = 0;
                    double dblDestProjX = 0;
                    double dblDestProjY = 0;
                    m_globals.MapWin.View.PixelToProj(m_dblInitX, m_dblInitY, ref dblProjInitX, ref dblProjInitY);
                    m_globals.MapWin.View.PixelToProj(m_dblDestinyX, m_dblDestinyY, ref dblDestProjX, ref dblDestProjY);

                    double dblDistanceX = Math.Abs(dblProjInitX - dblDestProjX);
                    double dblDistanceY = Math.Abs(dblProjInitY - dblDestProjY);


                    if (m_intSelectedShapes != null)
                    {
                        //double dblxMin, dblyMin, dblzMin, dblxMax, dblyMax, dblzMax;
                        //m_selectInfo.SelectBounds.GetBounds(out dblxMin, out dblyMin, out dblzMin, out dblxMax, out dblyMax, out dblzMax);

                        m_objShapefile.StartEditingShapes(true, null);
                        // Chris M 12/21/2006 - no longer necessary, using an integer array now

                        /* int[] intShapes = null;
                         * intShapes = (int[])m_objShapes; */

                        MapWinGIS.Shape objShape = null;

                        if (m_intSelectedShapes.Length > 0)
                        {
                            //http://www.mapwindow.org/wiki/index.php/MapWinGIS:SampleCode-VB_Net:SelectShapes
                            int intUpperBound = m_intSelectedShapes.Length;
                            m_globals.LogWrite("Upperbound" + intUpperBound);
                            for (int ixShape = 0; ixShape < intUpperBound; ixShape++)
                            {
                                // Move each next selected shape.
                                objShape = m_objShapefile.get_Shape(m_intSelectedShapes[ixShape]);
                                Moveshape(dblDistanceX, dblDistanceY, objShape);
                                m_globals.LogWrite(">1");
                            }
                        }

                        if (!m_objShapefile.StopEditingShapes(true, true, null))//true, true, ICallback))
                        {
                            //ToDo: Stopediting failed.
                            throw new Exception("referencing intShapes failed.");
                        }
                        ;
                        m_globals.MapWin.View.Redraw();
                    }
                    else
                    {
                        throw new Exception("Selectshapes failed.");
                    };
                }
                else
                {
                    //ToDo: Handling shapefile not opened.
                    throw new Exception("shapefile opened failed.");
                }
            }
            catch (Exception ex)
            {
                m_globals.LogWrite(ex.Message);
                m_globals.LogWrite(ex.StackTrace);;
            }
        }
Пример #17
0
        /// <summary>
        /// This creates a new shapefile that has Z values and follows along the same line segments.
        /// The boundaries for grid cells are marked with vertices and the segment is given a Z value
        /// that corresponds to the grid elevation it intersects.
        /// </summary>
        /// <param name="mwElevGrid">A MapWinGIS Grid that contains the elevations.</param>
        /// <param name="mwPolyLine">A MapWinGIS Shapefile that shows the pathways of the cross sections in the X-Y direction.</param>
        /// <param name="OutFileName">A string containing the full path of the desired output shapefile.  The extension should be *.shp</param>
        /// <param name="CrossSectionType">Clarifies the type of output.  default = PolyLineWithZ</param>
        /// <param name="ICallBack">A MapWinGIS.ICallback for progress messages. [Optional]</param>
        /// <remarks>This function throws Argument or Application exceptions on errors, so it's recommended that coders enclose it in a try catch block.</remarks>
        public static void GetCrossSection(MapWinGIS.Grid mwElevGrid, MapWinGIS.Shapefile mwPolyLine, string OutFileName, CrossSectionTypes CrossSectionType, MapWinGIS.ICallback ICallBack)
        {
            MapWinUtility.Logger.Dbg("GetCrossSection(mwElevGrid: " + Macro.ParamName(mwElevGrid) + ",\n" +
                                     "                mwPolyLine: " + Macro.ParamName(mwPolyLine) + ",\n" +
                                     "                OutFileName: " + OutFileName + ",\n" +
                                     "                CrossSectionType: " + CrossSectionType.ToString() + ",\n" +
                                     "                ICallback)");
            bool   res;
            int    Prog = 0;
            int    OldProg = 0;
            double dS, dX, dY, XllCenter, YllCenter;
            int    NumRows, NumCols, ElevField, IDField;

            ElevField = 1;
            IDField   = 0;
            // Test to be sure that the elevation grid and shapefile are not null
            if (mwElevGrid == null)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: Elevation grid mwElevGrid can't be null.");
                throw new ArgumentException("Elevation grid mwElevGrid can't be null.");
            }
            if (mwPolyLine == null)
            {
                MapWinUtility.Logger.Dbg("Argument Exception: The shapefile of input cross sections mwPolyLine can't be null.");
                throw new ArgumentException("The shapefile of input cross sections mwPolyLine can't be null.");
            }

            // Clear any existing shapefile output filenames that might cause problems if they exist.
            string fn;

            if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(OutFileName)) == false)
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(OutFileName));
            }
            if (System.IO.File.Exists(OutFileName))
            {
                System.IO.File.Delete(OutFileName);
            }
            fn = System.IO.Path.ChangeExtension(OutFileName, ".dbf");
            if (System.IO.File.Exists(fn))
            {
                System.IO.File.Delete(fn);
            }
            fn = System.IO.Path.ChangeExtension(OutFileName, ".shx");
            if (System.IO.File.Exists(fn))
            {
                System.IO.File.Delete(fn);
            }
            fn = System.IO.Path.ChangeExtension(OutFileName, ".prj");
            if (System.IO.File.Exists(fn))
            {
                System.IO.File.Delete(fn);
            }
            // Since we are given the lower left coordinate, just make sure dX and dY are positive
            dX = Math.Abs(mwElevGrid.Header.dX);
            if (dX == 0)
            {
                throw new ApplicationException("mwElevGrid.Header.dX cannot be 0.");
            }
            dY = Math.Abs(mwElevGrid.Header.dY);
            if (dY == 0)
            {
                throw new ApplicationException("mwElevGrid.Header.dY cannot be 0.");
            }

            // Determine the stepping distance from the grid coordintes
            dS = dX / 2;
            if (dY < dX)
            {
                dS = dY / 2;
            }


            XllCenter = mwElevGrid.Header.XllCenter;
            YllCenter = mwElevGrid.Header.YllCenter;
            NumRows   = mwElevGrid.Header.NumberRows;
            NumCols   = mwElevGrid.Header.NumberCols;

            // Test for intersection between the entire shapefile and the grid
            double left, right, top, bottom;

            left   = XllCenter - dX / 2;
            right  = XllCenter + NumCols * dX - dX / 2;
            bottom = YllCenter - dY / 2;
            top    = YllCenter + NumRows * dY - dY / 2;
            MapWinGeoProc.Topology2D.Envelope gExt = new MapWinGeoProc.Topology2D.Envelope(left, right, bottom, top);
            MapWinGeoProc.Topology2D.Envelope pExt = new MapWinGeoProc.Topology2D.Envelope(mwPolyLine.Extents);
            if (gExt.Intersects(pExt) == false)
            {
                MapWinUtility.Logger.Dbg("Application Exception: The shapefile doesn't overlap the grid, so no cross sections were found.");
                throw new ApplicationException("The shapefile doesn't overlap the grid, so no cross sections were found.");
            }


            // Setup the output shapefile and the basic shape objects
            MapWinGIS.Shape     mwShape;
            MapWinGIS.Shapefile sfOut = new MapWinGIS.Shapefile();
            sfOut.Projection = mwPolyLine.Projection;

            if (CrossSectionType == CrossSectionTypes.PointsWithZAndElevField)
            {
                res = sfOut.CreateNew(OutFileName, MapWinGIS.ShpfileType.SHP_POINTZ);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
                res = sfOut.StartEditingShapes(true, ICallBack);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
                MapWinGIS.Field ID = new MapWinGIS.Field();
                ID.Name = "ID";
                ID.Type = MapWinGIS.FieldType.INTEGER_FIELD;
                res     = sfOut.EditInsertField(ID, ref IDField, ICallBack);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
                MapWinGIS.Field Elev = new MapWinGIS.Field();
                Elev.Name = "Elevation";
                Elev.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
                res       = sfOut.EditInsertField(Elev, ref ElevField, ICallBack);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
            }
            else
            {
                res = sfOut.CreateNew(OutFileName, MapWinGIS.ShpfileType.SHP_POLYLINEZ);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
                res = sfOut.StartEditingShapes(true, ICallBack);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
                MapWinGIS.Field ID = new MapWinGIS.Field();
                ID.Name = "ID";
                ID.Type = MapWinGIS.FieldType.INTEGER_FIELD;
                res     = sfOut.EditInsertField(ID, ref IDField, ICallBack);
                if (res != true)
                {
                    MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                }
            }



            MapWinGIS.Shape mwOutShape;
            // Loop through all the shapes in the polyline shapefile
            int shIndx = -1;

            for (int shp = 0; shp < mwPolyLine.NumShapes; shp++)
            {
                mwShape = mwPolyLine.get_Shape(shp);

                // By turning multi-part polylines into multiple linestrings, we avoid the annoying multi-part logic
                MultiLineString MLS = GeometryFactory.CreateMultiLineString(mwShape);

                for (int ls = 0; ls < MLS.NumGeometries; ls++)
                {
                    LineString lsSource = MLS.GeometryN[ls] as LineString;
                    for (int pt = 0; pt < lsSource.Coordinates.Count - 1; pt++)
                    {
                        Coordinate start = lsSource.Coordinates[pt];
                        Coordinate end   = lsSource.Coordinates[pt + 1];

                        // Crop the parts of each segment that do not overlap with the grid.
                        if (start.X < left)
                        {
                            if (end.X < left)
                            {
                                // this segment is outside the grid
                                continue;
                            }
                            // crop this segment to only the portion on the grid
                            start.X = left;
                        }
                        if (end.X < left)
                        {
                            // crop this segment to only the portion on the grid
                            end.X = left;
                        }
                        if (start.X > right)
                        {
                            if (end.X > right)
                            {
                                // this segment is outside the grid
                                continue;
                            }
                            // crop to grid
                            start.X = right;
                        }
                        if (end.X > right)
                        {
                            // crop to the grid
                            end.X = right;
                        }


                        double length   = Math.Sqrt((end.X - start.X) * (end.X - start.X) + (end.Y - start.Y) * (end.Y - start.Y));
                        int    NumSteps = (int)Math.Floor(length / dS);
                        double segDx    = (end.X - start.X) / NumSteps;
                        double segDy    = (end.Y - start.Y) / NumSteps;
                        mwOutShape = new MapWinGIS.Shape();
                        if (CrossSectionType == CrossSectionTypes.PolyLineWithZ)
                        {
                            mwOutShape.Create(MapWinGIS.ShpfileType.SHP_POLYLINEZ);
                        }

                        // step by dS and get the grid value at that point at each step
                        int p = 0;
                        for (int I = 0; I < NumSteps; I++)
                        {
                            int    row, col;
                            object Elev;
                            double X = start.X + segDx * I;
                            double Y = start.Y + segDy * I;
                            mwElevGrid.ProjToCell(X, Y, out col, out row);
                            Elev = mwElevGrid.get_Value(col, row);
                            MapWinGIS.Point pnt = new MapWinGIS.Point();
                            pnt.x = X;
                            pnt.y = Y;
                            pnt.Z = (double)Elev;
                            if (CrossSectionType == CrossSectionTypes.PointsWithZAndElevField)
                            {
                                p          = 0;
                                mwOutShape = new MapWinGIS.Shape();
                                mwOutShape.Create(MapWinGIS.ShpfileType.SHP_POINTZ);
                                res = mwOutShape.InsertPoint(pnt, ref p);
                                if (res == false)
                                {
                                    throw new ApplicationException(mwOutShape.get_ErrorMsg(mwOutShape.LastErrorCode));
                                }
                                res = sfOut.EditInsertShape(mwOutShape, ref shIndx);
                                if (res != true)
                                {
                                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                                }
                                res = sfOut.EditCellValue(IDField, shIndx, shIndx);
                                if (res != true)
                                {
                                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                                }
                                res = sfOut.EditCellValue(ElevField, shIndx, Elev);
                                if (res != true)
                                {
                                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                                }
                                shIndx++;
                            }
                            else
                            {
                                res = mwOutShape.InsertPoint(pnt, ref p);
                                p++;
                                if (res == false)
                                {
                                    throw new ApplicationException(mwOutShape.get_ErrorMsg(mwOutShape.LastErrorCode));
                                }
                            }
                        }
                        if (CrossSectionType == CrossSectionTypes.PolyLineWithZ)
                        {
                            if (mwOutShape.numPoints > 0)
                            {
                                res = sfOut.EditInsertShape(mwOutShape, ref shIndx);
                                if (res != true)
                                {
                                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                                }
                                res = sfOut.EditCellValue(IDField, shIndx, shIndx);
                                if (res != true)
                                {
                                    throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                                }
                                shIndx++;
                            }
                        }
                    }
                }
                Prog = Convert.ToInt32(shp * 100 / mwPolyLine.NumShapes);
                if (Prog > OldProg)
                {
                    MapWinUtility.Logger.Progress("Evaluating Cross Section..." + Prog.ToString() + "% Complete.", Prog, OldProg);
                    OldProg = Prog;
                }
            }
            res = sfOut.StopEditingShapes(true, true, ICallBack);
            if (res != true)
            {
                MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode));
                throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode));
            }
        }
Пример #18
0
        /// <summary>
        /// This is used by the Identity process to export all shapes intesecting all polygons passed in.
        /// Each identity polygon is used to select and clip input shapes. The new clipped shape is written
        /// to the result shapefile. The attribute fields from both input and identity shapefiles are copied
        /// to the result shapefile.
        /// This process uses a QuadTree index to speed up the selection of overlapping geometries.
        /// </summary>
        /// <param name="inputSF">The shapefile, of any geometry type, to be clipped and exported.</param>
        /// <param name="identitySF">The polygon shapefile used to clip the inputSF.</param>
        /// <param name="resultSF">The result shapefile that will contain the results.</param>
        /// <returns>False if an error occurs, true otherwise.</returns>
        public static bool ExportShapesWithPolygons(ref MapWinGIS.Shapefile inputSF, ref MapWinGIS.Shapefile identitySF, ref MapWinGIS.Shapefile resultSF)
        {
            try
            {
                // Boundary intersection test variables
                double xMin1, xMax1, yMin1, yMax1, zMin1, zMax1, xMin2, xMax2, yMin2, yMax2, zMin2, zMax2;

                // Build Quadtree index for inputSF
                MapWinGeoProc.NTS.Topology.Index.Quadtree.Quadtree myQuadTree = new MapWinGeoProc.NTS.Topology.Index.Quadtree.Quadtree();

                MapWinGIS.Shape currGeom;
                for (int i = 0; i < inputSF.NumShapes; i++)
                {
                    currGeom = inputSF.get_Shape(i);
                    currGeom.Extents.GetBounds(out xMin1, out yMin1, out zMin1, out xMax1, out yMax1, out zMax1);
                    Envelope myItemEnv = new Envelope(xMin1, xMax1, yMin1, yMax1);
                    myQuadTree.Insert(myItemEnv, i);
                }//end of looping through lines

                // Copy inputSf and identitySF fields to resultSF, renaming duplicate fields
                if (Globals.CopyFields(ref inputSF, ref resultSF) == false)
                {
                    return(false);
                }
                if (Globals.CopyFields(ref identitySF, ref resultSF, true) == false)
                {
                    return(false);
                }

                int             resultNumFields             = resultSF.NumFields;
                int             inputNumFields              = inputSF.NumFields;
                int             identityNumFields           = identitySF.NumFields;
                int             shpIndex                    = 0;
                Envelope        myQueryEnv                  = null;
                Geometry        queryPoly                   = null;
                Geometry        inputGeom                   = null;
                IGeometry       intersectGeom               = null;
                MapWinGIS.Shape identityShape               = null;
                MapWinGIS.Shape intersectShape              = null;
                IList           results                     = null;
                string          progressmessage             = "";
                int             inputShapesForIdentityShape = 0;

                // Loop through identitySF and get inputSF geometries that intersect
                for (int identityIndex = 0; identityIndex < identitySF.NumShapes; identityIndex++)
                {
                    identityShape = identitySF.get_Shape(identityIndex);
                    queryPoly     = NTS_Adapter.ShapeToGeometry(identityShape);
                    identityShape.Extents.GetBounds(out xMin2, out yMin2, out zMin2, out xMax2, out yMax2, out zMax2);
                    myQueryEnv = new Envelope(xMin2, xMax2, yMin2, yMax2);

                    //use quadtree index to find geometries that may intersect
                    results = myQuadTree.Query(myQueryEnv);
                    int intersectIndex = 0;
                    for (int i = 0; i < results.Count; i++)
                    {
                        intersectIndex = Convert.ToInt32(results[i]);                                                                                                                                                                          // Get input id from quadtree results
                        currGeom       = inputSF.get_Shape(intersectIndex);                                                                                                                                                                    // Get input geometry
                        inputGeom      = NTS_Adapter.ShapeToGeometry(currGeom);                                                                                                                                                                // Convert to NTS Geometry
                        for (int inputGoemIndex = 0; inputGoemIndex < inputGeom.NumGeometries; inputGoemIndex++)                                                                                                                               //use each part of the geometry
                        {
                            if (inputGeom.GetGeometryN(inputGoemIndex).Intersects(queryPoly))                                                                                                                                                  // check for intersection
                            {
                                intersectGeom = MapWinGeoProc.NTS.Topology.Operation.Overlay.OverlayOp.Overlay(queryPoly, inputGeom.GetGeometryN(inputGoemIndex), MapWinGeoProc.NTS.Topology.Operation.Overlay.SpatialFunctions.Intersection); // create intersect geometry
                                if (!intersectGeom.IsEmpty)
                                {
                                    for (int geomIndex = 0; geomIndex < intersectGeom.NumGeometries; geomIndex++)                                          // process each part of intersect result
                                    {
                                        if (inputGeom.GetGeometryN(inputGoemIndex).GetType().Name == intersectGeom.GetGeometryN(geomIndex).GetType().Name) // only used geometries of the same type as the input.
                                        {
                                            // Write shape geometry
                                            intersectShape = NTS_Adapter.GeometryToShape(intersectGeom.GetGeometryN(geomIndex));
                                            shpIndex       = resultSF.NumShapes;
                                            if (resultSF.EditInsertShape(intersectShape, ref shpIndex) == false)
                                            {
                                                gErrorMsg = string.Format("Problem inserting shape into result file: {0}, Input Id: {1}, IdentityId: {2}", resultSF.get_ErrorMsg(resultSF.LastErrorCode), intersectIndex, identityIndex);
                                                Debug.WriteLine(gErrorMsg);
                                                Error.SetErrorMsg(gErrorMsg);
                                                return(false);
                                            }
                                            inputShapesForIdentityShape++;
                                            intersectShape = null;
                                            //add the table values from input SF
                                            for (int j = 0; j <= inputNumFields - 1; j++)
                                            {
                                                if (resultSF.EditCellValue(j, shpIndex, inputSF.get_CellValue(j, intersectIndex)) == false)
                                                {
                                                    gErrorMsg = "Problem inserting value into DBF table: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                                                    Debug.WriteLine(gErrorMsg);
                                                    Error.SetErrorMsg(gErrorMsg);
                                                    return(false);
                                                }
                                            }//end of looping through table
                                            //add the table values from identity SF
                                            for (int j = 0; j <= identityNumFields - 1; j++)
                                            {
                                                if (resultSF.EditCellValue(j + inputNumFields, shpIndex, identitySF.get_CellValue(j, identityIndex)) == false)
                                                {
                                                    gErrorMsg = "Problem inserting value into DBF table: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                                                    Debug.WriteLine(gErrorMsg);
                                                    Error.SetErrorMsg(gErrorMsg);
                                                    return(false);
                                                }
                                            }//end of looping through table
                                        }
                                    }
                                }
                            }
                        }
                        inputGeom = null;
                    }
                    progressmessage = string.Format("{3}: Identity Index:{0}, Quadtree Results:{1}, Shapes added:{2}", identityIndex, results.Count, inputShapesForIdentityShape, DateTime.Now.ToShortTimeString());
                    results.Clear();
                    Debug.WriteLine(progressmessage);
                    inputShapesForIdentityShape = 0;
                    resultSF.StopEditingShapes(true, true, null);
                    resultSF.StartEditingShapes(true, null);
                }
                return(resultSF.NumShapes > 0);
            }
            catch (Exception E)
            {
                System.Windows.Forms.MessageBox.Show(E.ToString());
                return(false);
            }
        }
Пример #19
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            double tolerance = 0;

            if (!double.TryParse(txtTolerance.Text, out tolerance))
            {
                MapWinUtility.Logger.Message("Please enter only numbers in the distance field.", "Enter Only Numbers", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, DialogResult.OK);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            prgShape.Visible = true;
            prgPoint.Visible = true;

            sf.StartEditingShapes(true, null);
            long totalRemoved = 0;
            long fromShapes   = 0;
            int  numPts;

            System.Collections.ArrayList removeList = new System.Collections.ArrayList();

            if (sf.NumShapes > 0)
            {
                prgShape.Maximum = sf.NumShapes;

                for (int z = 0; z < sf.NumShapes; z++)
                {
                    MapWinGIS.Shape shp = sf.get_Shape(z);
                    if (z < 100 || z % 5 == 0)
                    {
                        prgShape.Value = z;
                        this.Refresh();
                    }
                    Application.DoEvents();

                    numPts = shp.numPoints;
                    if (numPts > 0)
                    {
                        prgPoint.Maximum = numPts;

                        for (int i = numPts - 1; i > 0; i--) // 0 never needs to actually be hit, inner loop will compare against all zeros
                        {
                            if (i % 5 == 0)
                            {
                                prgPoint.Value = numPts - i;
                                this.Refresh();
                            }

                            for (int j = i - 1; j >= 0; j--)
                            {
                                if (Math.Sqrt(Math.Pow(shp.get_Point(i).x - shp.get_Point(j).x, 2) + Math.Pow(shp.get_Point(i).y - shp.get_Point(j).y, 2)) < tolerance)
                                {
                                    // Make sure that !(i == numPts - 1 && j == 0) -- polygon completion point
                                    if (!removeList.Contains(i) && !(i == numPts - 1 && j == 0))
                                    {
                                        removeList.Add(i);
                                    }
                                }
                            }
                        }
                    }

                    if (removeList.Count > 0)
                    {
                        if (removeList.Count >= shp.numPoints - 1)
                        {
                            // Probably not a good thing.....
                            MapWinUtility.Logger.Message("Aborting: Proceeding will remove all points from one or more shapes. The distance may need to be smaller, particularly for unprojected (latitute and longitude) coordinate systems.", "Aborting -- All Points Would Be Removed", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK);
                            sf.StopEditingShapes(false, true, null);
                            this.Cursor      = Cursors.Default;
                            prgPoint.Value   = 0;
                            prgShape.Value   = 0;
                            prgPoint.Visible = false;
                            prgShape.Visible = false;
                            this.Cursor      = Cursors.Default;
                            return;
                        }

                        totalRemoved += removeList.Count;
                        fromShapes++;

                        while (removeList.Count > 0)
                        {
                            for (int part = 0; part < shp.NumParts; part++)
                            {
                                if (shp.get_Part(part) >= (int)removeList[0])
                                {
                                    shp.set_Part(part, shp.get_Part(part) - 1);
                                }
                            }
                            shp.DeletePoint((int)removeList[0]);
                            removeList.RemoveAt(0);
                        }

                        // If this is a polygon and there are now less than 3 shapes, panic
                        if ((shp.ShapeType == MapWinGIS.ShpfileType.SHP_POLYGON || shp.ShapeType == MapWinGIS.ShpfileType.SHP_POLYGONZ || shp.ShapeType == MapWinGIS.ShpfileType.SHP_POLYGONM) && shp.numPoints < 3)
                        {
                            // Probably not a good thing.....
                            MapWinUtility.Logger.Message("Aborting: Proceeding will leave less than 3 points in a polygon. The distance may need to be smaller, particularly for unprojected (latitute and longitude) coordinate systems.", "Aborting -- Polygons Would Be Destroyed", MessageBoxButtons.OK, MessageBoxIcon.Error, DialogResult.OK);
                            sf.StopEditingShapes(false, true, null);
                            this.Cursor      = Cursors.Default;
                            prgPoint.Value   = 0;
                            prgShape.Value   = 0;
                            prgPoint.Visible = false;
                            prgShape.Visible = false;
                            this.Cursor      = Cursors.Default;
                            return;
                        }

                        // If the first and last points are not the same now, reclose it
                        if (shp.get_Point(0).x != shp.get_Point(shp.numPoints - 1).x || shp.get_Point(0).y != shp.get_Point(shp.numPoints - 1).y)
                        {
                            MapWinGIS.Point pnt = new MapWinGIS.Point();
                            pnt.x = shp.get_Point(0).x;
                            pnt.y = shp.get_Point(0).y;
                            pnt.Z = shp.get_Point(0).Z;
                            int ptidx = shp.numPoints;
                            shp.InsertPoint(pnt, ref ptidx);
                        }
                    }
                }
            }

            prgPoint.Value = prgPoint.Maximum;
            prgShape.Value = prgShape.Maximum;

            g.CreateUndoPoint();

            sf.StopEditingShapes(true, true, null);

            this.Cursor = Cursors.Default;

            if (totalRemoved > 0)
            {
                MapWinUtility.Logger.Message("There were " + totalRemoved.ToString() + " points removed from " + fromShapes.ToString() + " shapes.", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK);
            }
            else
            {
                MapWinUtility.Logger.Message("Finished -- no extra points needed to be removed.", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information, DialogResult.OK);
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Пример #20
0
        /// <summary>
        /// Converts a list of 3d-points to a point shapefile with z-value field.
        /// This function creates a new shapefile. The shapefile has two fields:
        /// a 'MWShapeId' field and a field which contains the z-value.
        /// </summary>
        /// <param name="ShpFileName">Name of the resulting point shapefile</param>
        /// <param name="ZFieldName">Name of the z-field in the shapefile</param>
        public void ToShapefile(string ShpFileName, string ZFieldName)
        {
            MapWinGIS.Shapefile newSF = new MapWinGIS.Shapefile();
            try
            {
                Hashtable FieldIndices = new Hashtable();

                MapWinGIS.ShpfileType sftype;
                sftype = MapWinGIS.ShpfileType.SHP_POINT;
                int fldIdx = 0;

                // if shapefile exists - open it and clear all shapes
                if (System.IO.File.Exists(ShpFileName))
                {
                    newSF.Open(ShpFileName, null);
                    newSF.StartEditingShapes(true, null);
                    newSF.EditClear();
                }
                else //else, create a new shapefile
                {
                    if (!newSF.CreateNew(ShpFileName, sftype))
                    {
                        throw new InvalidOperationException
                                  ("Error creating shapefile " + newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    newSF.StartEditingShapes(true, null);
                }

                //check existing fields:
                for (int i = 0; i < newSF.NumFields; ++i)
                {
                    MapWinGIS.Field fl = newSF.get_Field(i);
                    if (fl.Name == "MWShapeID")
                    {
                        FieldIndices.Add("MWShapeID", i);
                    }
                    if (fl.Name == ZFieldName)
                    {
                        FieldIndices.Add(ZFieldName, i);
                    }
                }

                //Add the fields:
                if (!FieldIndices.ContainsKey("MWShapeID"))
                {
                    //First an ID field
                    MapWinGIS.Field idFld = new MapWinGIS.Field();
                    idFld.Name = "MWShapeID";
                    idFld.Type = MapWinGIS.FieldType.INTEGER_FIELD;
                    fldIdx     = newSF.NumFields;

                    if (newSF.EditInsertField(idFld, ref fldIdx, null) == false)
                    {
                        throw new InvalidOperationException("error inserting field " +
                                                            newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    FieldIndices.Add("MWShapeID", fldIdx);
                }

                if (!FieldIndices.ContainsKey(ZFieldName))
                {
                    //Second add a Z-field
                    MapWinGIS.Field zFld = new MapWinGIS.Field();
                    zFld.Name = "Z";
                    zFld.Type = MapWinGIS.FieldType.DOUBLE_FIELD;
                    fldIdx    = newSF.NumFields;

                    if (newSF.EditInsertField(zFld, ref fldIdx, null) == false)
                    {
                        throw new InvalidOperationException("error inserting field " +
                                                            newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    FieldIndices.Add("Z", fldIdx);
                }

                foreach (ICoordinate pt in _points)
                {
                    //first, add a point shape (geometry)
                    MapWinGIS.Shape newShp = new MapWinGIS.Shape();
                    newShp.Create(MapWinGIS.ShpfileType.SHP_POINT);
                    MapWinGIS.Point newPt = new MapWinGIS.Point();
                    newPt.x = pt.X;
                    newPt.y = pt.Y;
                    int ptIdx = 0;
                    newShp.InsertPoint(newPt, ref ptIdx);
                    int shpIdx = newSF.NumShapes;
                    newSF.EditInsertShape(newShp, ref shpIdx);

                    //second add the z-value
                    newSF.EditCellValue(fldIdx, shpIdx, pt.Z);
                }
            }
            finally
            {
                //finally stop editing and close the shapefile
                newSF.StopEditingShapes(true, true, null);
                if (newSF.Close() == false)
                {
                    throw new InvalidOperationException("error closing shapefile " +
                                                        newSF.get_ErrorMsg(newSF.LastErrorCode));
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Generalization of polyline
        /// shapefiles using the Douglas-Peucker line simplification
        /// algorithm. This method will output a line shapefile.
        /// </summary>
        /// <param name="inFileName">Input shapefile</param>
        /// <param name="outFileName">Output shapefile</param>
        /// <param name="tolerance">tolerance parameter -
        /// specfies the maximum allowed distance between original polyline
        /// and simplified polyline</param>
        /// <param name="cback">Use this parameter for reporting progress. Set to null if not needed</param>
        public static void Generalize(string inFileName, string outFileName, double tolerance, MapWinGIS.ICallback cback)
        {
            MapWinGIS.Shapefile oldSF = new MapWinGIS.Shapefile();
            if (!oldSF.Open(inFileName, null))
            {
                throw new ArgumentException(string.Format("Shapefile {0} could not be opened. Error: {1}",
                                                          inFileName, oldSF.get_ErrorMsg(oldSF.LastErrorCode)));
            }

            //Check if it's a line shapefile
            if (!(oldSF.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINE ||
                  oldSF.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINEM ||
                  oldSF.ShapefileType == MapWinGIS.ShpfileType.SHP_POLYLINEZ))
            {
                throw new ArgumentException(string.Format("Shapefile {0} must be a polyline shapefile.", inFileName));
            }

            int numShapes = oldSF.NumShapes;
            int numFields = oldSF.NumFields;

            //create a new output shapefile
            MapWinGIS.Shapefile   newSF  = new MapWinGIS.Shapefile();
            MapWinGIS.ShpfileType sftype = MapWinGIS.ShpfileType.SHP_POLYLINE;

            // if shapefile exists - open it and clear all shapes
            if (System.IO.File.Exists(outFileName))
            {
                try
                {
                    //TODO: ask for overwriting..
                    bool deleted = MapWinGeoProc.DataManagement.DeleteShapefile(ref outFileName);
                }
                finally
                {
                }
            }

            if (!newSF.CreateNew(outFileName, sftype))
            {
                throw new InvalidOperationException
                          ("Error creating shapefile " + outFileName + " " + newSF.get_ErrorMsg(newSF.LastErrorCode));
            }
            newSF.StartEditingShapes(true, cback);

            //Copy all fields
            if (!Globals.CopyFields(ref oldSF, ref newSF))
            {
                throw new InvalidOperationException(string.Format("Error copying fields from {0} to {1}",
                                                                  oldSF.Filename, newSF.Filename));
            }

            int newShapeIndex = 0;

            for (int shpIdx = 0; shpIdx < numShapes; ++shpIdx)
            {
                MapWinGIS.Shape shp = oldSF.get_Shape(shpIdx);

                // convert each part of the polyline shape to a 'geometry' object
                Geometry geom = MapWinGeoProc.NTS_Adapter.ShapeToGeometry(shp);
                for (int partIdx = 0; partIdx < geom.NumGeometries; ++partIdx)
                {
                    Geometry geomPart = (Geometry)geom.GetGeometryN(partIdx);

                    //do the simplification
                    ICoordinate[] oldCoords = geomPart.Coordinates;
                    DouglasPeuckerLineSimplifier simplifier = new DouglasPeuckerLineSimplifier(oldCoords);
                    simplifier.DistanceTolerance = tolerance;
                    ICoordinate[] newCoords = simplifier.Simplify();

                    //convert the coordinates back to a geometry
                    Geometry newGeom = new LineString(newCoords);

                    //convert the geometry back to a shape
                    MapWinGIS.Shape newShape = MapWinGeoProc.NTS_Adapter.GeometryToShape(newGeom);

                    //add the shape to the new shapefile
                    newShapeIndex = newSF.NumShapes;
                    if (newSF.EditInsertShape(newShape, ref newShapeIndex) == false)
                    {
                        throw new InvalidOperationException("Error inserting shape: " +
                                                            newSF.get_ErrorMsg(newSF.LastErrorCode));
                    }
                    //add attribute values
                    for (int fldIdx = 0; fldIdx < numFields; ++fldIdx)
                    {
                        object val = oldSF.get_CellValue(fldIdx, shpIdx);
                        if (newSF.EditCellValue(fldIdx, newSF.NumShapes - 1, val) == false)
                        {
                            throw new InvalidOperationException("Error editing cell value: " +
                                                                newSF.get_ErrorMsg(newSF.LastErrorCode));
                        }
                    }
                }
            }
            //close the old shapefile
            oldSF.Close();

            //stop editing and close the new shapefile
            newSF.StopEditingShapes(true, true, cback);
            newSF.Close();
        }