Esempio n. 1
0
        private void btnLabel_Click(object sender, EventArgs e)
        {
            //Define a string to store the label of the feature
            string myLabel;
            //define two double variables to use as a coordinates for label postion
            double x, y;

            //Use a loop to read the cell value that use as a lable and set the label on the map
            for (int i = 0; i < myShapefile.NumShapes - 1; i++)
            {
                //assign the value of the cells of the field number zero to the label
                myLabel = System.Convert.ToString(
                    myShapefile.get_CellValue(0, i));
                //Calculate the x position for the label
                x = myShapefile.get_Shape(i).Extents.xMin +
                    (myShapefile.get_Shape(i).Extents.xMax - myShapefile.get_Shape(i).Extents.xMin) / 2;
                //Calculate the y postion for the label
                y = myShapefile.get_Shape(i).Extents.yMin +
                    (myShapefile.get_Shape(i).Extents.yMax - myShapefile.get_Shape(i).Extents.yMin) / 2;
                //add the label on the map
                axMap1.AddLabel(
                    intHandler,                                 //Layer handler
                    myLabel,                                    //Label string
                    (UInt32)(System.Drawing.ColorTranslator.ToOle
                                 (System.Drawing.Color.Black)), //Color of the label
                    x, y,                                       //Position of the lable
                    MapWinGIS.tkHJustification.hjCenter         //Justification of the label
                    );
            }
        }
Esempio n. 2
0
        // Add the shapes one by one
        private bool AddShapes(MapWinGIS.Shapefile inSF, out string errorMessage)
        {
            errorMessage = "No Error.";
            int outShp = _outSF.NumShapes;

            // Add all the shapes and attributes from the first shapefile
            for (int shp = 0; shp < inSF.NumShapes; shp++)
            {
                MapWinGIS.Shape shape = inSF.get_Shape(shp);
                _outSF.EditInsertShape(shape, ref outShp);
                for (int fld = 0; fld < inSF.NumFields; fld++)
                {
                    string name  = inSF.get_Field(fld).Name;
                    int    index = IndexOf(name);
                    if (index == -1)
                    {
                        errorMessage = "Could not find a field in the output shapefile: [" + name + "]";
                        return(false);
                    }
                    if (_outSF.EditCellValue(index, outShp, inSF.get_CellValue(fld, shp)) == false)
                    {
                        errorMessage = _outSF.get_ErrorMsg(_outSF.LastErrorCode);
                        return(false);
                    }
                }
                outShp++;
            }
            return(true);
        }
