Beispiel #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            string connectionStr = "server=127.0.0.1;user id=root;password=newpassword;database=gzuguide";

            connection_ = new MySqlConnection(connectionStr);
            connection_.Open();

            string           StopSql   = "select BSName from busstops where Note =" + 1;
            MySqlDataAdapter stopad    = new MySqlDataAdapter(StopSql, connection_);
            DataTable        stopTable = new DataTable();

            stopad.Fill(stopTable);
            string addName;

            for (int i = 0; i < stopTable.Rows.Count; i++)
            {
                addName = stopTable.Rows[i][0].ToString();
                comboBox1.Items.Add(addName);
                comboBox2.Items.Add(addName);
            }

            MapWinGIS.Shapefile shpfile1 = new MapWinGIS.Shapefile();
            MapWinGIS.Shapefile shpfile2 = new MapWinGIS.Shapefile();
            int    intHandler1;
            int    intHandler2;
            string filename  = "G:\\#导航设计\\广州大学城矢量地图\\广州大学城全要素地图\\广州大学城全要素地图\\道路\\boundary.shp";
            string filename2 = "G:\\#导航设计\\广州大学城矢量地图\\广州大学城全要素地图\\广州大学城全要素地图\\dxc_vector\\dxc_vector\\road";

            shpfile1.Open(filename, null);
            shpfile2.Open(filename2, null);
            intHandler1       = axMap1.AddLayer(shpfile1, true);
            intHandler2       = axMap1.AddLayer(shpfile2, true);
            axMap1.CursorMode = MapWinGIS.tkCursorMode.cmPan;
        }
        /// <summary>
        /// Constructor for setting label expression and options
        /// </summary>
        public LabelStyleForm(LegendControl.Legend legend, MapWinGIS.Shapefile sf, int handle)
        {
            if (sf == null)
            {
                throw new Exception("LabelStyleForm: unexpected null parameter");
            }
            m_legend    = legend;
            m_shapefile = sf;
            m_handle    = handle;

            InitializeComponent();

            //LabelStyle style = new LabelStyle( m_shapefile.Labels.Options);

            // old-style labels not based on expression
            if (m_shapefile.Labels.Expression == "" && m_shapefile.Labels.Count > 0 &&
                m_shapefile.Labels.get_Label(0, 0).Text != "")
            {
                richTextBox1.Text    = "<no expression>";
                listBox1.Enabled     = false;
                btnPlus.Enabled      = false;
                btnQuotes.Enabled    = false;
                btnNewLine.Enabled   = false;
                richTextBox1.Enabled = false;
            }
            else
            {
                richTextBox1.Text = LabelUtilities.StripNewLineQuotes(m_shapefile.Labels.Expression);
            }

            this.Initialize(m_shapefile.Labels.Options);

            tabControl1.SelectedIndex = tabNumber;
        }
Beispiel #3
0
        private int Add(AxMap map, object layer, bool Visible)
        {
            if (layer == null)
            {
                return(-1);
            }
            if (map == null)
            {
                throw new System.Exception("MapWinGIS.Map Object not yet set. Set Map Property before adding layers");
            }

            map.LockWindow(MapWinGIS.tkLockMode.lmLock);
            int MapLayerHandle = map.AddLayer(layer, Visible);

            if (MapLayerHandle < 0)
            {
                map.LockWindow(MapWinGIS.tkLockMode.lmUnlock);
                return(MapLayerHandle);
            }

            MapWinGIS.Shapefile sf = (layer as MapWinGIS.Shapefile);

            map.LockWindow(MapWinGIS.tkLockMode.lmUnlock);

            // FireLayerAdded(MapLayerHandle);

            return(MapLayerHandle);
        }
        /// <summary>
        /// Draws preview based on the specified expression string
        /// </summary>
        internal static void DrawPreview(LabelCategory category, MapWinGIS.Shapefile sf, System.Windows.Forms.PictureBox canvas, string expression, bool forceDrawing)
        {
            // retrieving text
            string s = get_LabelText(sf, expression);

            if (s.Trim() == string.Empty)
            {
                s = "";
            }

            Bitmap   img = new Bitmap(canvas.ClientRectangle.Width, canvas.ClientRectangle.Height);
            Graphics g   = Graphics.FromImage(img);

            //const int count = 50;
            //Pen gridPen = new Pen(Color.LightGray);
            //float step = (float)img.Height/count;
            //for (int i = 0; i < count; i++)
            //{
            //    g.DrawLine(gridPen, 0.0f, step * (float)i, (float)img.Width, step * (float)i);
            //}
            //step = (float)img.Width / count;
            //for (int j = 0; j < count; j++)
            //{
            //    g.DrawLine(gridPen, step * (float)j, 0.0f, step * (float)j, (float)img.Height);
            //}

            System.Drawing.Point pntOrigin = new System.Drawing.Point((canvas.ClientRectangle.Right + canvas.ClientRectangle.Left) / 2,
                                                                      (canvas.ClientRectangle.Bottom + canvas.ClientRectangle.Top) / 2);

            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode     = SmoothingMode.HighQuality;

            // drawing the label
            LabelStyle style = new LabelStyle(category);

            if (sf.Labels.Count > 0 || forceDrawing)
            {
                // drawing base point
                Pen       pen  = new Pen(Color.Black, 2);
                Rectangle rect = new Rectangle((int)pntOrigin.X, (int)pntOrigin.Y, 2, 2);
                //g.DrawEllipse(pen, rect);
                pen.Dispose();

                style.Draw(g, pntOrigin, s, true, 0);
            }

            if (canvas.Image != null)
            {
                canvas.Image.Dispose();
            }

            canvas.Image = img;
        }
