/// <summary>
        /// Loads layer from datasource specifed by filename
        /// </summary>
        private void LoadLayer()
        {
            axMap1.RemoveAllLayers();

            int    handle = -1;
            string ext    = System.IO.Path.GetExtension(m_layer.FileName).ToLower();

            if (ext == ".shp")
            {
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(m_layer.FileName, null))
                {
                    handle = axMap1.AddLayer(sf, true);
                    sf.Labels.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                    sf.Charts.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                    //sf.FastMode = true;
                }
            }
            else
            {
                MapWinGIS.Image img = new MapWinGIS.Image();
                if (img.Open(m_layer.FileName, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, null))
                {
                    handle = this.axMap1.AddLayer(img, true);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Update projection column for a specified layers
        /// </summary>
        private void UpdateProjection(string filename, DataGridView dgv, int rowIndex)
        {
            if (this.ControlType == CustomType.Projection)
            {
                string name            = "";
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(filename, null))
                {
                    name = sf.GeoProjection.Name;
                    ProjectionDatabase db = m_mapWin.ProjectionDatabase as ProjectionDatabase;
                    if (db != null)
                    {
                        CoordinateSystem cs = db.GetCoordinateSystem(sf.GeoProjection, ProjectionSearchType.UseDialects);
                        if (cs != null)
                        {
                            name = cs.Name;
                        }
                    }

                    dgv[this.CustomColumnIndex, rowIndex].Value = name;
                    sf.Close();
                }
                sf = null;

                if (name == "")
                {
                    dgv[this.CustomColumnIndex, rowIndex].Value = "Undefined";
                }
            }
        }
示例#3
0
        // Try to open the shapefiles, return false if there was a problem
        private bool OpenFiles(out string errorMessage)
        {
            errorMessage = "No Error";

            // Try to open the filenames and test that they are the same type of shapefile
            if (_inSF1.Open(_inFile1, null) == false)
            {
                errorMessage = _inSF1.get_ErrorMsg(_inSF1.LastErrorCode);
                return(false);
            }
            if (_inSF2.Open(_inFile2, null) == false)
            {
                _inSF1.Close();
                errorMessage = _inSF2.get_ErrorMsg(_inSF1.LastErrorCode);
                return(false);
            }
            if (_inSF1.ShapefileType != _inSF2.ShapefileType)
            {
                _inSF1.Close();
                _inSF2.Close();
                errorMessage = "Shape types were incompatible: " + _inSF1.ShapefileType.ToString() + " != " + _inSF2.ShapefileType.ToString();
                return(false);
            }

            // Create the output shapefile and prepare it for editing
            if (_outSF.CreateNew(_outFile, _inSF1.ShapefileType) == false)
            {
                _inSF1.Close();
                _inSF2.Close();
                errorMessage = _outSF.get_ErrorMsg(_outSF.LastErrorCode);
                return(false);
            }
            return(true);
        }
示例#4
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //Add first layer to your map
            int intHandler1; //integer index to handle the layer

            //create a new instance for MapWinGIS.Shapefile
            //MapWinGIS.Shapefile  is a data provider for ESRI Shapefile
            MapWinGIS.Shapefile shapefile1 = new MapWinGIS.Shapefile();
            //Define the data source for MapWinGIS.Shapefile instance
            shapefile1.Open(@"G:\OneDrve\Documents\PROJECTS\gis\p1\GISSampleData\GISSampleData\base.shp", null);
            //display the layer on the map
            intHandler1 = axMap1.AddLayer(shapefile1, true);

            //Add second layer
            int intHandler2;

            MapWinGIS.Shapefile shapefile2 = new MapWinGIS.Shapefile();
            shapefile2.Open(@"G:\OneDrve\Documents\PROJECTS\gis\p1\GISSampleData\GISSampleData\nile.shp", null);
            intHandler2 = axMap1.AddLayer(shapefile2, true);


            //Set Filling color of the ploygon shapefile
            axMap1.set_ShapeLayerFillColor(intHandler1,
                                           (UInt32)(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SaddleBrown)));
            //Set the line color
            axMap1.set_ShapeLayerLineColor(intHandler2,
                                           (UInt32)(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow)));
            //Set the line width
            axMap1.set_ShapeLayerLineWidth(intHandler2, 5);
        }