Esempio n. 3
0
        /// <summary>
        /// Exports the shapes from the inputSF which fall within the given polygon, saving to the resultSF provided.
        /// </summary>
        /// <returns>False if an error occurs, true otherwise.</returns>
        public static bool SelectPointsWithPolygon(ref MapWinGIS.Shapefile inputSF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool SkipMWShapeID)
        {
            MapWinGIS.Utils utils     = new MapWinGIS.UtilsClass();
            int             numPoints = inputSF.NumShapes;
            int             shpIndex  = 0;

            if (Globals.CopyFields(ref inputSF, ref resultSF) == false)
            {
                return(false);
            }

            for (int i = 0; i <= numPoints - 1; i++)
            {
                MapWinGIS.Point currPt = new MapWinGIS.PointClass();
                currPt = inputSF.QuickPoint(i, 0);
                if (utils.PointInPolygon(polygon, currPt))
                {
                    shpIndex = resultSF.NumShapes;
                    if (resultSF.EditInsertShape(inputSF.get_Shape(i), ref shpIndex) == false)
                    {
                        gErrorMsg = "Problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                        Debug.WriteLine(gErrorMsg);
                        Error.SetErrorMsg(gErrorMsg);
                        return(false);
                    }
                    //add the table values
                    int numFields = resultSF.NumFields;
                    for (int j = 0; j <= numFields - 1; j++)
                    {
                        if (resultSF.EditCellValue(j, shpIndex, inputSF.get_CellValue(j, i)) == 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
                }        //end of checking if point is inside polygon
            }            //end of looping through points

            if (resultSF.NumShapes > 0)
            {
                if (resultSF.NumFields == 0 || !SkipMWShapeID)
                {
                    //add the ID field and values
                    if (Globals.DoInsertIDs(ref resultSF) == false)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private static void CachePointsBrute(string InPointsPath, int InValueFieldIndex, out List <InterpolationPoint> PointsCache, out string Projection, out string ProjectionUnits, out MapWinGIS.Extents PointsExtents, MapWinGIS.ICallback callback)
        {
            int newperc = 0, oldperc = 0;

            MapWinGIS.Shapefile points = new MapWinGIS.Shapefile();
            points.Open(InPointsPath, null);

            PointsExtents = points.Extents;
            Projection    = points.Projection;
            if (Projection != null)
            {
                ProjectionUnits = Projection.Substring(Projection.IndexOf("units=") + 6);
                ProjectionUnits = ProjectionUnits.Substring(0, ProjectionUnits.IndexOf("+")).Trim();
            }
            else
            {
                double tmpX   = points.Extents.xMax;
                string tmpstr = Math.Floor(tmpX).ToString();

                if (tmpstr.Length > 4)
                {
                    ProjectionUnits = "";
                }
                else
                {
                    ProjectionUnits = "lat/long";
                }
            }

            PointsCache = new List <InterpolationPoint>();
            InterpolationPoint pt;

            MapWinGIS.Point currpt;
            int             ns         = points.NumShapes;

            for (int i = 0; i < ns; i++)
            {
                newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(ns)) * 100);
                if ((newperc > oldperc))
                {
                    if (callback != null)
                    {
                        callback.Progress("Status", newperc, "IDW Caching " + i.ToString());
                    }
                    oldperc = newperc;
                }

                currpt = points.get_Shape(i).get_Point(0);

                pt = new InterpolationPoint(currpt.x, currpt.y, double.Parse(points.get_CellValue(InValueFieldIndex, i).ToString()), 0);
                PointsCache.Add(pt);
            }
            points.Close();
        }
Esempio n. 5
0
        /// <summary>
        /// Exports the shapes from the inputSF which fall within the given polygon, saving to the resultSF provided.
        /// </summary>
        /// <returns>False if an error occurs, true otherwise.</returns>
        public static bool SelectPolygonsWithPolygon(ref MapWinGIS.Shapefile inputSF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool SkipMWShapeID)
        {
            MapWinUtility.Logger.Dbg("SelectPolygonsWithPolygon(inputSF: " + Macro.ParamName(inputSF) + ",\n" +
                                     "                          polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                          resultSF: ref " + Macro.ParamName(resultSF) + ",\n" +
                                     "                          SkipMWShapeID: " + SkipMWShapeID.ToString() + ")");
            int numShapes = inputSF.NumShapes;
            int shpIndex  = 0;

            if (Globals.CopyFields(ref inputSF, ref resultSF) == false)
            {
                return(false);
            }

            for (int i = 0; i <= numShapes - 1; i++)
            {
                MapWinGIS.Shape currShape = new MapWinGIS.ShapeClass();
                currShape = inputSF.get_Shape(i);
                bool boundsIntersect = Globals.CheckBounds(ref currShape, ref polygon);
                if (boundsIntersect)
                {
                    //check that actual intersection occurs
                    MapWinGIS.Shape intersectShp = new MapWinGIS.ShapeClass();
                    intersectShp = SpatialOperations.Intersection(currShape, polygon);
                    if (intersectShp != null && intersectShp.numPoints > 0)
                    {
                        //shape has at least a small portion inside polygon
                        shpIndex = resultSF.NumShapes;
                        if (resultSF.EditInsertShape(currShape, ref shpIndex) == false)
                        {
                            gErrorMsg = "Problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                            Debug.WriteLine(gErrorMsg);
                            Error.SetErrorMsg(gErrorMsg);
                            MapWinUtility.Logger.Dbg(gErrorMsg);
                            return(false);
                        }
                        //add the table values
                        int numFields = resultSF.NumFields;
                        for (int j = 0; j <= numFields - 1; j++)
                        {
                            if (resultSF.EditCellValue(j, shpIndex, inputSF.get_CellValue(j, i)) == false)
                            {
                                gErrorMsg = "Problem inserting value into DBF table: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                                Debug.WriteLine(gErrorMsg);
                                Error.SetErrorMsg(gErrorMsg);
                                MapWinUtility.Logger.Dbg(gErrorMsg);
                                return(false);
                            }
                        } //end of looping through table
                    }     //end of checking for intersection
                }         //end of checking bounds
            }             //end of looping through shapes
            if (resultSF.NumShapes > 0)
            {
                if (resultSF.NumFields == 0 || !SkipMWShapeID)
                {
                    //add the ID field and values
                    if (Globals.DoInsertIDs(ref resultSF) == false)
                    {
                        return(false);
                    }
                }
                MapWinUtility.Logger.Dbg("Finished SelectPolygonsWithPolygon");
                return(true);
            }
            else
            {
                MapWinUtility.Logger.Dbg("Finished SelectPolygonsWithPolygon");
                return(false);
            }
        }
Esempio n. 6
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);
            }
        }