Beispiel #5
0
        /// <summary>
        /// Create shapefile named shapeName  Any existing shapefile of the same name is deleted.
        /// </summary>
        /// <param name="shapeName">Path of output shapefile</param>
        /// <param name="cb">Callback for reporting errors</param>
        /// <returns>null if any error, else shapefile</returns>
        public MapWinGIS.Shapefile makeShapefile(string shapeName, MapWinGIS.ICallback cb)
        {
            MapWinGeoProc.DataManagement.DeleteShapefile(ref shapeName);
            MapWinGIS.Shapefile shpfile = new MapWinGIS.Shapefile();
            if (!shpfile.CreateNew(shapeName, ShpfileType.SHP_POLYGON))
            {
                if (cb != null)
                {
                    cb.Error("ManhattanShapes.makeShapefile", clsUtils.ManhattanShapes.nocreateshapefile + shapeName);
                }
                return(null);
            }
            if (!shpfile.StartEditingShapes(true, null))
            {
                if (cb != null)
                {
                    cb.Error("ManhattanShapes.makeShapefile", clsUtils.ManhattanShapes.noeditshapefile + shapeName);
                }
                return(null);
            }
            int shapeindex = 0;

            foreach (int k in ShapesTable.Keys)
            {
                if (!InsertShape(shpfile, k, ref shapeindex))
                {
                    if (cb != null)
                    {
                        cb.Error("ManhattanShapes.makeShapefile", clsUtils.ManhattanShapes.noaddshape + shapeName);
                    }
                    shpfile.StopEditingShapes(true, true, null);
                    shpfile.Close();
                    return(null);
                }
            }
            if (!shpfile.StopEditingShapes(true, true, null))
            {
                if (cb != null)
                {
                    cb.Error("ManhattanShapes.makeShapefile", clsUtils.ManhattanShapes.noeditshapefile + shapeName);
                }
                return(null);
            }
            if (!shpfile.Close())
            {
                if (cb != null)
                {
                    cb.Error("ManhattanShapes.makeShapefile", clsUtils.ManhattanShapes.nocloseshapefile + shapeName);
                }
                return(null);
            }
            return(shpfile);
        }
Beispiel #6
0
 /// <summary>
 /// Creates and adds shape corresponding to grid value val to shapeFile
 /// </summary>
 /// <param name="shapeFile"></param>
 /// <param name="val"></param>
 /// <param name="shapeIndex">set to index of added shape</param>
 /// <returns>true if shape successfully added</returns>
 public bool InsertShape(MapWinGIS.Shapefile shapeFile, int val, ref int shapeIndex)
 {
     MapWinGIS.Shape shape = offset.makeShape(ShapesTable[val].polygons);
     if (shape == null)
     {
         return(false);
     }
     else
     {
         return(shapeFile.EditInsertShape(shape, ref shapeIndex));
     }
 }
Beispiel #7
0
        /// <summary>
        /// returns the shape's attribute field value
        /// </summary>
        private object GetCellValue(MapWinGIS.Shapefile sf, int fieldIndex, int shapeIndex, object noDt)
        {
            object value;

            try
            {
                value = sf.get_CellValue(fieldIndex, shapeIndex);
            }
            catch (Exception ex)
            {
                value = noDt; //if no data is returned
            }
            return(value);
        }
Beispiel #8
0
        private bool Multipoint2Grid(MapWinGIS.Shapefile MultipointSf, int FldID, MapWinGIS.Grid Newgrd,
                                     MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback)
        {
            //count the number of shapes
            int s, p;

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

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

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

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

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

                //report the progress
                if (s >= shpsPerc)
                {
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                }
            }
            return(true);
        }