示例#5
0
        /// <summary>
        /// Loads layer from datasource specifed by filename
        /// </summary>
        private void LoadLayer()
        {
            axMap1.RemoveAllLayers();
            int    handle = -1;
            string ext    = System.IO.Path.GetExtension(m_filename).ToLower();

            if (ext == ".shp")
            {
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(m_filename, null))
                {
                    handle = axMap1.AddLayer(sf, true);
                    sf.Labels.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                    sf.Charts.SavingMode = MapWinGIS.tkSavingMode.modeNone;
                }
            }
            else
            {
                MapWinGIS.Image img = new MapWinGIS.Image();
                if (img.Open(m_filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, null))
                {
                    handle = this.axMap1.AddLayer(img, true);
                }
            }

            // serializing initial state to display random options afterwrads
            m_initState = axMap1.SerializeLayer(handle);
        }
示例#6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //Define the data source of Shapefile instanse
            myShapefile.Open(@"D:\GISSampleData2\arabcntry.shp", null);
            //Display the layer on the map control
            intHandler = axMap1.AddLayer(myShapefile, true);

            SetBasicSymbology();
        }
        /// <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);
            }
        }
        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();
        }
示例#9
0
        // calculate a default cellsize (grid-max.500 rows or columns)
        // using the input shapefile extent
        private double calcDefaultCellsize()
        {
            MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
            double result          = 0F;

            if (sf.Open(m_ShpFileName, null))
            {
                double sfX    = sf.Extents.xMax - sf.Extents.xMin;
                double sfY    = sf.Extents.yMax - sf.Extents.yMin;
                double minExt = Math.Max(sfX, sfY);
                result = Math.Floor(minExt / 250F);
            }
            sf.Close();
            return(result);
        }
示例#10
0
        public void UndoLastChange()
        {
            // MapWindow doesn't lock the shapefile so long as we're
            // not currently editing; so the file can be overwritten
            // and a redraw triggered.
            if (UndoStack.Count == 0)
            {
                return;
            }

            MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)MapWin.Layers[MapWin.Layers.CurrentLayer].GetObject();
            if (sf.EditingShapes || sf.EditingTable)
            {
                sf.StopEditingShapes(false, true, null);
            }

            // Lock the map and legend -- we're about to do evil things to the underlying map
            MapWin.View.LockMap();
            MapWin.View.LockLegend();

            string tmp  = (string)UndoStack.Pop();
            string xtmp = System.IO.Path.ChangeExtension(tmp, ".shx");
            string dtmp = System.IO.Path.ChangeExtension(tmp, ".dbf");

            string fail  = MapWin.Layers[MapWin.Layers.CurrentLayer].FileName;
            string xfail = System.IO.Path.ChangeExtension(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, ".shx");
            string dfail = System.IO.Path.ChangeExtension(MapWin.Layers[MapWin.Layers.CurrentLayer].FileName, ".dbf");

            sf.Close();

            System.IO.File.Copy(tmp, fail, true);
            System.IO.File.Copy(xtmp, xfail, true);
            System.IO.File.Copy(dtmp, dfail, true);

            System.IO.File.Delete(tmp);
            System.IO.File.Delete(xtmp);
            System.IO.File.Delete(dtmp);

            sf.Open(fail, null);

            // Unlock and refresh:
            MapWin.View.UnlockMap();
            MapWin.View.UnlockLegend();
            UpdateView();
            UpdateUndoButtons();
        }
        /// <summary>
        /// Inverse Distance Weighting Interpolation
        /// </summary>
        /// <param name="InPointsPath">Input point shapefile path to interpolate</param>
        /// <param name="InValueFieldIndex">Input field index where interpolation value is stored</param>
        /// <param name="OutGridPath">Output grid path where interpolation is stored</param>
        public static void IDW(string InPointsPath, int InValueFieldIndex, string OutGridPath)
        {
            MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
            sf.Open(InPointsPath, null);
            double height          = Math.Abs(sf.Extents.yMax - sf.Extents.yMin);
            double width           = Math.Abs(sf.Extents.xMax - sf.Extents.xMin);
            double defaultCellSize = -1;

            if (height <= width)
            {
                defaultCellSize = height / 250;
            }
            else
            {
                defaultCellSize = width / 250;
            }
            sf.Close();

            IDW(InPointsPath, InValueFieldIndex, OutGridPath, defaultCellSize);
        }