Esempio n. 7
0
        private void MapWindow_Load(object sender, EventArgs e)
        {
            int intHandler1;

            MapWinGIS.Shapefile shapefile1 = new MapWinGIS.Shapefile();
            shapefile1.Open("..\\..\\shapefiles\\Form.shp");
            intHandler1 = axMap1.AddLayer(shapefile1, true);

            int intHandler2;

            MapWinGIS.Shapefile shapefile2 = new MapWinGIS.Shapefile();
            shapefile2.Open("..\\..\\shapefiles\\gang.shp");
            intHandler2 = axMap1.AddLayer(shapefile2, true);

            int intHandler7;

            MapWinGIS.Shapefile shapefile7 = new MapWinGIS.Shapefile();
            shapefile7.Open("..\\..\\shapefiles\\Stairs.shp");
            intHandler7 = axMap1.AddLayer(shapefile7, true);

            int intHandler6;

            MapWinGIS.Shapefile shapefile6 = new MapWinGIS.Shapefile();
            shapefile6.Open("..\\..\\shapefiles\\Shape .shp");
            string myLabel;
            //define two double variables to use as a coordinates for label position
            double x, y;

            for (int i = 0; i < shapefile6.NumShapes - 1; i++)
            {
                //assign the value of the cells of the field number zero to the label
                myLabel = System.Convert.ToString(
                    shapefile6.get_CellValue(1, i));
                //Calculate the x position for the label
                x = shapefile6.get_Shape(i).Extents.xMin +
                    (shapefile6.get_Shape(i).Extents.xMax -
                     shapefile6.get_Shape(i).Extents.xMin) / 2;
                //Calculate the y position for the label
                y = shapefile6.get_Shape(i).Extents.yMin +
                    (shapefile6.get_Shape(i).Extents.yMax -
                     shapefile6.get_Shape(i).Extents.yMin) / 2;

                shapefile6.Labels.AddLabel(myLabel, x, y, 0, -1);
            }
            intHandler6 = axMap1.AddLayer(shapefile6, true);

            int intHandler3;

            MapWinGIS.Shapefile shapefile3 = new MapWinGIS.Shapefile();
            shapefile3.Open("..\\..\\shapefiles\\Indgang.shp");
            intHandler3 = axMap1.AddLayer(shapefile3, true);

            int intHandler8;

            MapWinGIS.Shapefile shapefile8 = new MapWinGIS.Shapefile();
            shapefile8.Open("..\\..\\shapefiles\\WC.shp");
            intHandler8 = axMap1.AddLayer(shapefile8, true);

            int intHandler4;

            MapWinGIS.Shapefile shapefile4 = new MapWinGIS.Shapefile();
            shapefile4.Open("..\\..\\shapefiles\\navlines.shp");
            intHandler4 = axMap1.AddLayer(shapefile4, false);

            int intHandler5;

            MapWinGIS.Shapefile shapefile5 = new MapWinGIS.Shapefile();
            shapefile5.Open("..\\..\\shapefiles\\navnodes.shp");
            intHandler5 = axMap1.AddLayer(shapefile5, true);

            if (File.Exists("..\\..\\devloc.txt"))
            {
                SetLocationMap.Loc = Convert.ToInt32(File.ReadAllText("..\\..\\devloc.txt"));
            }

            for (int i = 0; i < shapefile4.NumShapes; i++)
            {
                if (i == SetLocationMap.Loc)
                {
                    shapefile5.set_ShapeIsHidden(i, false);
                }
                else
                {
                    shapefile5.set_ShapeIsHidden(i, true);
                }
            }
        }
        /// <summary>
        /// Returns an in-memory shapefile of points from the input shapefile that fall within the polygon.
        /// </summary>
        /// <param name="pointSF">Full path to the point shapefile.</param>
        /// <param name="polygon">The polygon used for clipping the point shapefile.</param>
        /// <param name="result">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 MapWinGIS.Shapefile pointSF, ref MapWinGIS.Shape polygon, out MapWinGIS.Shapefile result, bool copyAttributes)
        {
            MapWinUtility.Logger.Dbg("ClipPointSFWithPolygon(pointSF: " + Macro.ParamName(pointSF) + ",\n" +
                                     "                       polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                       result: out, \n" +
                                     "                       copyAttributes: " + copyAttributes.ToString() + ",\n");
            MapWinGIS.Shapefile resultSF = new MapWinGIS.ShapefileClass();
            int shpIndex = 0;             //all new shapes will be placed at the beginning of the shapefile

            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)
            {
                string tempPath = System.IO.Path.GetTempPath() + "resultSF.shp";
                DataManagement.DeleteShapefile(ref tempPath);
                string tmpName;
                //create the result shapeFile if it does not already exist
                //if(resultSF.CreateNew(tempPath, sfType) == false)
                //{
                //    gErrorMsg = "Problem creating the result shapeFile: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                //    Debug.WriteLine(gErrorMsg);
                //    MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                //    result = resultSF;
                //    return false;
                //}
                //CDM 8/4/2006 resultSF.CreateNew(resultSFPath, sfType);
                Globals.PrepareResultSF(ref tempPath, ref resultSF, sfType);

                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;
                        resultSF.EditInsertField(tmpField, ref f, null);
                    }
                }

                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));
                            }
                        }
                    }
                }
            }
            else
            {
                gErrorMsg = "The shapefile is of the wrong type. Should be of type Point.";
                Debug.WriteLine(gErrorMsg);
                MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                result = resultSF;
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }
            result = resultSF;
            MapWinUtility.Logger.Dbg("Finished ClipPointSFWithPolygon");
            return(true);
        }
Esempio n. 9
0
        /// <summary>
        /// Removes points from the point shapefile that lie within the polygon.
        /// </summary>
        /// <param name="pointSF">The point shapefile.</param>
        /// <param name="polygon">The erase polygon.</param>
        /// <param name="resultSF">The resulting file with points removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ErasePointSFWithPoly(ref MapWinGIS.Shapefile pointSF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("ErasePointSFWithPoly(pointSF: " + Macro.ParamName(pointSF) + "\n, " +
                                     "                     polygon: " + Macro.ParamName(polygon) + "\n, " +
                                     "                     resultSF: " + Macro.ParamName(resultSF) + "\n, " +
                                     "                     CopyAttributes: " + CopyAttributes.ToString() + ")");

            if (pointSF == null || polygon == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= pointSF.NumFields - 1; f++)
                {
                    tmpField      = new MapWinGIS.Field();
                    currField     = pointSF.get_Field(f);
                    tmpName       = currField.Name;
                    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);
                }
            }

            int numPts   = pointSF.NumShapes;
            int numParts = polygon.NumParts;

            if (numParts == 0)
            {
                numParts = 1;
            }
            int shpIndex = 0;

            Globals.Vertex[][] vertArray = new Globals.Vertex[numParts][];
            Globals.ConvertPolyToVertexArray(ref polygon, out vertArray);

            for (int i = 0; i <= numPts - 1; i++)
            {
                MapWinGIS.Point currPt = new MapWinGIS.PointClass();
                currPt = pointSF.QuickPoint(i, 0);
                double currX = currPt.x;
                double currY = currPt.y;
                if (Utils.PointInPoly(ref vertArray, currX, currY) == false)
                {
                    shpIndex = resultSF.NumShapes;
                    if (resultSF.EditInsertShape(pointSF.get_Shape(i), ref shpIndex) == false)
                    {
                        gErrorMsg = "ErasePointSF: problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                        Debug.WriteLine(gErrorMsg);
                        Error.SetErrorMsg(gErrorMsg);
                        MapWinUtility.Logger.Dbg(gErrorMsg);
                        return(false);
                    }
                    if (CopyAttributes)
                    {
                        for (int f = 0; f <= pointSF.NumFields - 1; f++)
                        {
                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, pointSF.get_CellValue(f, i));
                        }
                    }
                }
            }
            MapWinUtility.Logger.Dbg("Finished ErasePointSFWithPoly");
            return(true);
        }