Beispiel #9
0
        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openshp = new OpenFileDialog();

            MapWinGIS.Shapefile shpfile1 = new MapWinGIS.Shapefile();
            openshp.Filter           = "shp文件|*.shp";
            openshp.RestoreDirectory = true;
            int intHandler1;

            if (openshp.ShowDialog() == DialogResult.OK)
            {
                shpfile1.Open(openshp.FileName, null);
                intHandler1 = axMap1.AddLayer(shpfile1, true);
            }
        }
        private void PopulateForm(bool ShowAfterward, MapWinGIS.Shapefile shapeFile, int shpIndex, bool calledBySelf)
        {
            if (!calledBySelf)
            {
                m_HavePanel = !ShowAfterward;
            }

            try
            {
                System.Windows.Forms.ListViewItem item;
                int numFields;
                m_ShapeFile = shapeFile;

                //clear the list view items
                lv.Items.Clear();

                numFields = shapeFile.NumFields;
                for (int i = 0; i < numFields; i++)
                {
                    string s = shapeFile.get_CellValue(i, shpIndex).ToString();
                    item = lv.Items.Add(shapeFile.get_Field(i).Name);
                    item.SubItems.Add(s);

                    item.ForeColor = Color.Black;
                    if (s.ToLower().StartsWith("http") || s.ToLower().StartsWith("file://"))
                    {
                        item.ForeColor = Color.Blue;
                    }
                }

                //color the current shape red
                if (m_SelShape != -1)
                {
                    m_parent.m_MapWin.View.SelectedShapes.AddByIndex(m_SelShape, YELLOW);
                }
                m_SelShape = shpIndex;
                m_parent.m_MapWin.View.SelectedShapes.AddByIndex(shpIndex, RED);

                if (ShowAfterward)
                {
                    this.Show();
                }
            }
            catch (System.Exception ex)
            {
                ShowErrorBox("PopulateForm()", ex.Message);
            }
        }
Beispiel #11
0
        /// <summary>
        /// convert point shapefile to grid
        /// </summary>
        private bool Point2Grid(MapWinGIS.Shapefile PointSf, int FldID, MapWinGIS.Grid Newgrd,
                                MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback)
        {
            //count the number of shapes
            int s;

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

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

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

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

                //report the progress
                if (s >= shpsPerc)
                {
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                }
            }
            return(true);
        }
        /// <summary>
        /// Handles the clicking on the layer color box
        /// </summary>
        /// <param name="Handle"></param>
        void m_legend_LayerColorboxClicked(int Handle)
        {
            if (m_legend == null || m_legend.m_Map == null)
            {
                return;
            }

            MapWinGIS.Shapefile sf = m_legend.m_Map.get_Shapefile(Handle);
            if (sf != null)
            {
                Form form = FormHelper.GetSymbologyForm(m_legend, Handle, sf.ShapefileType, sf.DefaultDrawingOptions, false);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // do something
                }
                form.Dispose();
            }
        }