示例#12
0
        public int GetNumCellsByDEMAndMask(MapWinGIS.GridHeader head, string strMask)
        {
            int numCells = 0, maskCells = 0;

            numCells = head.NumberCols * head.NumberRows;
            MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
            sf.Open(strMask);
            for (int iShape = 0; iShape < sf.NumShapes; iShape++)
            {
                MapWinGIS.Shape tempShape = sf.Shape[iShape];
                int             temp      = Convert.ToInt32(MapWinGeoProc.Utils.Area(ref tempShape) / (head.dX * head.dY));
                maskCells = maskCells + temp;
            }
            sf.Close();
            if (numCells > maskCells)
            {
                numCells = maskCells;
            }

            return(numCells);
        }
        /// <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="ElevGrid">A string filename for the grid that contains the elevations.</param>
        /// <param name="PolyLine">A string filename for a polyline 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</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(string ElevGrid, string PolyLine, string OutFileName, CrossSectionTypes CrossSectionType, MapWinGIS.ICallback ICallBack)
        {
            bool res;

            // Load the grid
            if (ElevGrid == null)
            {
                throw new ArgumentException("ElevGrid cannot be null.");
            }
            if (System.IO.File.Exists(ElevGrid) == false)
            {
                throw new ArgumentException("The file " + ElevGrid + " does not exist.");
            }
            MapWinGIS.Grid mwGrid = new MapWinGIS.Grid();
            res = mwGrid.Open(ElevGrid, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack);
            if (res == false)
            {
                throw new ApplicationException(mwGrid.get_ErrorMsg(mwGrid.LastErrorCode));
            }

            // Load the Shapefile
            if (PolyLine == null)
            {
                throw new ArgumentException("PolyLine cannot be null.");
            }
            if (System.IO.File.Exists(PolyLine) == false)
            {
                throw new ArgumentException("The file " + PolyLine + " does not exist.");
            }
            MapWinGIS.Shapefile mwPolyLine = new MapWinGIS.Shapefile();
            res = mwPolyLine.Open(PolyLine, ICallBack);
            if (res == false)
            {
                throw new ApplicationException(mwPolyLine.get_ErrorMsg(mwPolyLine.LastErrorCode));
            }

            GetCrossSection(mwGrid, mwPolyLine, OutFileName, CrossSectionType, ICallBack);
        }
示例#14
0
 private void populateFields(string shpFileName)
 {
     cmbFields.Items.Clear();
     MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
     MapWinGIS.Field     curField;
     if (sf.Open(shpFileName, sf.GlobalCallback))
     {
         for (int i = 0; i < sf.NumFields; ++i)
         {
             curField = sf.get_Field(i);
             if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD ||
                 curField.Type == MapWinGIS.FieldType.INTEGER_FIELD)
             {
                 cmbFields.Items.Add(curField.Name);
             }
         }
         sf.Close();
     }
     if (cmbFields.Items.Count > 0)
     {
         cmbFields.SelectedIndex = 0;
     }
 }