Esempio n. 10
0
        /// <summary>
        /// Erases the portions of the polygon shapefile that are within the polygon shape.
        /// </summary>
        /// <param name="polySF">The polygon shapefile.</param>
        /// <param name="polygon">The erase polygon.</param>
        /// <param name="resultSF">The resulting shapefile, with portions removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes or not.</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ErasePolySFWithPoly(ref MapWinGIS.Shapefile polySF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("ErasePolySFWithPoly(polySF: " + Macro.ParamName(polySF) + ",\n" +
                                     "                    polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                    resultSF: " + Macro.ParamName(resultSF) + "\n" +
                                     "                    CopyAttributes: " + CopyAttributes.ToString());
            if (polySF == null || polygon == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                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;
                    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);
                }
            }

            int numShapes = polySF.NumShapes;
            int shpIndex  = 0;

            for (int i = 0; i <= numShapes - 1; i++)
            {
                MapWinGIS.Shape currShape = new MapWinGIS.Shape();
                MapWinGIS.Shape resultShp = new MapWinGIS.Shape();

                currShape = polySF.get_Shape(i);

                //if bounds intersect, then check if all polygon points are inside the currShape
                if (Globals.CheckBounds(ref currShape, ref polygon))
                {
                    int  numPts    = polygon.numPoints;
                    bool allInside = true;
                    int  numParts  = currShape.NumParts;
                    if (numParts == 0)
                    {
                        numParts = 1;
                    }
                    Globals.Vertex[][] vertArray = new Globals.Vertex[numParts][];
                    Globals.ConvertPolyToVertexArray(ref currShape, out vertArray);
                    for (int j = 0; j <= numPts - 1; j++)
                    {
                        double x = polygon.get_Point(j).x;
                        double y = polygon.get_Point(j).y;
                        if (Utils.PointInPoly(ref vertArray, x, y) == false)
                        {
                            allInside = false;
                            break;
                        }
                    }

                    if (allInside == true)
                    {
                        resultShp = new MapWinGIS.ShapeClass();
                        resultShp.Create(polygon.ShapeType);
                        //we want the symmetric difference of these two shapes
                        //which should leave us with a hole where the erase polygon was in the currShape
                        resultShp = SpatialOperations.SymmetricDifference(polygon, currShape);
                    }
                    else
                    {
                        //erase overlapping section and add result to the file.
                        MapWinGIS.Shape intersect = new MapWinGIS.ShapeClass();
                        intersect.ShapeType = polygon.ShapeType;
                        intersect           = SpatialOperations.Intersection(polygon, currShape);
                        if (intersect.numPoints > 0)
                        {
                            //there might be parts in the difference result that do not belong,
                            //perform an intersection operation with currShape to remove them.
                            MapWinGIS.Shape diff = new MapWinGIS.ShapeClass();
                            diff.ShapeType = polygon.ShapeType;
                            //diff = SpatialOperations.SymmetricDifference(intersect, currShape);
                            diff = SpatialOperations.Difference(currShape, polygon);
                            int numPoints = diff.numPoints;
                            if (numPoints > 0)
                            {
                                resultShp = diff;
                            }                    //difference operation successful
                        }                        //intersect operation successful
                        else
                        {
                            //no intersection, shapes do not collide
                            resultShp = currShape;
                        }
                    }                    //all points of erase polygon are not inside currShape

                    if (resultShp.numPoints > 0)
                    {
                        shpIndex = resultSF.NumShapes;
                        if (resultSF.EditInsertShape(resultShp, ref shpIndex) == false)
                        {
                            gErrorMsg = "ErasePolySF: problem inserting shape into result file: " + 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, shpIndex, polySF.get_CellValue(f, i));
                            }
                        }
                    }
                }                //end of if bounds intersect
                else
                {
                    //the erase object does not intersect with the current polygon,
                    //add current polygon to resultSF in unchanged form
                    shpIndex = resultSF.NumShapes;
                    if (resultSF.EditInsertShape(currShape, ref shpIndex) == false)
                    {
                        gErrorMsg = "ErasePolySF: problem inserting shape into result file: " + 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, shpIndex, polySF.get_CellValue(f, i));
                        }
                    }
                }
            }            //end of looping through shapes in shapefile
            MapWinUtility.Logger.Dbg("Finished ErasePolySFWithPoly");
            return(true);
        }
        /// <summary>
        /// Returns the portions of the polygons in polySF that lie within polygon as a
        /// new shapefile of polygons: resultPolySF.
        /// </summary>
        /// <param name="polySF">The shapefile of polygons that are to be clipped.</param>
        /// <param name="polygon">The polygon used for clipping.</param>
        /// <param name="resultPolySF">The result shapefile for the resulting polygons to be saved (in-memory).</param>
        /// <param name="copyAttributes">True if copying attrs</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool ClipPolygonSFWithPolygon(ref MapWinGIS.Shapefile polySF, ref MapWinGIS.Shape polygon, out MapWinGIS.Shapefile resultPolySF, bool copyAttributes)
        {
            MapWinUtility.Logger.Dbg("ClipPolygonSFWithPolygon(polySF: " + Macro.ParamName(polySF) + ",\n" +
                                     "                         polygon: " + Macro.ParamName(polygon) + ",\n" +
                                     "                         resultPolySF: out,\n" +
                                     "                         copyAttributes: " + copyAttributes.ToString() + "\n");

            MapWinGIS.Shapefile   resultSF = new MapWinGIS.ShapefileClass();
            MapWinGIS.ShpfileType sfType   = polySF.ShapefileType;
            string tempPath = System.IO.Path.GetTempPath() + "resultSF.shp";

            DataManagement.DeleteShapefile(ref tempPath);
            string tmpName;

            Globals.PrepareResultSF(ref tempPath, ref resultSF, sfType, copyAttributes);

            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);
                }
            }

            int shapeIndex = 0;            //insert new shapes at the beginning of the shapefile

            if (polySF.NumShapes != 0 && polygon.numPoints != 0 && (sfType == MapWinGIS.ShpfileType.SHP_POLYGON || sfType == MapWinGIS.ShpfileType.SHP_POLYGONM || sfType == MapWinGIS.ShpfileType.SHP_POLYGONZ))
            {
                MapWinGIS.Shape resultShape     = new MapWinGIS.ShapeClass();
                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 intersection
                        resultShape = SpatialOperations.Intersection(polySF.get_Shape(i), 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);
                                MapWinGeoProc.Error.SetErrorMsg(gErrorMsg);
                                resultPolySF = resultSF;
                                return(false);
                            }
                            if (copyAttributes)
                            {
                                for (int f = 0; f <= polySF.NumFields - 1; f++)
                                {
                                    bool tmpbool = resultSF.EditCellValue(f, shapeIndex, polySF.get_CellValue(f, i));
                                }
                            }
                        }
                    }
                }
            }
            resultPolySF = resultSF;
            return(true);
        }