Beispiel #13
0
        public int get_MaxIconWidth(MapWinGIS.Shapefile sf)
        {
            if (sf == null)
            {
                return(0);
            }
            int maxWidth = GetCategoryWidth(sf.DefaultDrawingOptions);

            for (int i = 0; i < sf.Categories.Count; i++)
            {
                int width = GetCategoryWidth(sf.Categories.get_Item(i).DrawingOptions);
                if (width > maxWidth)
                {
                    maxWidth = width;
                }
            }
            return(maxWidth);
        }
        /// <summary>
        /// Handles the clicking on the labels for a layer
        /// </summary>
        /// <param name="Handle"></param>
        void m_legend_LayerLabelsClicked(int Handle)
        {
            if (m_legend == null || m_legend.m_Map == null)
            {
                return;
            }

            MapWinGIS.Shapefile sf = m_legend.m_Map.get_Shapefile(Handle);
            if (sf != null)
            {
                using (Form form = new LabelStyleForm(m_legend, sf, Handle))
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        m_legend.Refresh();
                    }
                }
            }
        }
        /// <summary>
        /// Constructor for editing single category
        /// </summary>
        /// <param name="lb"></param>
        public LabelStyleForm(MapWinGIS.Shapefile sf, MapWinGIS.LabelCategory lb)
        {
            m_categoryEdited = true;
            m_shapefile      = sf;

            InitializeComponent();
            this.Initialize(lb);

            tabControl1.SelectedIndex = tabNumber;

            // expression isn't available for the categories
            if (m_categoryEdited)
            {
                tabControl1.TabPages.Remove(tabControl1.TabPages[4]);   // visibility
                tabControl1.TabPages.Remove(tabControl1.TabPages[3]);   // position
                tabControl1.TabPages.Remove(tabControl1.TabPages[0]);   // expression
            }
            lblResult.Visible = false;
            btnApply.Visible  = false;
        }
        /// <summary>
        /// Reprojects layer of undefined type
        /// </summary>
        /// <param name="filename">Filename of layer to reproject. A changed name will be returned when new file was created</param>
        /// <param name="projection">New projection</param>
        /// <param name="inPlace">Whether new files should be written</param>
        /// <param name="report">A reference to report form</param>
        /// <returns>True on success and false otherwise</returns>
        public static TestingResult ReprojectLayer(LayerSource layer, out LayerSource newLayer, MapWinGIS.GeoProjection projection, frmTesterReport report)
        {
            newLayer = null;
            TestingResult result = TestingResult.Error;

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

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

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

            default:
                System.Diagnostics.Debug.Print("Coordinate transformation: unsupported interface");
                break;
            }
            return(result);
        }
        /// <summary>
        /// Creates a new instance of the AddChartsForm class
        /// </summary>
        public AddChartsForm(MapWinGIS.Shapefile sf)
        {
            InitializeComponent();

            m_shapefile = sf;

            ShpfileType type = Globals.ShapefileType2D(m_shapefile.ShapefileType);

            if (type == ShpfileType.SHP_POLYGON)
            {
                optPosition1.Text    = "Center";
                optPosition2.Text    = "Centroid";
                optPosition3.Text    = "Interior point";
                optPosition4.Visible = false;

                optPosition1.Tag = tkLabelPositioning.lpCenter;
                optPosition2.Tag = tkLabelPositioning.lpCentroid;
                optPosition3.Tag = tkLabelPositioning.lpInteriorPoint;

                groupBox5.Height -= 30;
                this.Height      -= 30;

                optPosition2.Checked = true;
            }
            else if (type == ShpfileType.SHP_POLYLINE)
            {
                optPosition1.Text = "First segment";
                optPosition2.Text = "Last segment";
                optPosition3.Text = "Middle segment";
                optPosition4.Text = "Longest segment";

                optPosition1.Tag = tkLabelPositioning.lpFirstSegment;
                optPosition2.Tag = tkLabelPositioning.lpLastSegment;
                optPosition3.Tag = tkLabelPositioning.lpMiddleSegment;
                optPosition4.Tag = tkLabelPositioning.lpLongestSegement;

                optPosition4.Checked = true;
            }
        }
        /// <summary>
        /// Handling the clicking on the category preview
        /// </summary>
        void m_legend_LayerCategoryClicked(int Handle, int Category)
        {
            if (m_legend == null || m_legend.m_Map == null)
            {
                return;
            }

            MapWinGIS.Shapefile sf = m_legend.m_Map.get_Shapefile(Handle);
            if (sf != null)
            {
                MapWinGIS.ShapefileCategory cat = sf.Categories.get_Item(Category);
                if (cat != null)
                {
                    Form form = FormHelper.GetSymbologyForm(m_legend, Handle, sf.ShapefileType, cat.DrawingOptions, false);
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        // do something
                    }
                    form.Dispose();
                }
            }
        }
 /// <summary>
 /// Retunrns label string formed by the first record of attribute table
 /// </summary>
 internal static string get_LabelText(MapWinGIS.Shapefile sf, string expression)
 {
     if (expression.ToLower() == "<no expression>")
     {
         if (sf.Labels.Count > 0)
         {
             return(sf.Labels.get_Label(0, 0).Text);
         }
         else
         {
             return("");
         }
     }
     else
     {
         bool byField = false;
         if (byField)
         {
             int index = sf.Labels.ClassificationField;
             var val   = sf.Table.get_CellValue(index, 0) as object;
             if (val != null)
             {
                 return(val.ToString());
             }
         }
         else
         {
             object obj; string err;
             expression = LabelUtilities.FixExpression(expression);
             if (sf.Table.Calculate(expression, 0, out obj, out err))
             {
                 return(obj.ToString());
             }
         }
         return("");
     }
 }
        /// <summary>
        /// Creates a new instance of the frmGenerateLabelCategories class
        /// </summary>
        public frmGenerateLabelCategories(LegendControl.Legend legend, MapWinGIS.Shapefile sf, int layerHandle)
        {
            InitializeComponent();

            m_shapefile   = sf;
            m_legend      = legend;
            m_layerHandle = layerHandle;

            Layer layer = legend.Layers.ItemByHandle(layerHandle);

            // classification
            cboClassificationType.Items.Clear();
            cboClassificationType.Items.Add("Natural breaks");
            cboClassificationType.Items.Add("Unique values");
            cboClassificationType.Items.Add("Quantiles");
            cboClassificationType.Items.Add("Equal intervals");

            // number of categories
            cboCategoriesCount.Items.Clear();
            for (int i = 3; i <= 25; i++)
            {
                cboCategoriesCount.Items.Add(Convert.ToString(i));
            }

            // initializing for list of color schemes
            icbFrame.ComboStyle = ImageComboStyle.ColorSchemeGraduated;
            Globals.LayerColors.SetFirstColorScheme(m_shapefile.Labels.FrameBackColor);
            icbFrame.ColorSchemes = Globals.LayerColors;

            udMinSize.Value = sf.Labels.FontSize;

            LoadOptions();

            RefreshControlsState(null, null);

            DrawPreview();
        }
        /// <summary>
        /// Initializes a new instance of the ChartStyleForm class
        /// </summary>
        public ChartStyleForm(LegendControl.Legend legend, MapWinGIS.Shapefile sf, bool legendCall, int handle)
        {
            InitializeComponent();
            _shapefile = sf;
            _charts    = sf.Charts;
            m_legend   = legend;
            _handle    = handle;

            MapWinGIS.tkSavingMode mode = _charts.SavingMode;
            _charts.SavingMode = MapWinGIS.tkSavingMode.modeNone;
            _initState         = _charts.Serialize();
            _charts.SavingMode = mode;

            _noEvents = true;

            panelPieChart.Top  = panelBarChart.Top;
            panelPieChart.Left = panelBarChart.Left;

            foreach (FontFamily family in FontFamily.Families)
            {
                cboFontName.Items.Add(family.Name);
            }

            cboValuesStyle.Items.Clear();
            cboValuesStyle.Items.Add("Horizontal");
            cboValuesStyle.Items.Add("Vertical");

            cboChartVerticalPosition.Items.Clear();
            cboChartVerticalPosition.Items.Add("Above current layer");
            cboChartVerticalPosition.Items.Add("Above all layers");

            optBarCharts.Checked = (_charts.ChartType == MapWinGIS.tkChartType.chtBarChart);
            optPieCharts.Checked = (_charts.ChartType == MapWinGIS.tkChartType.chtPieChart);

            // initializing for list of color schemes
            icbColors.ColorSchemes = Globals.ChartColors;
            icbColors.ComboStyle   = ImageComboStyle.ColorSchemeGraduated;
            if (icbColors.Items.Count > 0)
            {
                icbColors.SelectedIndex = 0;
            }

            string[] scales = { "1",      "10",     "100",     "1000", "5000", "10000", "25000", "50000", "100000",
                                "250000", "500000", "1000000", "10000000" };
            cboMinScale.Items.Clear();
            cboMaxScale.Items.Clear();
            for (int i = 0; i < scales.Length; i++)
            {
                cboMinScale.Items.Add(scales[i]);
                cboMaxScale.Items.Add(scales[i]);
            }

            txtChartExpression.Text = sf.Charts.VisibilityExpression;

            SetChartsType();

            InitFields();

            _noEvents = false;

            Settings2GUI();

            Draw();

            RefreshControlsState();

            tabControl1.SelectedIndex = _selectedTab;
        }
        public void PopulateForm(bool ShowAfterward, MapWinGIS.Shapefile shapeFile, string layerName, bool calledBySelf)
        {
            if (!calledBySelf)
            {
                m_HavePanel = !ShowAfterward;
            }

            try
            {
                int    numFields;
                string fieldName;
                m_ShapeFile = shapeFile;
                m_shpIndex  = null;

                m_LayerName = layerName;
                SetTitle();

                //new selected shapes
                m_SelShape = -1;

                //clear the selected box
                m_parent.m_MapWin.View.Draw.ClearDrawing(m_parent.m_hDraw);

                //clear the list view items
                lv.Items.Clear();
                cb.Items.Clear();
                cb.Text = "";

                //clear the combo Box field Name
                cbFieldName.Items.Clear();
                cbFieldName.Items.Add("Shape Index");
                cb.Text = "";

                numFields = shapeFile.NumFields;
                for (int i = 0; i < numFields; i++)
                {
                    fieldName = shapeFile.get_Field(i).Name;
                    lv.Items.Add(fieldName);

                    //add all the field name to the combo box
                    cbFieldName.Items.Add(fieldName);
                }

                //select the first field
                if (cbFieldName.Items.IndexOf(m_FieldName) == -1)
                {
                    cbFieldName.SelectedIndex = 0;
                }
                else
                {
                    cbFieldName.SelectedItem = m_FieldName;
                }

                if (ShowAfterward)
                {
                    this.Show();
                }
            }
            catch (System.Exception ex)
            {
                ShowErrorBox("PopulateForm()", ex.Message);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Converts grid to a shapefile, removing any existing shapefile.
        /// Assumed to be an integer grid.  Adds attribute headed id with the grid values, and
        /// attribute headed "Area" with the area for each polygon.
        /// </summary>
        /// <param name="gridName">Path of input grid</param>
        /// <param name="shapeName">Path of output shapefile</param>
        /// <param name="id">String to use for name of grid values attribute</param>
        /// <param name="cb">Callback for reporting errors</param>
        /// <returns>null if any errors, else shapefile</returns>
        public static MapWinGIS.Shapefile GridToShapeManhattan(string gridName, string shapeName,
                                                               string id, MapWinGIS.ICallback cb)
        {
            if (!System.IO.File.Exists(gridName))
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.nogrid + gridName);
                }
                return(null);
            }
            MapWinGIS.Grid grid = new MapWinGIS.GridClass();
            if (!grid.Open(gridName, GridDataType.UnknownDataType, true, GridFileType.UseExtension, null))
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noopengrid + gridName);
                }
                return(null);
            }
            MapWinGIS.GridHeader header = grid.Header;
            int numRows = header.NumberRows;
            int numCols = header.NumberCols;

            MapWinGeoProc.DataManagement.DeleteShapefile(ref shapeName);
            string oldProj = System.IO.Path.ChangeExtension(gridName, ".prj");
            string newProj = System.IO.Path.ChangeExtension(shapeName, ".prj");

            if (System.IO.File.Exists(oldProj) && !oldProj.Equals(newProj))
            {
                System.IO.File.Copy(oldProj, newProj);
            }
            MapWinGIS.Shapefile shapeFile = new MapWinGIS.Shapefile();
            bool success = shapeFile.CreateNew(shapeName, ShpfileType.SHP_POLYGON);

            if (!success)
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.nocreateshapefile + shapeName);
                }
                return(null);
            }
            success = shapeFile.StartEditingShapes(true, null);
            if (!success)
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditshapefile + shapeName);
                }
                return(null);
            }
            ManhattanShapes shapes = new ManhattanShapes(header);

            for (int i = 0; i < numRows; i++)
            {
                shapes.addGridRow(grid, i, numCols);
            }
            if (!shapes.lastError.Equals(""))
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", shapes.lastError);
                }
                return(null);
            }
            grid.Close();
            shapes.FinishShapes();
            MapWinGIS.Field idField = new MapWinGIS.Field();
            idField.Name = id;
            idField.Type = FieldType.INTEGER_FIELD;
            int idIndex = 0;

            success = shapeFile.EditInsertField(idField, ref idIndex, null);
            if (!success)
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noaddfield + shapeName);
                }
                shapeFile.Close();
                return(null);
            }
            MapWinGIS.Field areaField = new MapWinGIS.Field();
            areaField.Name = "Area";
            areaField.Type = FieldType.DOUBLE_FIELD;
            int areaIndex = 1;

            success = shapeFile.EditInsertField(areaField, ref areaIndex, null);
            if (!success)
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noaddfield + shapeName);
                }
                shapeFile.Close();
                return(null);
            }
            int shapeIndex = 0;

            foreach (int k in shapes.ShapesTable.Keys)
            {
                success = shapes.InsertShape(shapeFile, k, ref shapeIndex);
                if (!success)
                {
                    if (cb != null)
                    {
                        cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noaddshape + shapeName);
                    }
                    shapeFile.Close();
                    return(null);
                }
                success = shapeFile.EditCellValue(idIndex, shapeIndex, k);
                if (!success)
                {
                    if (cb != null)
                    {
                        cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditcell + shapeName);
                    }
                    shapeFile.Close();
                    return(null);
                }
                double area = shapes.Area(k);
                success = shapeFile.EditCellValue(areaIndex, shapeIndex, area);
                if (!success)
                {
                    if (cb != null)
                    {
                        cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditcell + shapeName);
                    }
                    shapeFile.Close();
                    return(null);
                }
            }
            success = shapeFile.StopEditingShapes(true, true, null);
            if (!success)
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditshapefile + shapeName);
                }
                shapeFile.Close();
                return(null);
            }
            if (!shapeFile.Close())
            {
                if (cb != null)
                {
                    cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.nocloseshapefile + shapeName);
                }
                return(null);
            }
            return(shapeFile);
        }