示例#15
0
        public bool topology(string streamsLayer)
        {
            MapWinGIS.Shapefile streamShp = new MapWinGIS.Shapefile();
            streamShp.Open(streamsLayer);

            ArrayList array = mwSWATTopology.readTree(hruGlobals, streamShp);

            hruData.computeDrainAreas(array, hruGlobals);

            TopologyData cd = new TopologyData();

            // add internal outlets (monitoring points)
            int monNum = 1;

            for (int i = 0; i < hruGlobals.monitoringPointBasins.Count; i++)
            {
                int basin = hruGlobals.monitoringPointBasins[i];
                // guard against basins upstream from inlets
                if (hruGlobals.basinToSWATBasin.ContainsKey(basin))
                {
                    int SWATBasin = hruGlobals.basinToSWATBasin[basin];
                    cd.addSavePoint(basin, SWATBasin, monNum);
                    monNum = monNum + 1;
                }
            }
            // add reservoirs
            int resNum = 1;

            for (int i = 0; i < hruGlobals.reservoirBasins.Count; i++)
            {
                int basin = hruGlobals.reservoirBasins[i];
                // guard against basins upstream from inlets
                if (hruGlobals.basinToSWATBasin.ContainsKey(basin))
                {
                    int SWATBasin = hruGlobals.basinToSWATBasin[basin];
                    cd.addReservoir(basin, SWATBasin, resNum);
                    resNum = resNum + 1;
                }
            }
            // add inlets
            int fileNum = 1;

            for (int i = 0; i < hruGlobals.inletBasins.Count; i++)
            {
                int basin = hruGlobals.inletBasins[i];
                // guard against inlets upstream from inlets (!)
                if (hruGlobals.basinToSWATBasin.ContainsKey(basin))
                {
                    int SWATBasin = hruGlobals.basinToSWATBasin[basin];
                    cd.addInlet(basin, SWATBasin, fileNum);
                    fileNum = fileNum + 1;
                }
            }
            // add point sources (still incrementing file numbers)
            for (int i = 0; i < hruGlobals.srcBasins.Count; i++)
            {
                int basin = hruGlobals.srcBasins[i];
                // guard against basins upstream from inlets
                if (hruGlobals.basinToSWATBasin.ContainsKey(basin))
                {
                    int SWATBasin = hruGlobals.basinToSWATBasin[basin];
                    cd.addPointSource(basin, SWATBasin, fileNum);
                    fileNum = fileNum + 1;
                }
            }
            if (hruGlobals.figFileWanted)
            {
                // Write fig.fig file
                string configFilePath = hruGlobals.TxtInOutDir + "\\fig.fig";
                return(mwSWATTopology.makeConfigFile(array, cd, configFilePath, hruGlobals));
            }

            return(true);
        }