Esempio n. 12
0
        private void MapResult_Load(object sender, EventArgs e)
        {
            idleTimer = DateTime.Now;
            timer1.Start();
            timer1.Interval = 5000;

            int intHandler1;

            MapWinGIS.Shapefile shapefile1 = new MapWinGIS.Shapefile();
            shapefile1.Open("..\\..\\shapefiles\\Form.shp");
            intHandler1 = axMap1.AddLayer(shapefile1, true);

            int intHandler2;

            MapWinGIS.Shapefile shapefile2 = new MapWinGIS.Shapefile();
            shapefile2.Open("..\\..\\shapefiles\\gang.shp");
            intHandler2 = axMap1.AddLayer(shapefile2, true);

            int intHandler7;

            MapWinGIS.Shapefile shapefile7 = new MapWinGIS.Shapefile();
            shapefile7.Open("..\\..\\shapefiles\\Stairs.shp");
            intHandler7 = axMap1.AddLayer(shapefile7, true);

            int intHandler6;

            MapWinGIS.Shapefile shapefile6 = new MapWinGIS.Shapefile();
            shapefile6.Open("..\\..\\shapefiles\\Shape .shp");
            string myLabel;
            //define two double variables to use as a coordinates for label position
            double x, y;

            for (int i = 0; i < shapefile6.NumShapes - 1; i++)
            {
                //assign the value of the cells of the field number zero to the label
                myLabel = System.Convert.ToString(
                    shapefile6.get_CellValue(1, i));
                //Calculate the x position for the label
                x = shapefile6.get_Shape(i).Extents.xMin +
                    (shapefile6.get_Shape(i).Extents.xMax -
                     shapefile6.get_Shape(i).Extents.xMin) / 2;
                //Calculate the y position for the label
                y = shapefile6.get_Shape(i).Extents.yMin +
                    (shapefile6.get_Shape(i).Extents.yMax -
                     shapefile6.get_Shape(i).Extents.yMin) / 2;

                shapefile6.Labels.AddLabel(myLabel, x, y, 0, -1);
            }
            intHandler6 = axMap1.AddLayer(shapefile6, true);

            int intHandler3;

            MapWinGIS.Shapefile shapefile3 = new MapWinGIS.Shapefile();
            shapefile3.Open("..\\..\\shapefiles\\Indgang.shp");
            intHandler3 = axMap1.AddLayer(shapefile3, true);

            int intHandler8;

            MapWinGIS.Shapefile shapefile8 = new MapWinGIS.Shapefile();
            shapefile8.Open("..\\..\\shapefiles\\WC.shp");
            intHandler8 = axMap1.AddLayer(shapefile8, true);

            int intHandler9;

            MapWinGIS.Shapefile shapefile4 = new MapWinGIS.Shapefile();
            shapefile4.Open("..\\..\\shapefiles\\navlines.shp");
            shapefile4.DefaultDrawingOptions.LineWidth = 4;
            intHandler9 = axMap1.AddLayer(shapefile4, true);

            int intHandler5;

            MapWinGIS.Shapefile shapefile5 = new MapWinGIS.Shapefile();
            shapefile5.Open("..\\..\\shapefiles\\navnodes.shp");
            intHandler5 = axMap1.AddLayer(shapefile5, false);

            //Calls the Dijkstra algorithm
            Dijkstra.dijkstra(SetLocationMap.Loc, Destinations.Dest);

            //Makes all lines initially hidden.
            for (int i = 0; i < shapefile4.NumShapes; i++)
            {
                shapefile4.set_ShapeIsHidden(i, true);
            }

            routelength = 0;

            foreach (int line in Dijkstra.Route.eroute)
            {
                //Sets included lines from  the route to be shown rather than hidden.
                shapefile4.set_ShapeIsHidden(line, false);
                //Sums up the lengths of included lines.
                routelength += Convert.ToDouble(shapefile4.get_CellValue(3, line));
            }
            //Sets the label to show travel time. It is the sum of line lengths (so total route length) divided by 1.4 meters per second (average walking speed) divided by 60 seconds (to get minutes).
            timeest.Text = String.Format("Estimated time to reach destination: {0} minutes", Math.Round((routelength / 1.4) / 60, 1));
            Dijkstra.Route.eroute.Clear();
        }
        private static void CachePoints(string InPointsPath, int InValueFieldIndex, out KDTreeDLL.KDTree PointsTree, out double[][] Points, out double[] PointVals, out string Projection, out string ProjectionUnits, out MapWinGIS.Extents PointsExtents, MapWinGIS.ICallback callback)
        {
            int newperc = 0, oldperc = 0;

            MapWinGIS.Shapefile pointsf = new MapWinGIS.Shapefile();
            pointsf.Open(InPointsPath, null);

            PointsExtents = pointsf.Extents;
            Projection    = pointsf.Projection;
            if (Projection != null)
            {
                ProjectionUnits = Projection.Substring(Projection.IndexOf("units=") + 6);
                ProjectionUnits = ProjectionUnits.Substring(0, ProjectionUnits.IndexOf("+")).Trim();
            }
            else
            {
                double tmpX   = pointsf.Extents.xMax;
                string tmpstr = Math.Floor(tmpX).ToString();

                if (tmpstr.Length > 4)
                {
                    ProjectionUnits = "";
                }
                else
                {
                    ProjectionUnits = "lat/long";
                }
            }

            PointsTree = new KDTreeDLL.KDTree(2);

            MapWinGIS.Point currpt;
            int             ns          = pointsf.NumShapes;

            Points    = new double[ns][];
            PointVals = new double[ns];
            int duplicates = 0;

            for (int i = 0; i < ns; i++)
            {
                Points[i] = new double[2];

                newperc = Convert.ToInt32((Convert.ToDouble(i) / Convert.ToDouble(ns)) * 100);
                if ((newperc > oldperc))
                {
                    if (callback != null)
                    {
                        callback.Progress("Status", newperc, "IDW Caching " + i.ToString());
                    }
                    oldperc = newperc;
                }

                currpt       = pointsf.get_Shape(i).get_Point(0);
                Points[i][0] = currpt.x;
                Points[i][1] = currpt.y;
                PointVals[i] = double.Parse(pointsf.get_CellValue(InValueFieldIndex, i).ToString());

                try
                {
                    if (PointsTree.search(Points[i]) == null)
                    {
                        PointsTree.insert(Points[i], i);
                    }
                }
                catch (KDTreeDLL.KeyDuplicateException)
                {
                    duplicates++;
                }
            }
            pointsf.Close();
        }