Beispiel #24
0
        private void SetLocationMap_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 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);

            axMap1.SendMouseDown   = true;
            axMap1.MouseDownEvent += axMap1_MouseDownEvent;
            axMap1.CursorMode      = tkCursorMode.cmNone;

            if (File.Exists("..\\..\\devloc.txt"))
            {
                Loc = Convert.ToInt32(File.ReadAllText("..\\..\\devloc.txt"));
            }
        }
        /// <summary>
        /// Draws preview based on the category options and expression stored in the Labels class
        /// </summary>
        internal static void DrawPreview(LabelCategory category, MapWinGIS.Shapefile sf, System.Windows.Forms.PictureBox canvas, bool forceDrawing)
        {
            string expression = (sf.Labels.Expression == "" && sf.Labels.Count != 0) ? "<no expression>" : sf.Labels.Expression;

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

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

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

            MapWinGIS.Shape PolyShp; //the polygon shape

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

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

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

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

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

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

                b     = -1;
                tempn = 0;

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

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

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

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

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

                //define the first line-scan
                double xstart;

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

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

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

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

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

            reportProgress(100, 100, "shapefile to grid", cback); //100 % shapes done
            return(true);
        }
        internal tkLabelAlignment m_alignment; // = tkLabelAlignment.laCenter;

        /// <summary>
        /// Creates a new instance of the AddLabelsForm
        /// </summary>
        public AddLabelsForm(MapWinGIS.Shapefile sf, tkLabelAlignment alignment)
        {
            InitializeComponent();

            if (sf == null)
            {
                throw new Exception("AddLabelsForm: Unexpected null parameter");
            }

            m_alignment = alignment;
            m_shapefile = sf;
            cboLineOrientation.Enabled = false;
            panel1.Visible             = false;

            ShpfileType type = Globals.ShapefileType2D(m_shapefile.ShapefileType);

            if (type == ShpfileType.SHP_POLYGON)
            {
                optPosition1.Text    = "Center";
                optPosition2.Text    = "Centroid";
                optPosition3.Text    = "Interior point";
                optPosition4.Visible = false;

                optPosition1.Tag = tkLabelPositioning.lpCenter;
                optPosition2.Tag = tkLabelPositioning.lpCentroid;
                optPosition3.Tag = tkLabelPositioning.lpInteriorPoint;

                groupBox5.Height -= 30;
                groupBox4.Top    -= 30;
                this.Height      -= 30;

                optPosition2.Checked = true;        // TODO: choose according Labels.Positioning
            }
            else if (type == ShpfileType.SHP_POLYLINE)
            {
                optPosition1.Text = "First segment";
                optPosition2.Text = "Last segment";
                optPosition3.Text = "Middle segment";
                optPosition4.Text = "The longest segment";

                optPosition1.Tag = tkLabelPositioning.lpFirstSegment;
                optPosition2.Tag = tkLabelPositioning.lpLastSegment;
                optPosition3.Tag = tkLabelPositioning.lpMiddleSegment;
                optPosition4.Tag = tkLabelPositioning.lpLongestSegement;

                optPosition4.Checked       = true; // TODO: choose according Labels.Positioning
                cboLineOrientation.Enabled = true;
            }
            else
            {
                panel1.Visible       = true;
                optPosition1.Visible = false;
                optPosition2.Visible = false;
                optPosition3.Visible = false;
                optPosition4.Visible = false;
                this.Height         -= 100;
                groupBox4.Visible    = false;

                optAlignBottomCenter.Checked = (m_alignment == tkLabelAlignment.laBottomCenter);
                optAlignBottomLeft.Checked   = (m_alignment == tkLabelAlignment.laBottomLeft);
                optAlignBottomRight.Checked  = (m_alignment == tkLabelAlignment.laBottomRight);
                optAlignCenterLeft.Checked   = (m_alignment == tkLabelAlignment.laCenterLeft);
                optAlignCenterRight.Checked  = (m_alignment == tkLabelAlignment.laCenterRight || m_alignment == tkLabelAlignment.laCenter);
                optAlignTopCenter.Checked    = (m_alignment == tkLabelAlignment.laTopCenter);
                optAlignTopLeft.Checked      = (m_alignment == tkLabelAlignment.laTopLeft);
                optAlignTopRight.Checked     = (m_alignment == tkLabelAlignment.laTopRight);

                // Applicable for polyline and polygon shapefiles
                //throw new Exception("AddLabelsForm: invalid shapefile type");
            }

            // line orientation
            cboLineOrientation.Items.Clear();
            cboLineOrientation.Items.Add("Horizontal");
            cboLineOrientation.Items.Add("Parallel");
            cboLineOrientation.Items.Add("Perpendicular");
            cboLineOrientation.SelectedIndex = 1;
        }
        /// <summary>
        /// Generates a new instance of the GenerateCategoriesForm class
        /// </summary>
        public GenerateCategoriesForm(MapWinGIS.Shapefile sf, int layerHandle)
        {
            InitializeComponent();

            _shapefile   = sf;
            _layerHandle = layerHandle;
            if (sf == null)
            {
                return;
            }

            SymbologySettings settings = new SymbologySettings();// _plugin.get_LayerSettings(layerHandle);

            // classification
            cboClassificationType.Items.Clear();
            cboClassificationType.Items.Add("Natural breaks");
            cboClassificationType.Items.Add("Unique values");
            cboClassificationType.Items.Add("Equal intervals");
            cboClassificationType.Items.Add("Quantiles");
            cboClassificationType.SelectedIndex = (int)settings.CategoriesClassification;

            // number of categories
            cboCategoriesCount.Items.Clear();
            for (int i = 3; i <= 25; i++)
            {
                cboCategoriesCount.Items.Add(Convert.ToString(i));
            }
            cboCategoriesCount.Text = settings.CategoriesCount.ToString();

            // dummy color scheme
            Globals.LayerColors.SetDefaultColorScheme(_shapefile);

            // initializing for list of color schemes
            icbColorScheme.ColorSchemes = Globals.LayerColors;
            icbColorScheme.ComboStyle   = ImageComboStyle.ColorSchemeGraduated;

            // settings active color scheme
            for (int i = 0; i < icbColorScheme.Items.Count; i++)
            {
                if (icbColorScheme.ColorSchemes.List[i] == settings.CategoriesColorScheme)
                {
                    icbColorScheme.SelectedIndex = i;
                    break;
                }
            }
            if (icbColorScheme.SelectedItem == null)
            {
                icbColorScheme.SelectedIndex = 0;
            }

            if (_shapefile.ShapefileType == ShpfileType.SHP_POINT || _shapefile.ShapefileType == ShpfileType.SHP_MULTIPOINT)
            {
                chkUseVariableSize.Text = "Use variable symbol size";
                udMinSize.Minimum       = 1;
                udMinSize.Maximum       = 80;
                udMaxSize.Minimum       = 1;
                udMaxSize.Maximum       = 80;
                udMinSize.SetValue(_shapefile.DefaultDrawingOptions.PointSize);
                udMaxSize.SetValue((double)udMinSize.Value + settings.CategoriesSizeRange);
            }
            else if (_shapefile.ShapefileType == ShpfileType.SHP_POLYLINE)
            {
                chkUseVariableSize.Text = "Use variable line width";
                udMinSize.Minimum       = 1;
                udMinSize.Maximum       = 10;
                udMaxSize.Minimum       = 1;
                udMaxSize.Maximum       = 10;
                udMinSize.SetValue(_shapefile.DefaultDrawingOptions.LineWidth);
                udMaxSize.SetValue((double)udMinSize.Value + settings.CategoriesSizeRange);
            }
            else
            {
                chkUseVariableSize.Enabled = false;
                udMinSize.Value            = udMinSize.Minimum;
                udMinSize.Enabled          = false;
                udMaxSize.Value            = udMaxSize.Minimum;
                udMaxSize.Enabled          = false;
            }

            chkRandomColors.Checked    = settings.CategoriesRandomColors;
            chkSetGradient.Checked     = settings.CategoriesUseGradient;
            chkUseVariableSize.Checked = settings.CategoriesVariableSize;

            RefreshControlsState(null, null);

            string name = settings.CategoriesFieldName.ToLower();

            for (int i = 0; i < cboField.Items.Count; i++)
            {
                if (((ComboItem)cboField.Items[i]).Text.ToLower() == name)
                {
                    cboField.SelectedIndex = i;
                    break;
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// 'Copyright (C) 2008  Enrico Antonio Chiaradia, UNIMI
        ///'This program is free software; you can redistribute it and/or
        ///'modify it under the terms of the GNU General Public License 
        ///'version 2, 1991 as published by the Free Software Foundation.
        ///'This program is distributed in the hope that it will be useful,
        ///'but WITHOUT ANY WARRANTY; without even the implied warranty of
        ///'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        ///'GNU General Public License for more details.
        ///'A copy of the full GNU General Public License is available at:
        ///'http://www.gnu.org/copyleft/gpl.html
        ///'or from:
        ///'The Free Software Foundation, Inc., 59 Temple Place - Suite 330, 
        ///'Boston, MA  02111-1307, USA.
        ///'If you wish to use or incorporate this program (or parts of it) into 
        ///'other software that does not meet the GNU General Public License 
        ///'conditions contact the author to request permission.
        ///'If you have any question or suggestion, please contact the author.
        ///'Enrico A. Chiaradia
        ///'University of Milan
        ///'Ist. di Idraulica Agraria
        ///'via Celoria 2
        ///'20133, Milan, Italy
        ///'email:  [email protected]
        /// </summary>
        /// <param name="sfPath">the name of the shapefile</param>
        /// <param name="resultGridPath">the name of the new grid</param>
        /// <param name="gridFileType">file type of the new grid</param>
        /// <param name="gridDataType">data format of the new grid</param>
        /// <param name="sfValueField">the name of the field that contains data</param>
        /// <param name="resultGridHeader">contains information about dimension of the new grid</param>
        /// <param name="callback">(optional) reports progress and error messages</param>
        /// <returns></returns>
        public bool ShapefileToGrid2(string SfNm, string GrdName,
            MapWinGIS.GridFileType GrdFileType, MapWinGIS.GridDataType GrdDataType,
            string Fldname, MapWinGIS.GridHeader GrdHd,
            MapWinGIS.ICallback cback)
        {
            int i;
            bool flg;
            string projStr;

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

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

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

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

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

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

            //save and close the grid, close shapefile
            NewGrd.Save(GrdName, GrdFileType, cback);
            NewGrd.Close();
            MySf.Close();
            return flg;
        }
Beispiel #30
0
/// <summary>
        /// converts a Line shapefile to grid using Bresenham algorithm
        /// </summary>
        /// <param name="PolySf">Polygon shapefile object</param>
        /// <param name="FldID">Field index</param>
        /// <param name="Newgrd">New grid object</param>
        /// <param name="header">Grid header</param>
        /// <param name="nodatavalue"></param>
        /// <param name="cback">optional, for reporting progress</param>
        /// <returns>true if successful</returns>

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

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

            object val; //the shape's value


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

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

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

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

                    curPartStart = LineShp.get_Part(p);

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

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

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

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

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

                //report the progress
                if (s >= shpsPerc)
                {
                    reportProgress(shpsPerc, nShps, "shapefile to grid", cback);
                    perc     = (int)((s * 100) / nShps);
                    shpsPerc = NumPercentShapes(perc + 1, nShps);
                }
            }
            return(true);
        }
Beispiel #31
0
        /// <summary>
        /// 'Copyright (C) 2008  Enrico Antonio Chiaradia, UNIMI
        ///'This program is free software; you can redistribute it and/or
        ///'modify it under the terms of the GNU General Public License
        ///'version 2, 1991 as published by the Free Software Foundation.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            //save and close the grid, close shapefile
            NewGrd.Save(GrdName, GrdFileType, cback);
            NewGrd.Close();
            MySf.Close();
            return(flg);
        }