示例#16
0
        // displays the grid extent!
        private void cmbExtent_SelectedIndexChanged(object sender, EventArgs e)
        {
            MapWinGIS.Shapefile        sf = new MapWinGIS.Shapefile();
            MapWindow.Interfaces.Layer curLayer;
            MapWinGIS.Grid             grd = new MapWinGIS.Grid();
            MapWinGIS.Extents          extents;
            double cellSize = m_DefaultCellSize;

            //get the cell size to value from textbox
            Utils.string2double(txtCellSize.Text, out cellSize);

            //handle the "as specified below" option
            if (cmbExtent.Text == msgSpecifiedBelow)
            {
                txtMinX.Enabled = true;
                txtMinY.Enabled = true;
                txtMaxX.Enabled = true;
                txtMaxY.Enabled = true;

                return;
            }
            else
            {
                txtMinX.Enabled = false;
                txtMinY.Enabled = false;
                txtMaxX.Enabled = false;
                txtMaxY.Enabled = false;
            }

            //handle the case when shapefile loaded from disk and selected
            if (cmbExtent.Text == msgSameAs + m_ShortName)
            {
                if (sf.Open(m_ShpFileName, null))
                {
                    extents = calcShapefileExtent(sf);
                    UpdateExtentBox(extents);
                }
                sf.Close();
            }

            for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i)
            {
                //an existing layer is used to determine the extent
                curLayer = m_MapWin.Layers[i];
                if (curLayer != null)
                {
                    if (msgSameAs + curLayer.Name == cmbExtent.Text)
                    {
                        switch (curLayer.LayerType)
                        {
                        //same extention as an existing grid
                        case MapWindow.Interfaces.eLayerType.Grid:
                            grd = curLayer.GetGridObject;
                            UpdateExtentBox(grd.Header);
                            break;

                        //same extention as an existing shapefile
                        case MapWindow.Interfaces.eLayerType.LineShapefile:
                        case MapWindow.Interfaces.eLayerType.PolygonShapefile:
                        case MapWindow.Interfaces.eLayerType.PointShapefile:
                            sf      = (MapWinGIS.Shapefile)curLayer.GetObject();
                            extents = calcShapefileExtent(sf);
                            UpdateExtentBox(extents);
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
示例#17
0
        private void Map()
        {
            AxMapWinGIS.AxMap map = new AxMapWinGIS.AxMap();
            map.Width           = 450;
            map.MouseDownEvent += Map_MouseDownEvent;
            map.Height          = 600;
            host.Child          = map;
            map.Show();
            map.ShapeHighlighted += Map_ShapeHighlighted;
            map.CreateControl();
            map.ShowZoomBar     = false;
            map.ShowCoordinates = MapWinGIS.tkCoordinatesDisplay.cdmNone;
            map.CursorMode      = MapWinGIS.tkCursorMode.cmIdentify;

            MapWinGIS.Shapefile shapeFileMap = new MapWinGIS.Shapefile();
            shapeFileMap.Open(@"D:\Projets\TheManager\TheManager_GUI\bin\Debug\gis\world\World_Countries.shp", null);
            shapeFileMap.Identifiable = false;
            map.AddLayer(shapeFileMap, true);
            map.ZoomToShape(0, 77);

            MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
            sf.Identifiable = true;
            sf.CreateNew("", MapWinGIS.ShpfileType.SHP_POINT);
            sf.DefaultDrawingOptions.AlignPictureByBottom = false;
            sf.DefaultDrawingOptions.PointType            = MapWinGIS.tkPointSymbolType.ptSymbolStandard;
            sf.CollisionMode = MapWinGIS.tkCollisionMode.AllowCollisions;

            List <City> takenCities = new List <City>();

            foreach (Journalist journalist in _media.journalists)
            {
                double projX = -1;
                double projY = -1;
                map.DegreesToProj(journalist.baseCity.Position.Longitude, journalist.baseCity.Position.Latitude, ref projX, ref projY);

                if (takenCities.Contains(journalist.baseCity))
                {
                    projY += Session.Instance.Random(3, 12) / 10.0;
                }

                MapWinGIS.Shape shp = new MapWinGIS.Shape();
                shp.Create(MapWinGIS.ShpfileType.SHP_POINT);
                shp.AddPoint(projX, projY);
                _indexOrders.Add(sf.EditAddShape(shp));
                takenCities.Add(journalist.baseCity);
            }
            int layer = map.AddLayer(sf, true);

            foreach (Journalist journalist in _media.journalists)
            {
                int    handle = map.NewDrawing(MapWinGIS.tkDrawReferenceList.dlScreenReferencedList);
                double pixX   = -1;
                double pixY   = -1;
                map.DegreesToPixel(journalist.baseCity.Position.Longitude, journalist.baseCity.Position.Latitude, ref pixX, ref pixY);

                float maxDistance = -1;
                foreach (Match m in journalist.CommentedGames)
                {
                    float dist = Utils.Distance(m.home.stadium.city, journalist.baseCity);
                    if (dist > maxDistance)
                    {
                        maxDistance = dist;
                    }
                }

                map.DrawCircleEx(handle, pixX, pixY, maxDistance / 2, 2883, true, 25);
            }

            map.ShapeIdentified += Map_ShapeIdentified;
            map.Redraw();
        }
示例#18
0
文件: frmGrid.cs 项目: qlands/GOBLET
        // displays the grid extent!
        private void cmbExtent_SelectedIndexChanged(object sender, EventArgs e)
        {
            MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
            MapWindow.Interfaces.Layer curLayer;
            MapWinGIS.Grid grd = new MapWinGIS.Grid();
            MapWinGIS.Extents extents;
            double cellSize = m_DefaultCellSize;

            //get the cell size to value from textbox
            Utils.string2double(txtCellSize.Text, out cellSize);

            //handle the "as specified below" option
            if (cmbExtent.Text == msgSpecifiedBelow)
            {
                txtMinX.Enabled = true;
                txtMinY.Enabled = true;
                txtMaxX.Enabled = true;
                txtMaxY.Enabled = true;

                return;
            }
            else
            {
                txtMinX.Enabled = false;
                txtMinY.Enabled = false;
                txtMaxX.Enabled = false;
                txtMaxY.Enabled = false;
            }

            //handle the case when shapefile loaded from disk and selected
            if (cmbExtent.Text == msgSameAs + m_ShortName)
            {
                if (sf.Open(m_ShpFileName,null))
                {
                    extents = calcShapefileExtent(sf);
                    UpdateExtentBox(extents);
                }
                sf.Close();
            }

            for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i)
            {
                //an existing layer is used to determine the extent
                curLayer = m_MapWin.Layers[i];
                if (curLayer != null)
                {
                    if (msgSameAs + curLayer.Name == cmbExtent.Text)
                    {
                        switch (curLayer.LayerType)
                        {
                            //same extention as an existing grid
                            case MapWindow.Interfaces.eLayerType.Grid:
                                grd = curLayer.GetGridObject;
                                UpdateExtentBox(grd.Header);
                                break;

                            //same extention as an existing shapefile
                            case MapWindow.Interfaces.eLayerType.LineShapefile:
                            case MapWindow.Interfaces.eLayerType.PolygonShapefile:
                            case MapWindow.Interfaces.eLayerType.PointShapefile:
                                sf = (MapWinGIS.Shapefile)curLayer.GetObject();
                                extents = calcShapefileExtent(sf);
                                UpdateExtentBox(extents);
                                break;

                            default:
                                break;
                        }
                    }
                }
            }
        }
示例#19
0
文件: frmGrid.cs 项目: qlands/GOBLET
 // calculate a default cellsize (grid-max.500 rows or columns)
 // using the input shapefile extent
 private double calcDefaultCellsize()
 {
     MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
     double result = 0F;
     if (sf.Open(m_ShpFileName, null))
     {
         double sfX = sf.Extents.xMax - sf.Extents.xMin;
         double sfY = sf.Extents.yMax - sf.Extents.yMin;
         double minExt = Math.Max(sfX, sfY);
         result = Math.Floor(minExt / 250F);
     }
     sf.Close();
     return result;
 }
示例#20
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();
        }
示例#21
0
        public bool LabelBasins(string watershedShpPath, string streamNetShpPath, string oiShpPath, string extraOiShpPath)
        {
            SetProjection();


            MapWinGIS.Grid dem = new MapWinGIS.Grid(); dem.Open(basedem);
            //MapWindow.Interfaces.Layer demLayer = (MapWindow.Interfaces.Layer)dem;

            wshd = new MapWinGIS.Shapefile(); wshd.Open(watershedShpPath);
            //MapWindow.Interfaces.Layer wshdLayer = (MapWindow.Interfaces.Layer)wshd;

            net = new MapWinGIS.Shapefile(); net.Open(streamNetShpPath);
            // MapWindow.Interfaces.Layer netLayer = (MapWindow.Interfaces.Layer)net;



            oiFile = new MapWinGIS.Shapefile(); oiFile.Open(oiShpPath);
            //MapWindow.Interfaces.Layer oiFileLayer = (MapWindow.Interfaces.Layer)oiFile;

            if (extraOiShpPath != "")
            {
                extraOiFile = new MapWinGIS.Shapefile();
                extraOiFile.Open(extraOiShpPath);
            }
            //MapWindow.Interfaces.Layer extraOiFileLayer = (MapWindow.Interfaces.Layer)extraOiFile;

            //hruGlobals.populateLinkToBasin(demLayer, wshdLayer, netLayer, oiFileLayer, extraOiFileLayer); //Passing, exception,, cannot convert UTM to LatLong
            hruGlobals.populateLinkToBasin(dem, wshd, net, oiFile, extraOiFile); //Passing, exception,, cannot convert UTM to LatLong

            hruGlobals.clearCentroids();
            int numFields = wshd.NumFields;
            // Find index for PolygonID field
            int polyidField = -1;

            for (int i = 0; i < numFields; i++)
            {
                if (wshd.Field[i].Name.Equals("PolygonID", System.StringComparison.InvariantCultureIgnoreCase))
                {
                    polyidField = i;
                    break;
                }
            }
            //////////////////////////////////////////////////////////////////////////
            int numShapes = wshd.NumShapes;

            for (int i = 0; i < numShapes; i++)
            {
                MapWinGIS.Shape shape    = wshd.Shape[i];
                MapWinGIS.Point centroid = MapWinGeoProc.Utils.Centroid(ref shape);
                int             link     = Convert.ToInt32(wshd.CellValue[polyidField, i]);
                if (hruGlobals.linkToBasin.ContainsKey(link) == false)
                {
                    //MessageBox.Show(strings_vb.nobasinforlink & link.ToString() & _
                    //strings_vb.tryrestart, MWSWATName, _
                    //MessageBoxButtons.OK, MessageBoxIcon.Error)
                    return(false);
                }

                int basin = hruGlobals.linkToBasin[link];
                hruGlobals.setCentroid(basin, centroid);
                if (hruGlobals.basinToSWATBasin.ContainsKey(basin))
                {
                    int SWATBasin = hruGlobals.basinToSWATBasin[basin];
                    //wshdLayer.AddLabel(SWATBasin.ToString(), System.Drawing.Color.Black, centroid.x, centroid.y, MapWinGIS.tkHJustification.hjCenter)
                }
            }
            return(true);
        }
        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();
        }
示例#23
0
        private void Map(Round t)
        {
            AxMapWinGIS.AxMap map = new AxMapWinGIS.AxMap();
            map.Width  = 380;
            map.Height = 380;
            host.Child = map;
            map.Show();
            map.CreateControl();
            map.ShowZoomBar     = false;
            map.ShowCoordinates = MapWinGIS.tkCoordinatesDisplay.cdmNone;
            map.CursorMode      = MapWinGIS.tkCursorMode.cmNone;

            MapWinGIS.Shapefile shapeFileMap = new MapWinGIS.Shapefile();
            shapeFileMap.Open(@"D:\Projets\TheManager\TheManager_GUI\bin\Debug\gis\world\World_Countries.shp", null);
            map.AddLayer(shapeFileMap, true);
            ILocalisation localisation = Session.Instance.Game.kernel.LocalisationTournament(t.Tournament);
            double        logoSize     = 30.0;

            if (localisation as Country != null)
            {
                map.ZoomToShape(0, (localisation as Country).ShapeNumber);
            }
            else
            {
                if (localisation.Name() == "Europe")
                {
                    map.ZoomToShape(0, 68 /*12 101*/);
                    map.CurrentZoom = 4;
                }
                else if (localisation.Name() == "Africa")
                {
                    map.ZoomToShape(0, 40);
                    map.CurrentZoom = 3;
                }
                logoSize = 15.0;
            }

            foreach (Club c in t.clubs)
            {
                CityClub cc = c as CityClub;
                if (cc != null)
                {
                    double projX = -1;
                    double projY = -1;
                    map.DegreesToProj(cc.city.Position.Longitude, cc.city.Position.Latitude, ref projX, ref projY);

                    MapWinGIS.Image img = new MapWinGIS.Image();
                    img.Open(Utils.Logo(c));

                    MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                    sf.CreateNew("", MapWinGIS.ShpfileType.SHP_POINT);
                    sf.DefaultDrawingOptions.AlignPictureByBottom = false;
                    sf.DefaultDrawingOptions.PointType            = MapWinGIS.tkPointSymbolType.ptSymbolPicture;
                    sf.DefaultDrawingOptions.Picture       = img;
                    sf.DefaultDrawingOptions.PictureScaleX = Math.Round(logoSize / img.OriginalWidth, 2);
                    sf.DefaultDrawingOptions.PictureScaleY = Math.Round(logoSize / img.OriginalHeight, 2);
                    sf.CollisionMode = MapWinGIS.tkCollisionMode.AllowCollisions;

                    MapWinGIS.Shape shp = new MapWinGIS.Shape();
                    shp.Create(MapWinGIS.ShpfileType.SHP_POINT);
                    shp.AddPoint(projX, projY);
                    sf.EditAddShape(shp);

                    map.AddLayer(sf, true);
                }
            }
            if (_competition.rounds[_indexTour].clubs.Count > 0 && _competition.rounds[_indexTour].clubs[0] as NationalTeam != null)
            {
                shapeFileMap.StartEditingTable();
                int fieldIndex = shapeFileMap.EditAddField("Qualification", MapWinGIS.FieldType.INTEGER_FIELD, 1, 1);
                shapeFileMap.DefaultDrawingOptions.FillType = MapWinGIS.tkFillType.ftStandard;
                for (int i = 0; i < shapeFileMap.NumShapes; i++)
                {
                    shapeFileMap.EditCellValue(fieldIndex, i, 0);
                }
                Dictionary <NationalTeam, int> clubCourses = new Dictionary <NationalTeam, int>();
                for (int i = 0; i < _competition.rounds.Count; i++)
                {
                    Round round = _competition.rounds[i];
                    foreach (Club c in round.clubs)
                    {
                        NationalTeam nt = c as NationalTeam;
                        if (!clubCourses.ContainsKey(nt))
                        {
                            clubCourses.Add(nt, 1);
                        }
                        clubCourses[nt] = i + 1;
                    }
                }
                foreach (KeyValuePair <NationalTeam, int> kvp in clubCourses)
                {
                    shapeFileMap.EditCellValue(fieldIndex, kvp.Key.country.ShapeNumber, kvp.Value);
                }
                shapeFileMap.Categories.Generate(fieldIndex, MapWinGIS.tkClassificationType.ctUniqueValues, _competition.rounds.Count + 1);
                shapeFileMap.Categories.ApplyExpressions();
                MapWinGIS.ColorScheme colorScheme = new MapWinGIS.ColorScheme();
                colorScheme.SetColors2(MapWinGIS.tkMapColor.AliceBlue, MapWinGIS.tkMapColor.DarkBlue);
                shapeFileMap.Categories.ApplyColorScheme(MapWinGIS.tkColorSchemeType.ctSchemeGraduated, colorScheme);
            }
            map.Redraw();
        }
示例#24
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();
        }