Esempio n. 14
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);
        }
Esempio n. 15
0
        /// <summary>
        /// Removes portions of the lineSF that fall within the erase polygon
        /// </summary>
        /// <param name="lineSF">The shapefile of lines to be erased.</param>
        /// <param name="erasePoly">The polygon to be used for erasing portion of the line shapefile.</param>
        /// <param name="resultSF">The resulting line shapefile with portions removed.</param>
        /// <param name="CopyAttributes">Indicates whether to copy attributes</param>
        /// <returns>False if an error was encountered, true otherwise.</returns>
        public static bool EraseLineSFWithPoly(ref MapWinGIS.Shapefile lineSF, ref MapWinGIS.Shape erasePoly, ref MapWinGIS.Shapefile resultSF, bool CopyAttributes)
        {
            MapWinUtility.Logger.Dbg("EraseLineSFWithPoly(lineSF: " + Macro.ParamName(lineSF) + ",\n" +
                                     "                    erasePoly: " + Macro.ParamName(erasePoly) + ",\n" +
                                     "                    resultSF: " + Macro.ParamName(resultSF) + ",\n" +
                                     "                    CopyAttributes: " + CopyAttributes.ToString() + ")");
            if (lineSF == null || erasePoly == null || resultSF == null)
            {
                gErrorMsg = "One of the input parameters is null.";
                Error.SetErrorMsg(gErrorMsg);
                Debug.WriteLine(gErrorMsg);
                MapWinUtility.Logger.Dbg(gErrorMsg);
                return(false);
            }

            if (CopyAttributes)
            {
                string          tmpName;
                MapWinGIS.Field tmpField, currField;
                for (int f = 0; f <= lineSF.NumFields - 1; f++)
                {
                    tmpField      = new MapWinGIS.Field();
                    currField     = lineSF.get_Field(f);
                    tmpName       = currField.Name;
                    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);
                }
            }

            int shpIndex = 0;
            int numLines = lineSF.NumShapes;

            for (int i = 0; i <= numLines - 1; i++)
            {
                MapWinGIS.Shape currLine = new MapWinGIS.ShapeClass();
                currLine.Create(lineSF.ShapefileType);
                currLine = lineSF.get_Shape(i);

                MapWinGIS.Shape lineEnvelope = new MapWinGIS.ShapeClass();
                lineEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                //create lineExtents' points out of the line extent points
                MapWinGIS.Point lTop, rTop, rBottom, lBottom;
                lTop      = new MapWinGIS.PointClass();
                lTop.x    = currLine.Extents.xMin;
                lTop.y    = currLine.Extents.yMax;
                rTop      = new MapWinGIS.PointClass();
                rTop.x    = currLine.Extents.xMax;
                rTop.y    = currLine.Extents.yMax;
                rBottom   = new MapWinGIS.PointClass();
                rBottom.x = currLine.Extents.xMax;
                rBottom.y = currLine.Extents.yMin;
                lBottom   = new MapWinGIS.PointClass();
                lBottom.x = currLine.Extents.xMin;
                lBottom.y = currLine.Extents.yMin;
                //now add the extent points to the new polygon shape: lineEnvelope
                int ptIndex = 0;
                lineEnvelope.InsertPoint(lTop, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(rTop, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(rBottom, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(lBottom, ref ptIndex);
                ptIndex++;
                lineEnvelope.InsertPoint(lTop, ref ptIndex);
                //remove COM points from memory
                while (Marshal.ReleaseComObject(lTop) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(rTop) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(rBottom) != 0)
                {
                    ;
                }
                while (Marshal.ReleaseComObject(lBottom) != 0)
                {
                    ;
                }

                //Check if line extents and polygon extents overlap
                if (Globals.CheckBounds(ref lineEnvelope, ref erasePoly))
                {
                    //make the envelope polygon slightly larger
                    MapWinGIS.Shape lgEnvelope = new MapWinGIS.ShapeClass();
                    lgEnvelope.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                    SpatialOperations.BufferPolygon(ref lineEnvelope, 0.5, Enumerations.Buffer_HoleTreatment.Ignore, Enumerations.Buffer_CapStyle.Pointed, out lgEnvelope);
                    //take the difference of the envelope polygon with the erase polygon.
                    MapWinGIS.Shape diff = new MapWinGIS.ShapeClass();
                    diff.Create(MapWinGIS.ShpfileType.SHP_POLYGON);
                    diff = SpatialOperations.Difference(lgEnvelope, erasePoly);
                    if (diff.numPoints > 0)
                    {
                        //the difference shape represents the line envelope
                        //minus the area of the erase polygon.
                        MapWinGIS.Shapefile inputLine = new MapWinGIS.ShapefileClass();
                        string tempPath = System.IO.Path.GetTempPath() + "tempInputLine.shp";
                        //CDM 8/4/2006 inputLine.CreateNew(tempPath, lineSF.ShapefileType);
                        Globals.PrepareResultSF(ref tempPath, ref inputLine, lineSF.ShapefileType);
                        shpIndex = 0;
                        inputLine.EditInsertShape(currLine, ref shpIndex);

                        int numParts = diff.NumParts;
                        if (numParts == 0)
                        {
                            numParts = 1;
                        }

                        if (numParts > 1)
                        {
                            //separate and test each part individually
                            MapWinGIS.Shape[] diffParts = new MapWinGIS.Shape[numParts];
                            Globals.SeparateParts(ref diff, out diffParts);
                            for (int j = 0; j <= numParts - 1; j++)
                            {
                                //don't check inside of holes
                                if (Globals.IsClockwise(ref diffParts[j]))
                                {
                                    MapWinGIS.Shapefile tempLineResult = new MapWinGIS.ShapefileClass();
                                    string tempLineFile = System.IO.Path.GetTempPath() + "tempLines.shp";
                                    DataManagement.DeleteShapefile(ref tempLineFile);
                                    //CDM 8/4/2006 tempLineResult.CreateNew(tempLineFile, lineSF.ShapefileType);
                                    Globals.PrepareResultSF(ref tempLineFile, ref tempLineResult, lineSF.ShapefileType);
                                    tempLineResult.StartEditingShapes(true, null);

                                    SpatialOperations.ClipShapesWithPolygon(ref inputLine, ref diffParts[j], out tempLineResult, false);

                                    int numResults = tempLineResult.NumShapes;
                                    if (numResults > 0)
                                    {
                                        //add results to the final result file.
                                        for (int k = 0; k <= numResults - 1; k++)
                                        {
                                            shpIndex = resultSF.NumShapes;
                                            resultSF.EditInsertShape(tempLineResult.get_Shape(k), ref shpIndex);
                                            if (CopyAttributes)
                                            {
                                                for (int f = 0; f <= lineSF.NumFields - 1; f++)
                                                {
                                                    bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                                                }
                                            }
                                        }
                                    }                    //clipping successful
                                }                        //done checking islands
                            }                            //done looping through parts of the difference shape
                        }
                        else
                        {
                            MapWinGIS.Shapefile tempLineResult = new MapWinGIS.ShapefileClass();
                            string tempLineFile = System.IO.Path.GetTempPath() + "tempLines.shp";
                            DataManagement.DeleteShapefile(ref tempLineFile);
                            //CDM 8/4/2006 tempLineResult.CreateNew(tempLineFile, lineSF.ShapefileType);
                            Globals.PrepareResultSF(ref tempLineFile, ref tempLineResult, lineSF.ShapefileType);

                            tempLineResult.StartEditingShapes(true, null);

                            SpatialOperations.ClipShapesWithPolygon(ref inputLine, ref diff, out tempLineResult, false);

                            int numResults = tempLineResult.NumShapes;
                            if (numResults > 0)
                            {
                                //add results to the final result file.
                                for (int k = 0; k <= numResults - 1; k++)
                                {
                                    shpIndex = resultSF.NumShapes;
                                    resultSF.EditInsertShape(tempLineResult.get_Shape(k), ref shpIndex);
                                    if (CopyAttributes)
                                    {
                                        for (int f = 0; f <= lineSF.NumFields - 1; f++)
                                        {
                                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                                        }
                                    }
                                }
                            }    //clipping successful
                        }
                    }            //difference operation successful
                }                //bounds overlapped
                else
                {
                    shpIndex = resultSF.NumShapes;
                    resultSF.EditInsertShape(currLine, ref shpIndex);
                    if (CopyAttributes)
                    {
                        for (int f = 0; f <= lineSF.NumFields - 1; f++)
                        {
                            bool tmpbool = resultSF.EditCellValue(f, shpIndex, lineSF.get_CellValue(f, i));
                        }
                    }
                }
            }            //end of looping through lines in the input shapefile
            MapWinUtility.Logger.Dbg("Finished EraseLineSFWithPoly");
            return(true);
        }
Esempio n. 16
0
        /// <summary>
        /// Exports the shapes from the inputSF which fall within the given polygon, saving to the resultSF provided.
        /// </summary>
        /// <returns>False if an error occurs, true otherwise.</returns>
        public static bool SelectLinesWithPolygon(ref MapWinGIS.Shapefile inputSF, ref MapWinGIS.Shape polygon, ref MapWinGIS.Shapefile resultSF, bool SkipMWShapeID)
        {
            int numLines = inputSF.NumShapes;
            int shpIndex = 0;

            // Boundary intersection test variables
            double xMin1, xMax1, yMin1, yMax1, zMin1, zMax1, xMin2, xMax2, yMin2, yMax2, zMin2, zMax2;

            // Get the masking polygon's boundaries only once:
            polygon.Extents.GetBounds(out xMin2, out yMin2, out zMin2, out xMax2, out yMax2, out zMax2);

            if (Globals.CopyFields(ref inputSF, ref resultSF) == false)
            {
                return(false);
            }

            MapWinGIS.Shape currLine;
            MapWinGIS.Point currPt;
            for (int i = 0; i <= numLines - 1; i++)
            {
                currLine = inputSF.get_Shape(i);
                currLine.Extents.GetBounds(out xMin1, out yMin1, out zMin1, out xMax1, out yMax1, out zMax1);

                // Are the boundaries intersecting?
                if (!(xMin1 > xMax2 || xMax1 < xMin2 || yMin1 > yMax2 || yMax1 < yMin2))
                {
                    //lines are nasty, just because the boundaries intersect it
                    //doesn't mean the line enters the polygon
                    //do a quick point check before doing a more thorough investigation

                    int  numPoints = currLine.numPoints;
                    bool ptInside  = false;
                    for (int j = 0; j <= numPoints - 1; j++)
                    {
                        currPt = currLine.get_Point(j);
                        if (polygon.PointInThisPoly(currPt))
                        {
                            ptInside = true;
                            break;
                        }
                    }
                    if (ptInside)
                    {
                        //we know part of the line is inside the polygon so add line to result file
                        shpIndex = resultSF.NumShapes;
                        if (resultSF.EditInsertShape(currLine, ref shpIndex) == false)
                        {
                            gErrorMsg = "Problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                            Debug.WriteLine(gErrorMsg);
                            Error.SetErrorMsg(gErrorMsg);
                            return(false);
                        }
                        //add the table values
                        int numFields = resultSF.NumFields;
                        for (int j = 0; j <= numFields - 1; j++)
                        {
                            if (resultSF.EditCellValue(j, shpIndex, inputSF.get_CellValue(j, i)) == 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
                    }                    //end of ptInside check
                    else
                    {
                        // Avoid using a temp file to test each individual file;
                        // instead, just see if the line crosses the polygon
                        if (LineCrossesPoly(ref currLine, ref polygon))
                        {
                            //part of the line lies within the polygon, add to result file
                            shpIndex = resultSF.NumShapes;
                            if (resultSF.EditInsertShape(currLine, ref shpIndex) == false)
                            {
                                gErrorMsg = "Problem inserting shape into result file: " + resultSF.get_ErrorMsg(resultSF.LastErrorCode);
                                Debug.WriteLine(gErrorMsg);
                                Error.SetErrorMsg(gErrorMsg);
                                return(false);
                            }
                            //add the table values
                            int numFields = resultSF.NumFields;
                            for (int j = 0; j <= numFields - 1; j++)
                            {
                                if (resultSF.EditCellValue(j, shpIndex, inputSF.get_CellValue(j, i)) == 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
                        }     //end of successful cross
                    }         //end of else no points were found inside polygon
                }             //end of checking bounds
            }                 //end of looping through lines

            if (resultSF.NumShapes > 0)
            {
                if (resultSF.NumFields == 0 || !SkipMWShapeID)
                {
                    //add the ID field and values
                    if (Globals.DoInsertIDs(ref resultSF) == false)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 17
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();
        }