示例#25
0
文件: MapWindow.cs 项目: zzzpppNj/P6
        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);
                }
            }
        }
示例#26
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);
        }
示例#27
0
        /// <summary>
        /// 打开指定数据源的图层
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public bool Open(string filename, MapWinGIS.ICallback callback)
        {
            this.Close();

            if (filename.ToLower().EndsWith(".shp"))
            {
                MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
                if (sf.Open(filename, callback))
                {
                    // 检查dbf是否存在
                    bool error = false;
                    if (!File.Exists(Path.ChangeExtension(sf.Filename, ".dbf")))
                    {
                        m_error = LayerSourceError.DbfIsMissing;
                        error   = true;
                    }

                    // 检查DBF记录数相匹配的形状的数量。
                    MapWinGIS.Table table = new MapWinGIS.Table();
                    table.Open(Path.ChangeExtension(sf.Filename, ".dbf"), null);
                    if (sf.NumShapes != table.NumRows)
                    {
                        m_error = LayerSourceError.DbfRecordCountMismatch;
                        error   = true;
                    }

                    table.Close();

                    if (error)
                    {
                        sf.Close();
                    }
                    else
                    {
                        m_shapefile = sf;
                    }
                    return(!error);
                }
                else
                {
                    m_error       = LayerSourceError.OcxBased;
                    m_ErrorString = sf.get_ErrorMsg(sf.LastErrorCode);
                }
            }
            else
            {
                bool asGrid = true;
                if (filename.ToLower().EndsWith(".tif"))
                {
                    asGrid = false;
                }

                // TODO: 可能更聪明的选择是在grid/image中使用应用程序设置
                if (asGrid)
                {
                    MapWinGIS.Grid grid = new MapWinGIS.Grid();
                    if (grid.Open(filename, MapWinGIS.GridDataType.UnknownDataType, false, MapWinGIS.GridFileType.UseExtension, callback))
                    {
                        m_grid = grid;
                        return(true);
                    }
                }

                // 尝试image
                MapWinGIS.Image image = new MapWinGIS.Image();
                if (image.Open(filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, callback))
                {
                    m_image = image;
                    return(true);
                }
                else
                {
                    m_error       = LayerSourceError.OcxBased;
                    m_ErrorString = image.get_ErrorMsg(image.LastErrorCode);
                }
            }
            return(false);
        }
示例#28
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));
                }
            }
        }
示例#29
0
 private void populateFields(string shpFileName)
 {
     cmbFields.Items.Clear();
     MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile();
     MapWinGIS.Field curField;
     if (sf.Open(shpFileName,sf.GlobalCallback))
     {
         for (int i = 0; i < sf.NumFields; ++i)
         {
             curField = sf.get_Field(i);
             if (curField.Type == MapWinGIS.FieldType.DOUBLE_FIELD ||
                 curField.Type == MapWinGIS.FieldType.INTEGER_FIELD)
             {
                 cmbFields.Items.Add(curField.Name);
             }
         }
         sf.Close();
     }
     if (cmbFields.Items.Count > 0)
     {
         cmbFields.SelectedIndex = 0;
     }
 }