private static ICoordinateTransformation Proj2Proj(IProjectedCoordinateSystem source, IProjectedCoordinateSystem target)
		{
			ConcatenatedTransform ct = new ConcatenatedTransform();
			CoordinateTransformationFactory ctFac = new CoordinateTransformationFactory();
			//First transform from projection to geographic
			ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source, source.GeographicCoordinateSystem));
			//Transform geographic to geographic:
			ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source.GeographicCoordinateSystem, target.GeographicCoordinateSystem));
			//Transform to new projection
			ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(target.GeographicCoordinateSystem, target));

			return new CoordinateTransformation(source,
				target, TransformType.Transformation, ct,
				String.Empty, String.Empty, -1, String.Empty, String.Empty);
		}
Exemple #2
0
        /// <summary>
        /// ��������ϵͳ
        /// </summary>
        /// <param name="isFile">�Ƿ��ļ���ʽ����</param>
        private void LoadProCoord(bool isFile, IProjectedCoordinateSystem pProCoord)
        {
            this.txtName.Text = pProCoord.Name;
            this.rtxDetail.Text = "ͶӰ����ϵͳ��\n";
            this.rtxDetail.Text += " Name :" + pProCoord.Name + "\n";

            this.rtxDetail.Text += "Projection: " + pProCoord.Projection.Name + "\n";
            this.rtxDetail.Text += "Parameters:\n";
            this.rtxDetail.Text += " False_Easting: " + pProCoord.FalseEasting.ToString() + "\n";
            this.rtxDetail.Text += " False_Northing: " + pProCoord.FalseNorthing.ToString() + "\n";
            this.rtxDetail.Text += " Central_Meridian: " + pProCoord.get_CentralMeridian(true).ToString() + "\n";
            this.rtxDetail.Text += " Scale_Factor: " + pProCoord.ScaleFactor.ToString() + "\n";
            this.rtxDetail.Text += " Latitude_Of_Origin: 0.000000\n";
            this.rtxDetail.Text += " Linear Unit: Meter (1.000000)\n";

            this.rtxDetail.Text += "��������ϵͳ��\n";
            this.rtxDetail.Text += " Name: " + pProCoord.GeographicCoordinateSystem.Name + "\n";
            this.rtxDetail.Text += " Alias: " + pProCoord.GeographicCoordinateSystem.Alias + "\n";
            this.rtxDetail.Text += " Abbreviation: " + pProCoord.GeographicCoordinateSystem.Abbreviation + "\n";
            this.rtxDetail.Text += " Remarks: " + pProCoord.GeographicCoordinateSystem.Remarks + "\n";
            this.rtxDetail.Text += " Angular Unit: Degree (0.017453292519943299)\n";
            this.rtxDetail.Text += " Prime Meridian: " + pProCoord.GeographicCoordinateSystem.PrimeMeridian.Name + "\n";
            this.rtxDetail.Text += " Datum: " + pProCoord.GeographicCoordinateSystem.Datum.Name + "\n";
            this.rtxDetail.Text += "   Spheroid: " + pProCoord.GeographicCoordinateSystem.Datum.Spheroid.Name + "\n";
            this.rtxDetail.Text += "   Semimajor Axis: " + pProCoord.GeographicCoordinateSystem.Datum.Spheroid.SemiMajorAxis.ToString() + "\n";
            this.rtxDetail.Text += "   Semiminor Axis: " + pProCoord.GeographicCoordinateSystem.Datum.Spheroid.SemiMinorAxis.ToString() + "\n";
            this.rtxDetail.Text += "   Inverse Flattening: " + pProCoord.GeographicCoordinateSystem.Datum.Spheroid.Flattening.ToString() + "\n";

            this.rtxDetail.Text += "X/Y Domain: \n";
            double xMin = 0, xMax = 90000000, yMin = 0, yMax = 90000000, zMin = 0, zMax = 20000;
            pProCoord.SetDomain(xMin, xMax, yMin, yMax);

            this.rtxDetail.Text += " Min X: " + xMin.ToString() + "\n";
            this.rtxDetail.Text += " Min Y: " + yMin.ToString() + "\n";
            this.rtxDetail.Text += " Max X: " + xMax.ToString() + "\n";
            this.rtxDetail.Text += " Max Y: " + yMax.ToString() + "\n";

            this.rtxDetail.Text += "Z Domain: \n";
            pProCoord.SetZDomain(zMin, zMax);

            this.rtxDetail.Text += " Min: " + zMin.ToString() + "\n";
            this.rtxDetail.Text += " Max: " + zMax.ToString() + "\n";
        }
 public void TestProjectedCoordinateSystem()
 {
     IProjectedCoordinateSystem projectedCoordinateSystem = _factory.CreateProjectedCoordinateSystem("27700");
     string test1 = CoordinateSystemXmlWriter.Write(projectedCoordinateSystem);
 }
        public List <Object> CalculateDataTable(string polyfile)
        {
            //List<GeoAPI.Geometries.IGeometry> polys = new List<GeoAPI.Geometries.IGeometry>();
            List <GeoAPI.Geometries.IGeometry> squares = new List <GeoAPI.Geometries.IGeometry>();
            ArrayList     polys       = new ArrayList();
            List <Object> infoTable   = new List <Object>();
            double        squareArea  = 0;//0.015625;
            double        gridArea    = 0;
            double        polygonArea = 0;
            string        catchmentID = "";

            //////////////
            string gridfile = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.shp";//"";
            string gridproj = @"M:\DotSpatTopology\tests\NLDAS_Grid_Reference.prj";
            //////////////

            Guid   gid       = Guid.NewGuid();
            string directory = @"M:\\TransientStorage\\" + gid.ToString() + "\\";


            //This block is for getting and setting shapefiles for NLDAS Grid

            /**
             * client.DownloadFile("https://ldas.gsfc.nasa.gov/nldas/gis/NLDAS_Grid_Reference.zip", @"M:\\TransientStorage\\NLDAS.zip");
             * ZipFile.ExtractToDirectory(@"M:\\TransientStorage\\NLDAS.zip", @"M:\\TransientStorage\\NLDAS");
             * unzippedLocation = (@"M:\\TransientStorage\\NLDAS");
             * foreach (string file in Directory.GetFiles(unzippedLocation))
             * {
             *  if (Path.GetExtension(file).Equals(".shp"))
             *  {
             *      gridfile = file;
             *  }
             *  else if (Path.GetExtension(file).Equals(".prj"))
             *  {
             *      gridproj = file;
             *  }
             * }
             * client.Dispose();**/


            ShapefileDataReader reader2 = new ShapefileDataReader(gridfile, NetTopologySuite.Geometries.GeometryFactory.Default);

            while (reader2.Read())
            {
                squares.Add(reader2.Geometry);
                gridArea += reader2.Geometry.Area;
            }

            reader2.Dispose();



            //if (polyfile.StartsWith(@"{""type"": ""FeatureCollection"""))
            if (polyfile.StartsWith(@"{""type"":"))//.geojson
            {
                Boolean  version1      = true;
                string[] featureParams = new string[3];
                string   jsonfile      = polyfile;
                var      readera       = new NetTopologySuite.IO.GeoJsonReader();
                NetTopologySuite.Features.FeatureCollection result = readera.Read <NetTopologySuite.Features.FeatureCollection>(jsonfile);
                if (result[0].Attributes.GetNames().Contains("HUC_8"))
                {
                    version1         = false;
                    featureParams[0] = "OBJECTID";
                    featureParams[1] = "HUC_8";
                    featureParams[2] = "HUC_12";
                }
                else if (result[0].Attributes.GetNames().Contains("HUC8"))
                {
                    version1         = true;
                    featureParams[0] = "COMID";
                    featureParams[1] = "HUC8";
                    featureParams[2] = "HUC12";
                }
                else
                {
                    version1         = false;
                    featureParams[0] = null;
                    featureParams[1] = null;
                    featureParams[2] = null;
                }


                List <Object> huc8Table = new List <Object>();
                huc8Table.Add(new KeyValuePair <string, string>("HUC 8 ID: ", result[0].Attributes[featureParams[1]].ToString()));

                for (int i = 0; i < result.Count; i++)
                {
                    List <Object> huc12Table = new List <Object>();
                    if (version1)
                    {
                        huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null));
                    }
                    else
                    {
                        huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", result[i].Attributes["HUC_12"].ToString()));
                    }

                    catchmentID = result[i].Attributes[featureParams[0]].ToString();
                    huc12Table.Add(new KeyValuePair <string, string>("Catchment ID: ", catchmentID));
                    foreach (GeoAPI.Geometries.IGeometry s in squares)
                    {
                        double interArea = 0.0;
                        squareArea = s.Area;
                        if (result[i].Geometry.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = result[i].Geometry.Intersection(s);
                            interArea += intersection.Area;
                            double percent2 = (interArea / squareArea) * 100;
                            Dictionary <string, string> catchTable = new Dictionary <string, string>();
                            //catchTable.Add("catchmentID", catchmentID);
                            catchTable.Add("latitude", s.Centroid.X.ToString());
                            catchTable.Add("longitude", s.Centroid.Y.ToString());
                            catchTable.Add("cellArea", squareArea.ToString());
                            catchTable.Add("containedArea", interArea.ToString());
                            catchTable.Add("percentArea", percent2.ToString());
                            huc12Table.Add(catchTable);
                        }
                    }
                    huc8Table.Add(huc12Table);
                }
                infoTable.Add(huc8Table);
            }
            else                                                    //Huc ID
            {
                catchmentID = polyfile;
                string ending = polyfile + ".zip";

                WebClient     client = new WebClient();
                DirectoryInfo di     = Directory.CreateDirectory(directory);
                client.DownloadFile("ftp://newftp.epa.gov/exposure/NHDV1/HUC12_Boundries/" + ending, directory + ending);

                string projfile = "";
                string dataFile = "";

                ZipFile.ExtractToDirectory(directory + ending, directory + polyfile);
                string unzippedLocation = (directory + polyfile + "\\" + polyfile); //+ "\\NHDPlus" + polyfile + "\\Drainage");
                foreach (string file in Directory.GetFiles(unzippedLocation))
                {
                    if (Path.GetExtension(file).Equals(".shp"))
                    {
                        polyfile = file;
                    }
                    else if (Path.GetExtension(file).Equals(".prj"))
                    {
                        projfile = file;
                    }
                    else if (Path.GetExtension(file).Equals(".dbf"))
                    {
                        dataFile = file;
                    }
                }

                //This block is for setting projection parameters of input shapefile and projecting it to NLDAS grid
                //Reprojecting of coordinates is not needed for NHDPlus V2

                string   line       = System.IO.File.ReadAllText(projfile);
                string[] projParams = { "PARAMETER", @"PARAMETER[""latitude_Of_origin"",0]," };//@"PARAMETER[""false_easting"",0],", @"PARAMETER[""false_northing"",0],", @"PARAMETER[""central_meridian"",0],", @"PARAMETER[""standard_parallel_1"",0],", @"PARAMETER[""standard_parallel_2"",0],", @"PARAMETER[""latitude_Of_origin"",0]," };
                int      ptr        = 0;
                foreach (string x in projParams)
                {
                    if (line.Contains(x))
                    {
                        ptr = line.IndexOf(x);
                    }
                    else if (!line.Contains(x) && !x.Equals("PARAMETER"))
                    {
                        line = line.Insert(ptr, x);
                    }
                }
                string line2 = System.IO.File.ReadAllText(gridproj);

                IProjectedCoordinateSystem  pcs = CoordinateSystemWktReader.Parse(line) as IProjectedCoordinateSystem;
                IGeographicCoordinateSystem gcs = GeographicCoordinateSystem.WGS84 as IGeographicCoordinateSystem;

                CoordinateTransformationFactory ctfac       = new CoordinateTransformationFactory();
                ICoordinateTransformation       transformTo = ctfac.CreateFromCoordinateSystems(pcs, gcs);
                IMathTransform inverseTransformTo           = transformTo.MathTransform;


                //Read geometries from both shapefiles and store in array lists
                //As well as calculate shapefile areas ahead of time
                ShapefileDataReader reader = new ShapefileDataReader(polyfile, NetTopologySuite.Geometries.GeometryFactory.Default);
                while (reader.Read())
                {
                    //Reprojection not needed for NHDPLUSV2
                    CoordinateList cordlist = new CoordinateList();
                    foreach (Coordinate coord in reader.Geometry.Coordinates)
                    {
                        double[] newCoord = { coord.X, coord.Y };
                        newCoord = inverseTransformTo.Transform(newCoord);
                        Coordinate newpt = new Coordinate(newCoord[0], newCoord[1]);
                        cordlist.Add(newpt);
                    }
                    Coordinate[]     listofpts  = cordlist.ToCoordinateArray();
                    IGeometryFactory geoFactory = new NetTopologySuite.Geometries.GeometryFactory();
                    NetTopologySuite.Geometries.LinearRing linear = (NetTopologySuite.Geometries.LinearRing) new GeometryFactory().CreateLinearRing(listofpts);
                    Polygon projPoly = new Polygon(linear, null, geoFactory);

                    polys.Add(projPoly);
                    polygonArea += projPoly.Area;
                }
                reader.Dispose();

                List <Object> huc8Table = new List <Object>();
                huc8Table.Add(new KeyValuePair <string, string>("HUC 8 ID: ", catchmentID));

                foreach (Polygon p in polys)
                {
                    List <Object> huc12Table = new List <Object>();
                    huc12Table.Add(new KeyValuePair <string, string>("HUC 12 ID: ", null));
                    catchmentID = null;//result[i].Attributes["OBJECTID"].ToString();
                    huc12Table.Add(new KeyValuePair <string, string>("Catchment ID: ", catchmentID));
                    foreach (GeoAPI.Geometries.IGeometry s in squares)
                    {
                        double interArea = 0.0;
                        squareArea = s.Area;
                        if (p.Intersects(s))
                        {
                            GeoAPI.Geometries.IGeometry intersection = p.Intersection(s);
                            interArea += intersection.Area;
                            double percent2 = (interArea / squareArea) * 100;
                            Dictionary <string, string> catchTable = new Dictionary <string, string>();
                            //catchTable.Add("catchmentID", catchmentID);
                            catchTable.Add("latitude", s.Centroid.X.ToString());
                            catchTable.Add("longitude", s.Centroid.Y.ToString());
                            catchTable.Add("cellArea", squareArea.ToString());
                            catchTable.Add("containedArea", interArea.ToString());
                            catchTable.Add("percentArea", percent2.ToString());
                            huc12Table.Add(catchTable);
                        }
                    }
                    huc8Table.Add(huc12Table);
                }
                infoTable.Add(huc8Table);
            }

            //System.IO.DirectoryInfo del = new DirectoryInfo(directory);

            /*
             * foreach (FileInfo file in del.GetFiles())
             * {
             *  file.Delete();
             * }
             * foreach (DirectoryInfo dir in del.GetDirectories())
             * {
             *  dir.Delete(true);
             * }*/
            //del.Delete(true);
            /////
            //infoTable.Add(new List<Object>() { elapsedTime, elapsedTime, elapsedTime, elapsedTime });
            //////

            return(infoTable);
        }
        private static ICoordinateTransformation Proj2Proj(IProjectedCoordinateSystem source, IProjectedCoordinateSystem target)
        {
            ConcatenatedTransform           ct    = new ConcatenatedTransform();
            CoordinateTransformationFactory ctFac = new CoordinateTransformationFactory();

            //First transform from projection to geographic
            ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source, source.GeographicCoordinateSystem));
            //Transform geographic to geographic:
            ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source.GeographicCoordinateSystem, target.GeographicCoordinateSystem));
            //Transform to new projection
            ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(target.GeographicCoordinateSystem, target));

            return(new CoordinateTransformation(source,
                                                target, TransformType.Transformation, ct,
                                                String.Empty, String.Empty, -1, String.Empty, String.Empty));
        }
Exemple #6
0
        /// <summary>
        /// 初始化form element
        /// </summary>
        private void Initialize()
        {
            IFeatureLayer           featureLayer    = (IFeatureLayer)m_layer;
            IGeoFeatureLayer        geoLayer        = (IGeoFeatureLayer)m_layer;
            IFeatureClass           featureClass    = featureLayer.FeatureClass;
            ILayerGeneralProperties layerProperties = (ILayerGeneralProperties)featureLayer;

            // 图层属性页
            this.textBoxLayerName.Text        = m_layer.Name;
            this.textBoxLayerDescription.Text = layerProperties.LayerDescription;
            this.checkBoxVisibility.Checked   = m_layer.Visible;

            String scaleMin = geoLayer.MinimumScale.ToString();
            String sacleMax = geoLayer.MaximumScale.ToString();

            if ("0" == scaleMin && "0" == sacleMax)
            {
                this.radioButtonScaleAll.Checked  = true;
                this.radioButtonScaleZoom.Checked = false;
            }
            else
            {
                this.radioButtonScaleAll.Checked  = false;
                this.radioButtonScaleZoom.Checked = true;
                this.comboBoxScaleMax.Text        = sacleMax;
                this.comboBoxScaleMin.Text        = scaleMin;
            }

            // 字段定义页
            IFields fields     = featureClass.Fields;
            int     fieldCount = fields.FieldCount;

            for (int i = 0; i < fieldCount; i++)
            {
                IField       field = fields.get_Field(i);
                ListViewItem item  = new ListViewItem(field.Name);
                item.SubItems.Add(field.AliasName);
                item.SubItems.Add(field.Editable ? "允许编辑" : "不允许编辑");
                item.SubItems.Add(field.IsNullable ? "允许为空" : "不允许为空");
                item.SubItems.Add(field.Length.ToString());
                item.SubItems.Add(field.Precision.ToString());
                item.SubItems.Add(field.Scale.ToString());
                item.SubItems.Add(GetFieldType(field.Type));
                listViewFields.Items.Add(item);
            }

            // 数据源及四至范围
            IEnvelope envelope = m_layer.AreaOfInterest;

            textBoxLeft.Text   = envelope.XMin.ToString();
            textBoxRight.Text  = envelope.XMax.ToString();
            textBoxTop.Text    = envelope.YMin.ToString();
            textBoxBottom.Text = envelope.YMax.ToString();

            IDataset dataset = (IDataset)featureLayer;

            textBoxDataSource.AppendText("数据源类型:           ");
            textBoxDataSource.AppendText(featureLayer.DataSourceType);
            textBoxDataSource.AppendText("\r\n数据集:               ");
            textBoxDataSource.AppendText(dataset.BrowseName);
            textBoxDataSource.AppendText("\r\n数据源名称:           ");
            textBoxDataSource.AppendText(dataset.Workspace.PathName);

            textBoxDataSource.AppendText("\r\n要素类:               ");
            textBoxDataSource.AppendText(featureClass.AliasName);
            textBoxDataSource.AppendText("\r\n要素类类型:           ");
            textBoxDataSource.AppendText(GetFeatureType(featureClass.FeatureType));
            textBoxDataSource.AppendText("\r\n几何类型:             ");
            textBoxDataSource.AppendText(GetGeometryType(featureClass.ShapeType));

            IGeoDataset geoDataset = (IGeoDataset)featureClass;
            // 通过IGeoDataset接口获取FeatureClass坐标系统
            ISpatialReference          spatialReference   = geoDataset.SpatialReference;
            IProjectedCoordinateSystem projectCoordSystem = null;

            if (spatialReference is IProjectedCoordinateSystem)
            {
                projectCoordSystem = (IProjectedCoordinateSystem)spatialReference;

                if (projectCoordSystem == null)
                {
                    return;
                }

                textBoxDataSource.AppendText("\r\n");

                IProjection project = projectCoordSystem.Projection;
                textBoxDataSource.AppendText("\r\n投影坐标系:           ");
                textBoxDataSource.AppendText(projectCoordSystem.Name);
                textBoxDataSource.AppendText("\r\n投影:                 ");
                textBoxDataSource.AppendText(project.Name);
                textBoxDataSource.AppendText("\r\nFalseEasting:         ");
                textBoxDataSource.AppendText(projectCoordSystem.FalseEasting.ToString());
                textBoxDataSource.AppendText("\r\nFalseNorthing:        ");
                textBoxDataSource.AppendText(projectCoordSystem.FalseNorthing.ToString());
                textBoxDataSource.AppendText("\r\n中央经线:             ");
                textBoxDataSource.AppendText(projectCoordSystem.get_CentralMeridian(true).ToString());
                textBoxDataSource.AppendText("\r\n缩放比例:             ");
                textBoxDataSource.AppendText(projectCoordSystem.ScaleFactor.ToString());
                textBoxDataSource.AppendText("\r\n高度原点:             ");
                try
                {
                    textBoxDataSource.AppendText(projectCoordSystem.LongitudeOfOrigin.ToString());
                }
                catch (Exception e)
                {
                    textBoxDataSource.AppendText("0");
                }

                textBoxDataSource.AppendText("\r\n单位:                 ");
                textBoxDataSource.AppendText(projectCoordSystem.CoordinateUnit.Name);

                textBoxDataSource.AppendText("\r\n");

                IGeographicCoordinateSystem geographCoordinateSystem = projectCoordSystem.GeographicCoordinateSystem;
                if (geographCoordinateSystem != null)
                {
                    textBoxDataSource.AppendText("\r\n地理坐标系:           ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.Name);
                    textBoxDataSource.AppendText("\r\n基准面:               ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.Datum.Name);
                    textBoxDataSource.AppendText("\r\n本初子午线:           ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.PrimeMeridian.Name);
                    textBoxDataSource.AppendText("\r\n单位:                 ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.CoordinateUnit.Name);
                }
            }
            else if (spatialReference is IGeographicCoordinateSystem)
            {
                IGeographicCoordinateSystem geographCoordinateSystem = spatialReference as IGeographicCoordinateSystem;
                if (geographCoordinateSystem != null)
                {
                    textBoxDataSource.AppendText("\r\n地理坐标系:           ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.Name);
                    textBoxDataSource.AppendText("\r\n基准面:               ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.Datum.Name);
                    textBoxDataSource.AppendText("\r\n本初子午线:           ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.PrimeMeridian.Name);
                    textBoxDataSource.AppendText("\r\n单位:                 ");
                    textBoxDataSource.AppendText(geographCoordinateSystem.CoordinateUnit.Name);
                }
            }



            // filter

            IDisplayString displayString = (IDisplayString)featureLayer;

            textBoxFilter.AppendText(displayString.ExpressionProperties.Expression);

            // 标注
            IAnnotateLayerPropertiesCollection annoLayerPropsColl = geoLayer.AnnotationProperties;
            IAnnotateLayerProperties           annoLayerProps     = null;
            IElementCollection placedElements   = null;
            IElementCollection unplacedElements = null;

            annoLayerPropsColl.QueryItem(0, out annoLayerProps, out placedElements, out unplacedElements);
            ILabelEngineLayerProperties aLELayerProps = annoLayerProps as ILabelEngineLayerProperties;

            // annoLayerProps.DisplayAnnotation;
            checkBoxLabelVisibility.Checked = annoLayerProps.DisplayAnnotation;

            //初始化字体大小下拉框
            for (int k = 5; k <= 11; k++)
            {
                cmbFontSize.Items.Add(k);
            }
            for (int k = 12; k <= 72; k = k + 2)
            {
                cmbFontSize.Items.Add(k);
            }
            // cmbFontSize.Text = "8";

            //初始化字体下拉框
            foreach (FontFamily onefontfamily in FontFamily.Families)
            {
                //去掉名称头个字为@的字体
                if (onefontfamily.Name.Substring(0, 1) != "@")
                {
                    cmbFontName.Items.Add(onefontfamily.Name);
                }
            }
            // cmbFontName.Text = "宋体";
            ITextSymbol pTextSymbol = aLELayerProps.Symbol;

            stdole.IFontDisp pFontDisp = pTextSymbol.Font;
            cmbFontSize.Text = pFontDisp.Size.ToString();
            toolBarStyle.Buttons[0].Pushed = pFontDisp.Bold;
            toolBarStyle.Buttons[1].Pushed = pFontDisp.Italic;
            toolBarStyle.Buttons[2].Pushed = pFontDisp.Underline;
            cmbFontName.Text = pFontDisp.Name;
            IRgbColor rgbColor = (IRgbColor)pTextSymbol.Color;

            colorButtonFont.Color = Color.FromArgb(rgbColor.Transparency,
                                                   rgbColor.Red,
                                                   rgbColor.Green,
                                                   rgbColor.Blue);
            colorButtonFont.Refresh();
            for (int i = 0; i < fields.FieldCount; i++)
            {
                IField field = fields.get_Field(i);
                cmbFieldName.Items.Add(field.Name);
            }

            cmbFieldName.Enabled = aLELayerProps.IsExpressionSimple;
            String expr = aLELayerProps.Expression.Trim('[').Trim(']');

            cmbFieldName.SelectedIndex = cmbFieldName.FindString(expr);

            cmbMaxScale.Text = annoLayerProps.AnnotationMaximumScale.ToString();
            cmbMinScale.Text = annoLayerProps.AnnotationMinimumScale.ToString();

            if (cmbMaxScale.Text == "0" && cmbMinScale.Text == "0")
            {
                rbScaleWithLayer.Checked    = true;
                this.rbScaleDefined.Checked = false;
            }
            else
            {
                rbScaleWithLayer.Checked    = false;
                this.rbScaleDefined.Checked = true;
            }

            //ITextSymbol pTextSymbol = aLELayerProps.Symbol;
            //stdole.IFontDisp pFontDisp = pTextSymbol.Font;
            //pFontDisp.Size = decimal.Parse(fontSize);
            //pFontDisp.Bold = boldBool;
            //pFontDisp.Italic = italicBool;
            //pFontDisp.Name = fontStyle;
            //IRgbColor pRgbColor = new RgbColorClass();
            //pRgbColor.Red = int.Parse(fontColor.R.ToString());
            //pRgbColor.Blue = int.Parse(fontColor.B.ToString());
            //pRgbColor.Green = int.Parse(fontColor.G.ToString());
            //pTextSymbol.Font = pFontDisp;
            //pTextSymbol.Color = pRgbColor;
            //aLELayerProps.Symbol = pTextSymbol;
            //annoLayerProps = aLELayerProps as IAnnotateLayerProperties;
            //annoLayerProps.FeatureLayer = geoLayer;
            //annoLayerProps.LabelWhichFeatures = esriLabelWhichFeatures.esriAllFeatures;
            //annoLayerPropsColl.Add(annoLayerProps);

            // 符号
            checkBoxCostomSymbol.Checked = EPSUtils.IsLayerRenderer(featureLayer);
        }
Exemple #7
0
        private void GetDataSource()
        {
            IFeatureLayer     pFeatureLayer   = (IFeatureLayer)m_pLayer;
            IFeatureClass     pFeatureClass   = pFeatureLayer.FeatureClass;
            IDataset          pFeatureDataset = pFeatureClass as IDataset;
            ISpatialReference pSpatialRef;

            pSpatialRef = (pFeatureClass as IGeoDataset).SpatialReference;

            //判断如果转换成投影坐标是否成功 xisheng 20111122
            IProjectedCoordinateSystem  pProjectedCoordinateSystem  = ((pFeatureClass as IGeoDataset).SpatialReference) as IProjectedCoordinateSystem;
            IGeographicCoordinateSystem pGeographicCoordinateSystem = null;

            if (pProjectedCoordinateSystem == null)
            {
                pGeographicCoordinateSystem = ((pFeatureClass as IGeoDataset).SpatialReference) as IGeographicCoordinateSystem;
            }
            else
            {
                pGeographicCoordinateSystem = pProjectedCoordinateSystem.GeographicCoordinateSystem;
            }
            //**************************************************end
            string strDataType      = pFeatureLayer.DataSourceType;
            string strLocation      = pFeatureDataset.Workspace.PathName;
            string strFeatureDSName = pFeatureDataset.Name;
            string strFCName        = pFeatureClass.AliasName;
            string strFeatureType   = pFeatureClass.FeatureType.ToString().Substring(6);
            string strGeometryType  = pFeatureClass.ShapeType.ToString().Substring(12);

            if (pProjectedCoordinateSystem != null)
            {
                string strPCSName         = pProjectedCoordinateSystem.Name;
                string strProjection      = pProjectedCoordinateSystem.Projection.Name;
                string strFalseEasting    = pProjectedCoordinateSystem.FalseEasting.ToString();
                string strFalseNorthing   = pProjectedCoordinateSystem.FalseNorthing.ToString();
                string strCentralMeridian = pProjectedCoordinateSystem.get_CentralMeridian(true).ToString();
                string strScaleFactor     = pProjectedCoordinateSystem.ScaleFactor.ToString();
                string strLinearUnit      = pProjectedCoordinateSystem.CoordinateUnit.Name;

                string strGCSName       = pGeographicCoordinateSystem.Name;
                string strDatum         = pGeographicCoordinateSystem.Datum.Name;
                string strPrimeMeridian = pGeographicCoordinateSystem.PrimeMeridian.Name;
                string strAngularUnit   = pGeographicCoordinateSystem.CoordinateUnit.Name;
                txtDataSource.Text =
                    "Data Type:\t\t\t" + strDataType +
                    "\r\n位置:\t\t\t" + strLocation +
                    "\r\n要素集:\t\t" + strFeatureDSName +
                    "\r\n要素类:\t\t\t" + strFCName +
                    "\r\n要素类型:\t\t\t" + strFeatureType +
                    "\r\n几何类型:\t\t\t" + strGeometryType +
                    "\r\n\r\n投影坐标系信息:\t" + strPCSName +
                    "\r\n投影:\t\t\t" + strProjection +
                    "\r\nFalse_Easting:\t\t\t" + strFalseEasting +
                    "\r\nFalse_Northing:\t\t\t" + strFalseNorthing +
                    "\r\nCentral_Meridian:\t\t" + strCentralMeridian +
                    "\r\nScale_Factor:\t\t\t" + strScaleFactor +
                    "\r\nLinear Unit:\t\t\t" + strLinearUnit +
                    "\r\n\r\nGeographic Coordinate System:\t" + strGCSName +
                    "\r\nDatum:\t\t\t\t" + strDatum +
                    "\r\nPrime Meridian:\t\t\t" + strPrimeMeridian +
                    "\r\nAngular Unit:\t\t\t" + strAngularUnit + "\r\n";
            }
            else
            {
                string strGCSName       = pGeographicCoordinateSystem.Name;
                string strDatum         = pGeographicCoordinateSystem.Datum.Name;
                string strPrimeMeridian = pGeographicCoordinateSystem.PrimeMeridian.Name;
                string strAngularUnit   = pGeographicCoordinateSystem.CoordinateUnit.Name;
                txtDataSource.Text =
                    "Data Type:\t\t\t" + strDataType +
                    "\r\nLocation:\t\t\t" + strLocation +
                    "\r\nFeature Dataset:\t\t" + strFeatureDSName +
                    "\r\nFeature Class:\t\t\t" + strFCName +
                    "\r\nFeature Type:\t\t\t" + strFeatureType +
                    "\r\nGeometry Type:\t\t\t" + strGeometryType +
                    "\r\n\r\nGeographic Coordinate System:\t" + strGCSName +
                    "\r\nDatum:\t\t\t\t" + strDatum +
                    "\r\nPrime Meridian:\t\t\t" + strPrimeMeridian +
                    "\r\nAngular Unit:\t\t\t" + strAngularUnit + "\r\n";
            }
        }
 public double getLinearConversion(IProjectedCoordinateSystem prjSys)
 {
     IUnitConverter converter = new UnitConverterClass();
     ILinearUnit linearUnit = prjSys.CoordinateUnit;
     double meter = linearUnit.MetersPerUnit;
     double unitToFoot = converter.ConvertUnits(meter, esriUnits.esriMeters, esriUnits.esriFeet);
     return unitToFoot;
 }
Exemple #9
0
 public MapProjection(int zone, bool north)
 {
     Projection = ProjectedCoordinateSystem.WGS84_UTM(zone, north);
     MakeTransforms();
 }
Exemple #10
0
 public MapProjection(string path, int epsg)
 {
     DbPath     = Path.Combine(path, "SRID.csv");
     Projection = (IProjectedCoordinateSystem)GetCSbyID(epsg);
     MakeTransforms();
 }
Exemple #11
0
        /// <summary>
        /// Creates a transformation from a single transformation code.
        /// </summary>
        /// <remarks>
        /// The ‘Authority’ and ‘AuthorityCode’ values of the created object will be set to the authority of this object, and the code supplied by the client, respectively.  The other metadata values may or may not be set.
        /// </remarks>
        /// <param name="code">The EPSG code of the transformation to create.</param>
        /// <returns>An object that implements the ICoordinateTransformation interface.</returns>
        public ICoordinateTransformation CreateFromTransformationCode(string code)
        {
            string sqlQuery = "SELECT	SOURCE_CRS_CODE, TARGET_CRS_CODE, COORD_OP_NAME, COORD_OP_SCOPE, COORD_OP_METHOD_CODE, "+
                              "		REMARKS, INFORMATION_SOURCE, DATA_SOURCE, AREA_OF_USE_CODE, COORD_OP_TYPE "+
                              "FROM	Coordinate_Operation " +
                              "WHERE COORD_OP_CODE={0}";

            sqlQuery = String.Format(sqlQuery, code);
            IDataReader reader = Database.ExecuteQuery(_databaseConnection, sqlQuery);

            if (!reader.Read())
            {
                throw new ArgumentException(String.Format("Coord Operation code of {0} is not found.", code));
            }
            string sourceCSCode  = reader["SOURCE_CRS_CODE"].ToString();
            string targetCSCode  = reader["TARGET_CRS_CODE"].ToString();
            string coordOpMethod = reader["COORD_OP_METHOD_CODE"].ToString();
            string areaOfUseCode = reader["AREA_OF_USE_CODE"].ToString();
            string authority     = reader["DATA_SOURCE"].ToString();
            string name          = reader["COORD_OP_NAME"].ToString();
            string remarks       = reader["REMARKS"].ToString();
            string coordOpType   = reader["COORD_OP_TYPE"].ToString().ToLower();

            Database.CheckOneRow(reader, code, "CreateFromTransformationCode");

            string areaOfUseDescription = this.GetAreaOfUse(areaOfUseCode);

            ICoordinateSystem sourceCS      = null;
            ICoordinateSystem targetCS      = null;
            IMathTransform    mathTransform = null;

            if (coordOpType == "transformation")
            {
                if (sourceCSCode == "" || targetCSCode == "")
                {
                    throw new InvalidOperationException(String.Format("Coordinate operation {0} which is a transformation does not have a source or target coordinate system.", code));
                }
                // create the coordinate systems. Use this helper method. The
                // helper first determines if the coordinate system is a projected or geographic coordinate system
                // and then creates the right one.
                sourceCS = _coordSystemFactory.CreateCoordinateSystem(sourceCSCode);
                targetCS = _coordSystemFactory.CreateCoordinateSystem(targetCSCode);

                // use the WGS84 ellipsoid if an ellipsoid is not defined.
                IEllipsoid ellipsoid = Ellipsoid.WGS84Test;
                if (sourceCS is IProjectedCoordinateSystem)
                {
                    IProjectedCoordinateSystem projectedCS = (IProjectedCoordinateSystem)sourceCS;
                    ellipsoid = projectedCS.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid;
                    IProjection projection = projectedCS.Projection;

                    //mathTransform = CreateCoordinateOperation(code, coordOpMethod, ellipsoid);
                    mathTransform = CreateCoordinateOperation(projection, ellipsoid);
                }
            }
            else if (coordOpType == "conversion")
            {
                // not sure what to do here.
                throw new NotImplementedException("Coordinate operation 'conversion' has not been implemented.");
                // use the the WGS84 ellipsoid as a default.
                //mathTransform = CreateCoordinateOperation(code, coordOpMethod, Ellipsoid.WGS84Test);
            }
            else if (coordOpType == "concatenated operation")
            {
                throw new NotImplementedException("concatenated operation have not been implemented.");
            }

            ICoordinateTransformation coordinateTransformation = new CoordinateTransformation(
                TransformType.Transformation,
                targetCS,
                sourceCS,
                mathTransform,
                code,
                authority,
                name,
                areaOfUseDescription,
                remarks, "");

            return(coordinateTransformation);
        }
        private static ICoordinateTransformation Proj2Proj(IProjectedCoordinateSystem source, IProjectedCoordinateSystem target)
        {
            ConcatenatedTransform           mathTransform = new ConcatenatedTransform();
            CoordinateTransformationFactory factory       = new CoordinateTransformationFactory();

            mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source, source.GeographicCoordinateSystem));
            mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source.GeographicCoordinateSystem, target.GeographicCoordinateSystem));
            mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(target.GeographicCoordinateSystem, target));
            return(new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform, string.Empty, string.Empty, -1L, string.Empty, string.Empty));
        }
        private static ICoordinateTransformation Geog2Proj(IGeographicCoordinateSystem source, IProjectedCoordinateSystem target)
        {
            if (source.EqualParams(target.GeographicCoordinateSystem))
            {
                return(new CoordinateTransformation(source, target, TransformType.Transformation, CreateCoordinateOperation(target.Projection, target.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid), string.Empty, string.Empty, -1L, string.Empty, string.Empty));
            }
            ConcatenatedTransform           mathTransform = new ConcatenatedTransform();
            CoordinateTransformationFactory factory       = new CoordinateTransformationFactory();

            mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source, target.GeographicCoordinateSystem));
            mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(target.GeographicCoordinateSystem, target));
            return(new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform, string.Empty, string.Empty, -1L, string.Empty, string.Empty));
        }
Exemple #14
0
        public static object Create(XmlTextReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            // we don't want to handle whitespace
            reader.WhitespaceHandling = WhitespaceHandling.None;
            object returnObject = null;

            reader.Read();


            // skip declarions and comments.
            while (reader.NodeType != XmlNodeType.Element)
            {
                reader.Read();
            }

            if (reader.NodeType == XmlNodeType.Element)
            {
                switch (reader.Name)
                {
                case "CS_LinearUnit":
                    ILinearUnit linearUnit = ReadLinearUnit(reader);
                    returnObject = linearUnit;
                    break;

                case "CS_AngularUnit":
                    IAngularUnit angularUnit = ReadAngularUnit(reader);
                    returnObject = angularUnit;
                    break;

                case "CS_VerticalDatum":
                    IVerticalDatum verticalDatum = ReadVerticalDatum(reader);
                    returnObject = verticalDatum;
                    break;

                case "CS_Ellipsoid":
                    IEllipsoid ellipsoid = ReadEllipsoid(reader);
                    returnObject = ellipsoid;
                    break;

                case "CS_WGS84ConversionInfo":
                    WGS84ConversionInfo wgsInfo = ReadWGS84ConversionInfo(reader);
                    returnObject = wgsInfo;
                    break;

                case "CS_HorizontalDatum":
                    IHorizontalDatum horizontalDatum = ReadHorizontalDatum(reader);
                    returnObject = horizontalDatum;
                    break;

                case "CS_PrimeMeridian":
                    IPrimeMeridian primeMeridian = ReadPrimeMeridian(reader);
                    returnObject = primeMeridian;
                    break;

                case "CS_VerticalCoordinateSystem":
                    IVerticalCoordinateSystem verticalCS = ReadVerticalCoordinateSystem(reader);
                    returnObject = verticalCS;
                    break;

                case "CS_GeographicCoordinateSystem":
                    IGeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(reader);
                    returnObject = geographicCS;
                    break;

                case "CS_ProjectedCoordinateSystem":
                    IProjectedCoordinateSystem projectedCS = ReadProjectedCoordinateSystem(reader);
                    returnObject = projectedCS;
                    break;

                case "CS_CompoundCoordinateSystem":
                    ICompoundCoordinateSystem compoundCS = ReadCompoundCoordinateSystem(reader);
                    returnObject = compoundCS;
                    break;

                case "CS_Projection":
                    IProjection projection = ReadProjection(reader);
                    returnObject = projection;
                    break;

                case "CS_CoordinateSystem":
                    // must be a compound coord sys since all other coord system should have been
                    // taken care of by now.
                    reader.Read();
                    ICoordinateSystem coordinateSystem = ReadCompoundCoordinateSystem(reader);
                    reader.Read();
                    returnObject = coordinateSystem;
                    break;

                case "CS_GEOCCS":
                case "CS_FITTED_CS":
                case "CS_LOCAL_CS":
                    throw new NotSupportedException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} is not implemented.", reader.Name));

                default:
                    throw new ParseException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Element type {0} was is not understoon.", reader.Name));
                }
            }

            return(returnObject);
        }
 /// <summary>
 /// 初始化常用的信息
 /// </summary>
 private static void InitInfo()
 {
     pCTFAC = new CoordinateTransformationFactory();
     pPCS   = ProjectedCoordinateSystem.WGS84_UTM(50, true);
     pGCS   = GeographicCoordinateSystem.WGS84;
 }
 private void BindRunTime()
 {
     if (ESRI.ArcGIS.RuntimeManager.ActiveRuntime == null)
     {
         // Required to prevent Runtime.InteropServices.COMException
         ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
         bngSRef = new SpatialReferenceEnvironmentClass().CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_BritishNationalGrid);
         wgs84SRef = new SpatialReferenceEnvironmentClass().CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);
     }
 }
        private static CoordinateSystemFactory CreateNad83ToLambertFactory(out IGeographicCoordinateSystem gcs, out IProjectedCoordinateSystem coordsys)
        {
            CoordinateSystemFactory cfac = new CoordinateSystemFactory();

            // Define ellipsoid GRS 1980 used by NAD83
            IEllipsoid ellipsoid = cfac.CreateFlattenedSphere("GRS 1980", 6378137, 298.257222101, LinearUnit.Metre);

            // Define NAD83 system
            IHorizontalDatum datum = cfac.CreateHorizontalDatum("NAD83 (CSRS)", DatumType.HD_Other, ellipsoid, null);

            gcs = cfac.CreateGeographicCoordinateSystem("NAD83 (CSRS)", AngularUnit.Degrees, datum,
                                                        PrimeMeridian.Greenwich, new AxisInfo("Lon", AxisOrientationEnum.East), new AxisInfo("Lat", AxisOrientationEnum.North));

            // Define Lambert parameters
            List <ProjectionParameter> parameters = new List <ProjectionParameter>(5);

            parameters.Add(new ProjectionParameter("latitude_of_origin", 44));
            parameters.Add(new ProjectionParameter("central_meridian", -70));
            parameters.Add(new ProjectionParameter("standard_parallel_1", 50));
            parameters.Add(new ProjectionParameter("standard_parallel_2", 46));
            parameters.Add(new ProjectionParameter("false_easting", 800000));
            parameters.Add(new ProjectionParameter("false_northing", 0));
            IProjection projection = cfac.CreateProjection("Lambert Conic Conformal (2SP)", "lambert_conformal_conic_2sp", parameters);

            coordsys = cfac.CreateProjectedCoordinateSystem("NAD83/Lambert", gcs, projection, LinearUnit.Metre, new AxisInfo("East", AxisOrientationEnum.East), new AxisInfo("North", AxisOrientationEnum.North));

            return(cfac);
        }
 private static ICoordinateTransformation Proj2Proj(IProjectedCoordinateSystem source, IProjectedCoordinateSystem target)
 {
     ConcatenatedTransform mathTransform = new ConcatenatedTransform();
     CoordinateTransformationFactory factory = new CoordinateTransformationFactory();
     mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source, source.GeographicCoordinateSystem));
     mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source.GeographicCoordinateSystem, target.GeographicCoordinateSystem));
     mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(target.GeographicCoordinateSystem, target));
     return new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform, string.Empty, string.Empty, -1L, string.Empty, string.Empty);
 }
Exemple #19
0
 private static ICoordinateTransformation Geog2Proj(IGeographicCoordinateSystem source, IProjectedCoordinateSystem target)
 {
     if (source.EqualParams(target.GeographicCoordinateSystem))
     {
         IMathTransform mathTransform = CreateCoordinateOperation(target.Projection, target.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid, target.LinearUnit);
         return(new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform,
                                             String.Empty, String.Empty, -1, String.Empty, String.Empty));
     }
     else
     {
         // Geographic coordinatesystems differ - Create concatenated transform
         ConcatenatedTransform           ct    = new ConcatenatedTransform();
         CoordinateTransformationFactory ctFac = new CoordinateTransformationFactory();
         ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source, target.GeographicCoordinateSystem));
         ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(target.GeographicCoordinateSystem, target));
         return(new CoordinateTransformation(source,
                                             target, TransformType.Transformation, ct,
                                             String.Empty, String.Empty, -1, String.Empty, String.Empty));
     }
 }
Exemple #20
0
        public override void SendCommand()
        {
            if (masterpos.Lat == 0 || masterpos.Lng == 0)
            {
                return;
            }

            Console.WriteLine(DateTime.Now);
            Console.WriteLine("Leader {0} {1} {2}", masterpos.Lat, masterpos.Lng, masterpos.Alt);

            int a = 0;

            foreach (var port in MainV2.Comports)
            {
                if (port == Leader)
                {
                    continue;
                }

                PointLatLngAlt target = new PointLatLngAlt(masterpos);

                try
                {
                    //convert Wgs84ConversionInfo to utm
                    CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();

                    GeographicCoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;

                    int utmzone = (int)((masterpos.Lng - -186.0) / 6.0);

                    IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone,
                                                                                         masterpos.Lat < 0 ? false : true);

                    ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

                    double[] pll1 = { target.Lng, target.Lat };

                    double[] p1 = trans.MathTransform.Transform(pll1);

                    // add offsets to utm
                    p1[0] += ((HIL.Vector3)offsets[port]).x;
                    p1[1] += ((HIL.Vector3)offsets[port]).y;

                    // convert back to wgs84
                    IMathTransform inversedTransform = trans.MathTransform.Inverse();
                    double[]       point             = inversedTransform.Transform(p1);

                    target.Lat  = point[1];
                    target.Lng  = point[0];
                    target.Alt += ((HIL.Vector3)offsets[port]).z;

                    port.setGuidedModeWP(new Locationwp()
                    {
                        alt = (float)target.Alt,
                        lat = target.Lat,
                        lng = target.Lng,
                        id  = (byte)MAVLink.MAV_CMD.WAYPOINT
                    });

                    Console.WriteLine("{0} {1} {2} {3}", port.ToString(), target.Lat, target.Lng, target.Alt);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to send command " + port.ToString() + "\n" + ex.ToString());
                }

                a++;
            }
        }
        protected override void OnClick()
        {
            //
            //  TODO: Sample code showing how to access button host
            //
            #region Get Shapefile
            // Ask user to browse to a shapefile
            IGxObject openedFile = commonFunctions.OpenShapefile("Select your Fissure Waypoint Shapefile");
            if (openedFile == null)
            {
                return;
            }

            // Open the file as an IFeatureClass
            IWorkspaceFactory wsFact = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace ws     = wsFact.OpenFromFile(openedFile.Parent.FullName, 0) as IFeatureWorkspace;

            string path = @"C:\tmp\config.txt";
            if (!File.Exists(path))
            {
                MessageBox.Show("Missing the config File !");
                return;
            }

            IFeatureClass fissureWaypoints = ws.OpenFeatureClass(openedFile.Name);

            // Make sure user selected a point featureclass
            if (fissureWaypoints.ShapeType != esriGeometryType.esriGeometryPoint)
            {
                MessageBox.Show("The shapefile you selected does not contain points. Try again.");
                return;
            }

            // Make sure that the Coordinate System is set
            IGeoDataset                gDs          = fissureWaypoints as IGeoDataset;
            IGeoDatasetSchemaEdit      schemaEditor = gDs as IGeoDatasetSchemaEdit;
            ISpatialReferenceFactory2  spaRefFact   = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem projCs       = spaRefFact.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N);
            schemaEditor.AlterSpatialReference(projCs);

            // Put all the points into a cursor
            IFeatureCursor sourcePoints = fissureWaypoints.Search(null, false);
            #endregion

            #region Prepare for Loop
            // Get a reference to the Stations featureclass in EarthFissure SDE database
            IWorkspace sdeWs = commonFunctions.OpenFissureWorkspace();

            if (sdeWs == null)
            {
                return;
            }
            IFeatureClass stations = commonFunctions.OpenFeatureClass(sdeWs, "Stations");

            // Get a reference to the Fissure Info table in the SDE database
            ITable fissInfoTable = commonFunctions.OpenTable(sdeWs, "FissureStationDescription");

            // Get a reference to the SysInfo table for spinning up IDs
            sysInfo fissDbInfo = new sysInfo(sdeWs);

            // Get field indexes
            Dictionary <string, int> stationIndexes = GetFieldIndexes(stations as ITable);
            Dictionary <string, int> infoIndexes    = GetFieldIndexes(fissInfoTable);
            Dictionary <string, int> sourceIndexes  = GetFieldIndexes(fissureWaypoints as ITable);

            // Need a geographic coordinate system in the loop
            IGeographicCoordinateSystem geoCs = spaRefFact.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);

            // Setup the ProgressBar
            //setupProgressBar(fissureWaypoints.FeatureCount(null));
            #endregion

            #region Perform Loop
            // Start an edit session
            IWorkspaceEdit wsEditor = sdeWs as IWorkspaceEdit;
            wsEditor.StartEditing(false);
            wsEditor.StartEditOperation();

            try
            {
                // Get Insert Cursors
                IFeatureCursor stationInsert     = stations.Insert(true);
                ICursor        stationInfoInsert = fissInfoTable.Insert(true);

                // Loop through the source points, appending appropriately to both tables.
                IFeature sourcePoint = sourcePoints.NextFeature();

                while (sourcePoint != null)
                {
                    // Get the new station's identifier
                    string stationID = "FIS.StationPoints." + fissDbInfo.GetNextIdValue("StationPoints");

                    // Get the new station description entry's identifier
                    string descriptionID = "FIS.FissureStationDescription." + fissDbInfo.GetNextIdValue("FissureStationDescription");

                    // Get the Lat/Long values for the new point
                    IGeometry locGeom = sourcePoint.ShapeCopy as IGeometry;
                    locGeom.Project(geoCs);
                    IPoint locPoint = locGeom as IPoint;

                    // Make the new StationPoint
                    IFeatureBuffer newStation = stations.CreateFeatureBuffer();
                    newStation.set_Value(stationIndexes["Stations_ID"], stationID);
                    newStation.set_Value(stationIndexes["FieldID"], "");
                    newStation.set_Value(stationIndexes["Label"], "");
                    newStation.set_Value(stationIndexes["Symbol"], sourcePoint.get_Value(sourceIndexes["Waypoint_T"]));
                    newStation.set_Value(stationIndexes["PlotAtScale"], 24000);
                    newStation.set_Value(stationIndexes["LocationConfidenceMeters"], sourcePoint.get_Value(sourceIndexes["Horz_Prec"]));
                    newStation.set_Value(stationIndexes["MapY"], locPoint.Y);
                    newStation.set_Value(stationIndexes["MapX"], locPoint.X);
                    newStation.set_Value(stationIndexes["DataSourceID"], "");
                    newStation.Shape = sourcePoint.ShapeCopy;
                    stationInsert.InsertFeature(newStation);

                    // Make the new FissureDescription
                    IRowBuffer newDescription = fissInfoTable.CreateRowBuffer();
                    newDescription.set_Value(infoIndexes["stationid"], stationID);
                    newDescription.set_Value(infoIndexes["dateofobservation"], sourcePoint.get_Value(sourceIndexes["Date_of_th"]));
                    newDescription.set_Value(infoIndexes["timeofobservation"], sourcePoint.get_Value(sourceIndexes["Time_of_th"]));
                    newDescription.set_Value(infoIndexes["surfaceexpression"], sourcePoint.get_Value(sourceIndexes["Surface_Ex"]));
                    newDescription.set_Value(infoIndexes["displacement"], sourcePoint.get_Value(sourceIndexes["Displaceme"]));
                    newDescription.set_Value(infoIndexes["surfacewidth"], sourcePoint.get_Value(sourceIndexes["Surface_Wi"]));
                    newDescription.set_Value(infoIndexes["fissuredepth"], sourcePoint.get_Value(sourceIndexes["Fissure_De"]));
                    newDescription.set_Value(infoIndexes["vegetation"], sourcePoint.get_Value(sourceIndexes["Vegetation"]));
                    newDescription.set_Value(infoIndexes["fissureshape"], sourcePoint.get_Value(sourceIndexes["Fissure_Sh"]));
                    newDescription.set_Value(infoIndexes["linecontinuity"], string.IsNullOrEmpty(sourcePoint.get_Value(sourceIndexes["Line_Conti"]).ToString().Trim()) ? DBNull.Value : sourcePoint.get_Value(sourceIndexes["Line_Conti"]));
                    newDescription.set_Value(infoIndexes["datafile"], sourcePoint.get_Value(sourceIndexes["Datafile"]));
                    newDescription.set_Value(infoIndexes["locationwrtfissure"], sourcePoint.get_Value(sourceIndexes["Location_w"]));
                    newDescription.set_Value(infoIndexes["vegetationtype"], sourcePoint.get_Value(sourceIndexes["Vegetatio2"]));
                    newDescription.set_Value(infoIndexes["fissdescription_id"], descriptionID);
                    stationInfoInsert.InsertRow(newDescription);

                    // Iterate
                    sourcePoint = sourcePoints.NextFeature();
                    // progress.PerformStep();
                }

                // Done. Save edits.
                wsEditor.StopEditOperation();
                wsEditor.StopEditing(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
                wsEditor.StopEditOperation();
                wsEditor.StopEditing(false);
            }
            finally
            {
                // progress.Visible = false;
            }
            #endregion

            ArcMap.Application.CurrentTool = null;
        }
        public void TestDatumTransform()
        {
            ICoordinateSystemFactory cFac = new ICoordinateSystemFactory();

            //Define datums
            IHorizontalDatum wgs72 = HorizontalDatum.WGS72;
            IHorizontalDatum ed50  = HorizontalDatum.ED50;

            //Define geographic coordinate systems
            IGeographicCoordinateSystem gcsWGS72 =
                cFac.CreateGeographicCoordinateSystem("WGS72 Geographic", AngularUnit.Degrees, wgs72,
                                                      PrimeMeridian.Greenwich,
                                                      new AxisInfo("East", AxisOrientation.East),
                                                      new AxisInfo("North", AxisOrientation.North));

            IGeographicCoordinateSystem gcsWGS84 =
                cFac.CreateGeographicCoordinateSystem("WGS84 Geographic", AngularUnit.Degrees, HorizontalDatum.WGS84,
                                                      PrimeMeridian.Greenwich,
                                                      new AxisInfo("East", AxisOrientation.East),
                                                      new AxisInfo("North", AxisOrientation.North));

            IGeographicCoordinateSystem gcsED50 =
                cFac.CreateGeographicCoordinateSystem("ED50 Geographic", AngularUnit.Degrees, ed50,
                                                      PrimeMeridian.Greenwich,
                                                      new AxisInfo("East", AxisOrientation.East),
                                                      new AxisInfo("North", AxisOrientation.North));

            //Define geocentric coordinate systems
            IGeocentricCoordinateSystem gcenCsWGS72 =
                cFac.CreateGeocentricCoordinateSystem("WGS72 Geocentric", wgs72, LinearUnit.Metre,
                                                      PrimeMeridian.Greenwich);
            IGeocentricCoordinateSystem gcenCsWGS84 =
                cFac.CreateGeocentricCoordinateSystem("WGS84 Geocentric", HorizontalDatum.WGS84, LinearUnit.Metre,
                                                      PrimeMeridian.Greenwich);
            IGeocentricCoordinateSystem gcenCsED50 =
                cFac.CreateGeocentricCoordinateSystem("ED50 Geocentric", ed50, LinearUnit.Metre, PrimeMeridian.Greenwich);

            //Define projections
            //Collection<ProjectionParameter> parameters = new Collection<ProjectionParameter>(5);
            Collection <ProjectionParameter> parameters = new Collection <ProjectionParameter>();

            parameters.Add(new ProjectionParameter("latitude_of_origin", 0));
            parameters.Add(new ProjectionParameter("central_meridian", 9));
            parameters.Add(new ProjectionParameter("scale_factor", 0.9996));
            parameters.Add(new ProjectionParameter("false_easting", 500000));
            parameters.Add(new ProjectionParameter("false_northing", 0));
            IProjection projection             = cFac.CreateProjection("Transverse Mercator", "Transverse_Mercator", parameters);
            IProjectedCoordinateSystem utmED50 =
                cFac.CreateProjectedCoordinateSystem("ED50 UTM Zone 32N", gcsED50, projection, LinearUnit.Metre,
                                                     new AxisInfo("East", AxisOrientation.East),
                                                     new AxisInfo("North", AxisOrientation.North));
            IProjectedCoordinateSystem utmWGS84 =
                cFac.CreateProjectedCoordinateSystem("WGS84 UTM Zone 32N", gcsWGS84, projection, LinearUnit.Metre,
                                                     new AxisInfo("East", AxisOrientation.East),
                                                     new AxisInfo("North", AxisOrientation.North));

            //Set TOWGS84 parameters
            wgs72.Wgs84Parameters = new Wgs84ConversionInfo(0, 0, 4.5, 0, 0, 0.554, 0.219);
            ed50.Wgs84Parameters  = new Wgs84ConversionInfo(-81.0703, -89.3603, -115.7526,
                                                            -0.48488, -0.02436, -0.41321,
                                                            -0.540645); //Parameters for Denmark

            //Set up coordinate transformations
            ICoordinateTransformationFactory ctFac  = new CoordinateTransformationFactory();
            ICoordinateTransformation        ctForw = ctFac.CreateFromCoordinateSystems(gcsWGS72, gcenCsWGS72);
            //Geographic->Geocentric (WGS72)
            ICoordinateTransformation ctWGS84_Gcen2Geo = ctFac.CreateFromCoordinateSystems(gcenCsWGS84, gcsWGS84);
            //Geocentric->Geographic (WGS84)
            ICoordinateTransformation ctWGS84_Geo2UTM = ctFac.CreateFromCoordinateSystems(gcsWGS84, utmWGS84);
            //UTM ->Geographic (WGS84)
            ICoordinateTransformation ctED50_UTM2Geo = ctFac.CreateFromCoordinateSystems(utmED50, gcsED50);
            //UTM ->Geographic (ED50)
            ICoordinateTransformation ctED50_Geo2Gcen = ctFac.CreateFromCoordinateSystems(gcsED50, gcenCsED50);
            //Geographic->Geocentric (ED50)

            //Test datum-shift from WGS72 to WGS84
            //Point3D pGeoCenWGS72 = ctForw.MathTransform.Transform(pLongLatWGS72) as Point3D;
            IPoint3D pGeoCenWGS72 = new IPoint3D(3657660.66, 255768.55, 5201382.11);
            ICoordinateTransformation geocen_ed50_2_Wgs84 = ctFac.CreateFromCoordinateSystems(gcenCsWGS72, gcenCsWGS84);
            IPoint3D pGeoCenWGS84 = geocen_ed50_2_Wgs84.MathTransform.Transform(pGeoCenWGS72) as IPoint3D;

            //Point3D pGeoCenWGS84 = wgs72.Wgs84Parameters.Apply(pGeoCenWGS72);

            Assert.IsTrue(toleranceLessThan(new IPoint3D(3657660.78, 255778.43, 5201387.75), pGeoCenWGS84, 0.01));

            ICoordinateTransformation utm_ed50_2_Wgs84 = ctFac.CreateFromCoordinateSystems(utmED50, utmWGS84);
            IPoint pUTMED50  = new IPoint(600000, 6100000);
            IPoint pUTMWGS84 = utm_ed50_2_Wgs84.MathTransform.Transform(pUTMED50);

            Assert.IsTrue(toleranceLessThan(new IPoint(599928.6, 6099790.2), pUTMWGS84, 0.1));
            //Perform reverse
            ICoordinateTransformation utm_Wgs84_2_Ed50 = ctFac.CreateFromCoordinateSystems(utmWGS84, utmED50);

            pUTMED50 = utm_Wgs84_2_Ed50.MathTransform.Transform(pUTMWGS84);
            Assert.IsTrue(toleranceLessThan(new IPoint(600000, 6100000), pUTMED50, 0.1));
            //Assert.IsTrue(Math.Abs((pUTMWGS84 as Point3D).Z - 36.35) < 0.5);
            //Point pExpected = Point.FromDMS(2, 7, 46.38, 53, 48, 33.82);
            //ED50_to_WGS84_Denmark: datum.Wgs84Parameters = new Wgs84ConversionInfo(-89.5, -93.8, 127.6, 0, 0, 4.5, 1.2);
        }
Exemple #23
0
		/// <summary>
		/// 获取VCT头节点
		/// </summary>
		public HeadNode GetHeadNode()
        {
            m_HeadNode = new HeadNode();
            ///头文件数据标识、版本号、坐标系统类型,维数
            m_HeadNode.Datamark =Metadata.MetaDataFile.HeadConfig.DataMark.Value;
            m_HeadNode.Version = Metadata.MetaDataFile.HeadConfig.Version.Defualt;// "1.0";
            m_HeadNode.CoordinateSystemType = Metadata.MetaDataFile.HeadConfig.CoordSystemType.Defualt;//"C";
            m_HeadNode.Dim =Convert.ToInt32( Metadata.MetaDataFile.HeadConfig.CoordinateDim.Defualt);

            ///投影类型
            m_HeadNode.Projection = Metadata.MetaDataFile.HeadConfig.Projection.Value;

            ///头文件X、Y坐标方向
            m_HeadNode.XaxisDirection = Metadata.MetaDataFile.HeadConfig.XAxisDirection.Defualt;
            m_HeadNode.YAxisDirection = Metadata.MetaDataFile.HeadConfig.YAxisDirection.Defualt;

            //获取投影参数
           // m_HeadNode.Parametetor = Metadata.MetaDataFile.HeadConfig.ProjectionParator.Value;//ipSpheroid.SemiMajorAxis.ToString("f6") + "," + ipSpheroid.SemiMinorAxis.ToString("f6");

            ///参考椭球,长半轴,扁率的倒数
            m_HeadNode.Spheroid = Metadata.MetaDataFile.HeadConfig.Spheroid.Value; //pSpatialReference.Name + "," + ipSpheroid.SemiMajorAxis.ToString("f6") + "," + flater.ToString("f6");

            //首子午线
            m_HeadNode.PrimeMeridian = Metadata.MetaDataFile.HeadConfig.PrimeMeridian.Value;// ipProjCoordSys.get_CentralMeridian(true).ToString();

            ///比例尺
            m_HeadNode.Scale = Metadata.MetaDataFile.HeadConfig.Scale.Value;

            ///坐标单位
            m_HeadNode.Unit = Metadata.MetaDataFile.HeadConfig.CoordinateUnit.Defualt;

            ///偏移量
            m_HeadNode.Excursion = Metadata.MetaDataFile.HeadConfig.Excurtion.Value;

            //if("3_Degree")


            //获取空间参考参数
            ISpatialReference pSpatialReference = m_pSpatialReference;
            ISpheroid ipSpheroid=null;
            IProjection ipProjection;

            ///投影坐标系
            if (m_pSpatialReference is IProjectedCoordinateSystem)
            {
                //获取空间参考参数
                IProjectedCoordinateSystem ipProjCoordSys = m_pSpatialReference as IProjectedCoordinateSystem;//投影参考信息
                ipProjection = ipProjCoordSys.Projection;

                IGeographicCoordinateSystem ipGeoCoordSys = ipProjCoordSys.GeographicCoordinateSystem;
                ipSpheroid = ipGeoCoordSys.Datum.Spheroid;

                //m_HeadNode.Excursion = ipProjCoordSys.FalseEasting.ToString();///坐标偏移量

                //m_HeadNode.Scale = ipProjCoordSys.ScaleFactor.ToString("6f");//比例尺

                ///获取最小、大坐标
                double xMin = 10000000, xMax = 10000000, yMin = -10000000, yMax = -10000000;
                ipProjCoordSys.GetDomain(out xMin, out xMax, out yMin, out yMax);
                //GetXyDomain(m_pWorkspace, ref xMin, ref yMin, ref xMax, ref yMax);
                m_HeadNode.MajorMax = new PointInfoNode(xMax, yMax);
                m_HeadNode.MajorMin = new PointInfoNode(xMin, yMin);

                m_HeadNode.CoordinateSystemType = "P";

                ///投影参数(东偏、北偏、原点经度、第一标准纬线,第二标准纬线、方位角)
                m_HeadNode.Parametetor.EastOffset = ipProjCoordSys.FalseEasting.ToString();
                m_HeadNode.Parametetor.NorthOffset = ipProjCoordSys.FalseNorthing.ToString();
                m_HeadNode.Parametetor.OriginLongtitude = ipProjCoordSys.get_CentralMeridian(true).ToString();
                try
                {
                    m_HeadNode.Parametetor.FirstStandard = ipProjCoordSys.LatitudeOf1st.ToString();
                    m_HeadNode.Parametetor.SecondStandard = ipProjCoordSys.LatitudeOf2nd.ToString();
                    m_HeadNode.Parametetor.Angle = ipProjCoordSys.Azimuth.ToString();
                }
                catch
                { }
                //m_HeadNode.Parametetor.Angle = ipProjCoordSys.Azimuth.ToString();
               // m_HeadNode.Parametetor.OriginLatitude= ipProjCoordSys.

                /////根据投影名称来判断带号,带宽
                if (ipProjCoordSys.Name.Contains("3_Degree"))
                {
                    m_HeadNode.Parametetor.With = "3";
                }
                else
                {
                    m_HeadNode.Parametetor.With = "6";
                }


                ////包含Zone的表示可能带带号
                if (ipProjCoordSys.Name.Contains("Zone"))
                {
                    int index = ipProjCoordSys.Name.LastIndexOf("Zone_");
                    int nTolLen = ipProjCoordSys.Name.Length;

                    string strSubName = ipProjCoordSys.Name.Substring(index+5, nTolLen - index-5);

                    ////带号中不存在n则表示有带号
                    if (!strSubName.Contains("N"))
                        m_HeadNode.Parametetor.Num = m_HeadNode.Parametetor.Num;
                }
                else
                {
                    ///不存在带号
                }
            }
            else if (m_pSpatialReference is IGeographicCoordinateSystem)
            {
                IGeographicCoordinateSystem ipGeoCoordSys = m_pSpatialReference as IGeographicCoordinateSystem;
                ipSpheroid = ipGeoCoordSys.Datum.Spheroid;

                ///获取最小、大坐标
                double xMin = 10000000, xMax = 10000000, yMin = -10000000, yMax = -10000000;
                ipGeoCoordSys.GetDomain(out xMin, out xMax, out yMin, out yMax);
                //GetXyDomain(m_pWorkspace, ref xMin, ref yMin, ref xMax, ref yMax);
                m_HeadNode.MajorMax = new PointInfoNode(xMax, yMax);
                m_HeadNode.MajorMin = new PointInfoNode(xMin, yMin);
                m_HeadNode.CoordinateSystemType = "D";

                //中央经线
                m_HeadNode.Parametetor.OriginLongtitude = ipGeoCoordSys.PrimeMeridian.Longitude.ToString();
            }


            ///高程基准 时间参考系
            m_HeadNode.Vertical = Metadata.MetaDataFile.HeadConfig.Vertical.Value;
            m_HeadNode.TemporalReferenceSystem = Metadata.MetaDataFile.HeadConfig.TemporalReferenceSystem.Value;

            ///获取日期
            string dataTime = DateTime.Now.Year.ToString();

            ///计算月份部分不足两位加0
            if (DateTime.Now.Month < 10)
                dataTime = dataTime + "0" + DateTime.Now.Month.ToString();
            else
                dataTime += DateTime.Now.Month.ToString();
            ///计算日期部分不足两位加0
            if (DateTime.Now.Day < 10)
                dataTime = dataTime + "0" + DateTime.Now.Day.ToString();
            else
                dataTime += DateTime.Now.Day.ToString();

            m_HeadNode.Date= dataTime;
            HeadNode.Separator = Metadata.MetaDataFile.HeadConfig.Sparator.Value.ToCharArray()[0];
            return m_HeadNode;
		}
        private static ICoordinateTransformation Geog2Proj(IGeographicCoordinateSystem source, IProjectedCoordinateSystem target)
        {
            IMathTransform mathTransform = CreateCoordinateOperation(target.Projection, target.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid);

            return(new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform,
                                                String.Empty, String.Empty, -1, String.Empty, String.Empty));
        }
Exemple #25
0
        public override void SendCommand()
        {
            if (masterpos.Lat == 0 || masterpos.Lng == 0)
            {
                return;
            }

            //Console.WriteLine(DateTime.Now);
            //Console.WriteLine("Leader {0} {1} {2}", masterpos.Lat, masterpos.Lng, masterpos.Alt);

            int a = 0;

            foreach (var port in MainV2.Comports)
            {
                if (port == Leader)
                {
                    continue;
                }

                PointLatLngAlt target = new PointLatLngAlt(masterpos);

                try
                {
                    //convert Wgs84ConversionInfo to utm
                    CoordinateTransformationFactory ctfac = new CoordinateTransformationFactory();

                    GeographicCoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84;

                    int utmzone = (int)((masterpos.Lng - -186.0) / 6.0);

                    IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone,
                                                                                         masterpos.Lat < 0 ? false : true);

                    ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

                    double[] pll1 = { target.Lng, target.Lat };

                    double[] p1 = trans.MathTransform.Transform(pll1);

                    double heading = -Leader.MAV.cs.yaw;

                    double length = offsets[port].length();

                    var x = ((HIL.Vector3)offsets[port]).x;
                    var y = ((HIL.Vector3)offsets[port]).y;

                    // add offsets to utm
                    p1[0] += x * Math.Cos(heading * deg2rad) - y * Math.Sin(heading * deg2rad);
                    p1[1] += x * Math.Sin(heading * deg2rad) + y * Math.Cos(heading * deg2rad);

                    if (port.MAV.cs.firmware == MainV2.Firmwares.ArduPlane)
                    {
                        // project the point forwards gs*5
                        var gs = port.MAV.cs.groundspeed;

                        p1[1] += gs * 5 * Math.Cos((-heading) * deg2rad);
                        p1[0] += gs * 5 * Math.Sin((-heading) * deg2rad);
                    }
                    // convert back to wgs84
                    IMathTransform inversedTransform = trans.MathTransform.Inverse();
                    double[]       point             = inversedTransform.Transform(p1);

                    target.Lat  = point[1];
                    target.Lng  = point[0];
                    target.Alt += ((HIL.Vector3)offsets[port]).z;

                    if (port.MAV.cs.firmware == MainV2.Firmwares.ArduPlane)
                    {
                        var dist = target.GetDistance(new PointLatLngAlt(port.MAV.cs.lat, port.MAV.cs.lng, port.MAV.cs.alt));

                        dist -= port.MAV.cs.groundspeed * 5;

                        var leadergs = Leader.MAV.cs.groundspeed;

                        var newspeed = (leadergs + (float)(dist / 10));

                        if (newspeed < 5)
                        {
                            newspeed = 5;
                        }

                        port.setParam("TRIM_ARSPD_CM", newspeed * 100.0f);

                        // send position
                        port.setGuidedModeWP(new Locationwp()
                        {
                            alt = (float)target.Alt,
                            lat = target.Lat,
                            lng = target.Lng,
                            id  = (ushort)MAVLink.MAV_CMD.WAYPOINT
                        });
                    }
                    else
                    {
                        Vector3 vel = new Vector3(Math.Cos(Leader.MAV.cs.groundcourse * deg2rad) * Leader.MAV.cs.groundspeed,
                                                  Math.Sin(Leader.MAV.cs.groundcourse * deg2rad) * Leader.MAV.cs.groundspeed, Leader.MAV.cs.verticalspeed);

                        port.setPositionTargetGlobalInt((byte)port.sysidcurrent, (byte)port.compidcurrent, true, true, false,
                                                        MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT_INT, target.Lat, target.Lng, target.Alt, vel.x, vel.y, -vel.z);
                    }

                    //Console.WriteLine("{0} {1} {2} {3}", port.ToString(), target.Lat, target.Lng, target.Alt);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to send command " + port.ToString() + "\n" + ex.ToString());
                }

                a++;
            }
        }
Exemple #26
0
        public override void SendCommand()
        {
            if (masterpos.Lat == 0 || masterpos.Lng == 0)
            {
                return;
            }

            //Console.WriteLine(DateTime.Now);
            //Console.WriteLine("Leader {0} {1} {2}", masterpos.Lat, masterpos.Lng, masterpos.Alt);

            int a = 0;

            foreach (var port in MainV2.Comports.ToArray())
            {
                foreach (var mav in port.MAVlist)
                {
                    if (mav == Leader)
                    {
                        continue;
                    }

                    PointLatLngAlt target = new PointLatLngAlt(masterpos);

                    try
                    {
                        int utmzone = (int)((masterpos.Lng - -186.0) / 6.0);

                        IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone,
                                                                                             masterpos.Lat < 0 ? false : true);

                        ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

                        double[] pll1 = { target.Lng, target.Lat };

                        double[] p1 = trans.MathTransform.Transform(pll1);

                        double heading = -Leader.cs.yaw;

                        double length = offsets[mav].length();

                        var x = ((Vector3)offsets[mav]).x;
                        var y = ((Vector3)offsets[mav]).y;

                        // add offsets to utm
                        p1[0] += x * Math.Cos(heading * MathHelper.deg2rad) - y * Math.Sin(heading * MathHelper.deg2rad);
                        p1[1] += x * Math.Sin(heading * MathHelper.deg2rad) + y * Math.Cos(heading * MathHelper.deg2rad);

                        // convert back to wgs84
                        IMathTransform inversedTransform = trans.MathTransform.Inverse();
                        double[]       point             = inversedTransform.Transform(p1);

                        target.Lat  = point[1];
                        target.Lng  = point[0];
                        target.Alt += ((Vector3)offsets[mav]).z;

                        if (mav.cs.firmware == Firmwares.ArduPlane)
                        {
                            // get distance from target position
                            var dist = target.GetDistance(mav.cs.Location);

                            // get bearing to target
                            var targyaw = mav.cs.Location.GetBearing(target);

                            var targettrailer = target.newpos(Leader.cs.yaw, Math.Abs(dist) * -0.25);
                            var targetleader  = target.newpos(Leader.cs.yaw, 10 + dist);

                            var yawerror       = wrap_180(targyaw - mav.cs.yaw);
                            var mavleadererror = wrap_180(Leader.cs.yaw - mav.cs.yaw);

                            if (dist < 100)
                            {
                                targyaw  = mav.cs.Location.GetBearing(targetleader);
                                yawerror = wrap_180(targyaw - mav.cs.yaw);

                                var targBearing = mav.cs.Location.GetBearing(target);

                                // check the bearing for the leader and target are within 45 degrees.
                                if (Math.Abs(wrap_180(targBearing - targyaw)) > 45)
                                {
                                    dist *= -1;
                                }
                            }
                            else
                            {
                                targyaw  = mav.cs.Location.GetBearing(targettrailer);
                                yawerror = wrap_180(targyaw - mav.cs.yaw);
                            }

                            // display update
                            mav.GuidedMode.x = (int)(target.Lat * 1e7);
                            mav.GuidedMode.y = (int)(target.Lng * 1e7);
                            mav.GuidedMode.z = (float)target.Alt;

                            MAVLink.mavlink_set_attitude_target_t att_target = new MAVLink.mavlink_set_attitude_target_t();
                            att_target.target_system    = mav.sysid;
                            att_target.target_component = mav.compid;
                            att_target.type_mask        = 0xff;

                            Tuple <PID, PID, PID, PID> pid;

                            if (pids.ContainsKey(mav))
                            {
                                pid = pids[mav];
                            }
                            else
                            {
                                pid = new Tuple <PID, PID, PID, PID>(
                                    new PID(1f, .03f, 0.02f, 10, 20, 0.1f, 0),
                                    new PID(1f, .03f, 0.02f, 10, 20, 0.1f, 0),
                                    new PID(1, 0, 0.00f, 15, 20, 0.1f, 0),
                                    new PID(0.01f, 0.001f, 0, 0.5f, 20, 0.1f, 0));
                                pids.Add(mav, pid);
                            }

                            var rollp   = pid.Item1;
                            var pitchp  = pid.Item2;
                            var yawp    = pid.Item3;
                            var thrustp = pid.Item4;

                            var newroll  = 0d;
                            var newpitch = 0d;

                            if (true)
                            {
                                var altdelta = target.Alt - mav.cs.alt;
                                newpitch              = altdelta;
                                att_target.type_mask -= 0b00000010;

                                pitchp.set_input_filter_all((float)altdelta);

                                newpitch = pitchp.get_pid();
                            }

                            if (true)
                            {
                                var leaderturnrad = Leader.cs.radius;
                                var mavturnradius = leaderturnrad - x;

                                {
                                    var distToTarget    = mav.cs.Location.GetDistance(target);
                                    var bearingToTarget = mav.cs.Location.GetBearing(target);

                                    // bearing stability
                                    if (distToTarget < 30)
                                    {
                                        bearingToTarget = mav.cs.Location.GetBearing(targetleader);
                                    }
                                    // fly in from behind
                                    if (distToTarget > 100)
                                    {
                                        bearingToTarget = mav.cs.Location.GetBearing(targettrailer);
                                    }

                                    var bearingDelta = wrap_180(bearingToTarget - mav.cs.yaw);
                                    var tangent90    = bearingDelta > 0 ? 90 : -90;

                                    newroll = 0;

                                    // if the delta is > 90 then we are facing the wrong direction
                                    if (Math.Abs(bearingDelta) < 85)
                                    {
                                        var insideAngle = Math.Abs(tangent90 - bearingDelta);
                                        var angleCenter = 180 - insideAngle * 2;

                                        // sine rule
                                        var sine1 = Math.Max(distToTarget, 40) /
                                                    Math.Sin(angleCenter * MathHelper.deg2rad);
                                        var radius = sine1 * Math.Sin(insideAngle * MathHelper.deg2rad);

                                        // average calced + leader offset turnradius - acts as a FF
                                        radius = (Math.Abs(radius) + Math.Abs(mavturnradius)) / 2;

                                        var angleBank = ((mav.cs.groundspeed * mav.cs.groundspeed) / radius) / 9.8;

                                        angleBank *= MathHelper.rad2deg;

                                        if (bearingDelta > 0)
                                        {
                                            newroll = Math.Abs(angleBank);
                                        }
                                        else
                                        {
                                            newroll = -Math.Abs(angleBank);
                                        }
                                    }

                                    newroll += MathHelper.constrain(bearingDelta, -20, 20);
                                }

                                // tr = gs2 / (9.8 * x)
                                // (9.8 * x) * tr = gs2
                                // 9.8 * x = gs2 / tr
                                // (gs2/tr)/9.8 = x

                                var angle = ((mav.cs.groundspeed * mav.cs.groundspeed) / mavturnradius) / 9.8;

                                //newroll = angle * MathHelper.rad2deg;

                                // 1 degree of roll for ever 1 degree of yaw error
                                //newroll += MathHelper.constrain(yawerror, -20, 20);

                                //rollp.set_input_filter_all((float)yawdelta);
                            }

                            // do speed
                            if (true)
                            {
                                //att_target.thrust = (float) MathHelper.mapConstrained(dist, 0, 40, 0, 1);
                                att_target.type_mask -= 0b01000000;

                                // in m out 0-1
                                thrustp.set_input_filter_all((float)dist);

                                // prevent buildup prior to being close
                                if (dist > 40)
                                {
                                    thrustp.reset_I();
                                }

                                // 0.1 demand + pid results
                                att_target.thrust = (float)MathHelper.constrain(thrustp.get_pid(), 0.1, 1);
                            }

                            Quaternion q = new Quaternion();
                            q.from_vector312(newroll * MathHelper.deg2rad, newpitch * MathHelper.deg2rad, yawerror * MathHelper.deg2rad);

                            att_target.q    = new float[4];
                            att_target.q[0] = (float)q.q1;
                            att_target.q[1] = (float)q.q2;
                            att_target.q[2] = (float)q.q3;
                            att_target.q[3] = (float)q.q4;

                            //0b0= rpy
                            att_target.type_mask -= 0b10000101;
                            //att_target.type_mask -= 0b10000100;

                            Console.WriteLine("sysid {0} - {1} dist {2} r {3} p {4} y {5}", mav.sysid,
                                              att_target.thrust, dist, newroll, newpitch, (targyaw - mav.cs.yaw));

                            /*  Console.WriteLine("rpyt {0} {1} {2} {3} I {4} {5} {6} {7}",
                             *    rollp.get_pid(), pitchp.get_pid(), yawp.get_pid(), thrustp.get_pid(),
                             *    rollp.get_i(), pitchp.get_i(), yawp.get_i(), thrustp.get_i());
                             */
                            port.sendPacket(att_target, mav.sysid, mav.compid);
                        }
                        else
                        {
                            Vector3 vel = new Vector3(Leader.cs.vx, Leader.cs.vy, Leader.cs.vz);

                            // do pos/vel
                            port.setPositionTargetGlobalInt(mav.sysid, mav.compid, true,
                                                            true, false, false,
                                                            MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT_INT, target.Lat, target.Lng, target.Alt, vel.x,
                                                            vel.y, vel.z, 0, 0);

                            // do yaw
                            if (!gimbal)
                            {
                                // within 3 degrees dont send
                                if (Math.Abs(mav.cs.yaw - Leader.cs.yaw) > 3)
                                {
                                    port.doCommand(mav.sysid, mav.compid, MAVLink.MAV_CMD.CONDITION_YAW, Leader.cs.yaw,
                                                   100.0f, 0, 0, 0, 0, 0, false);
                                }
                            }
                            else
                            {
                                // gimbal direction
                                if (Math.Abs(mav.cs.yaw - Leader.cs.yaw) > 3)
                                {
                                    port.setMountControl(mav.sysid, mav.compid, 45, 0, Leader.cs.yaw, false);
                                }
                            }
                        }

                        //Console.WriteLine("{0} {1} {2} {3}", port.ToString(), target.Lat, target.Lng, target.Alt);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to send command " + mav.ToString() + "\n" + ex.ToString());
                    }

                    a++;
                }
            }
        }
 public static string FormatSpatialReference(ISpatialReference sr)
 {
     try
     {
         if (sr == null)
         {
             return("");
         }
         StringBuilder builder = new StringBuilder();
         if (sr is UnknownCoordinateSystem)
         {
             builder.Append("UnknownCoordinateSystem");
         }
         else
         {
             if (sr.Name == "Unknown")
             {
                 builder.Append("UnknownCoordinateSystem");
             }
             else
             {
                 IGeographicCoordinateSystem system2;
                 if (sr is IProjectedCoordinateSystem)
                 {
                     Exception exception;
                     IProjectedCoordinateSystem system = sr as IProjectedCoordinateSystem;
                     builder.Append("投影坐标系:\n");
                     builder.Append("  Name:").Append(system.Name).Append("\n");
                     builder.Append("  Alias:").Append(system.Alias).Append("\n");
                     builder.Append("  Abbreviation:").Append(system.Abbreviation).Append("\n");
                     builder.Append("  Remarks:").Append(system.Remarks).Append("\n");
                     builder.Append("投影:").Append(system.Projection.Name).Append("\n");
                     builder.Append("投影参数:\n");
                     builder.Append("   False_Easting:").Append(system.FalseEasting).Append("\n");
                     builder.Append("   False_Northing:").Append(system.FalseNorthing).Append("\n");
                     builder.Append("   Central_Meridian:").Append(system.get_CentralMeridian(true)).Append("\n");
                     try
                     {
                         builder.Append("   Scale_Factor:").Append(system.ScaleFactor).Append("\n");
                     }
                     catch
                     {
                     }
                     builder.Append("   Latitude_Of_Origin:0\n");
                     builder.Append("Linear Unit:")
                     .Append(system.CoordinateUnit.Name)
                     .Append("(")
                     .Append(system.CoordinateUnit.MetersPerUnit)
                     .Append(")\n");
                     builder.Append("Geographic Coordinate System:\n");
                     system2 = system.GeographicCoordinateSystem;
                     builder.Append("  Name:").Append(system2.Name).Append("\n");
                     builder.Append("  Alias:").Append(system2.Alias).Append("\n");
                     builder.Append("  Abbreviation:").Append(system2.Abbreviation).Append("\n");
                     builder.Append("  Remarks:").Append(system2.Remarks).Append("\n");
                     builder.Append("  Angular Unit:")
                     .Append(system2.CoordinateUnit.Name)
                     .Append("(")
                     .Append(system2.CoordinateUnit.RadiansPerUnit)
                     .Append(")\n");
                     builder.Append("  Prime Meridian:")
                     .Append(system2.PrimeMeridian.Name)
                     .Append("(")
                     .Append(system2.PrimeMeridian.Longitude)
                     .Append(")\n");
                     builder.Append("  Datum:").Append(system2.Datum.Name).Append("\n");
                     builder.Append("    Spheroid:").Append(system2.Datum.Spheroid.Name).Append("\n");
                     builder.Append("      Semimajor Axis:")
                     .Append(system2.Datum.Spheroid.SemiMajorAxis)
                     .Append("\n");
                     builder.Append("      Semiminor Axis:")
                     .Append(system2.Datum.Spheroid.SemiMinorAxis)
                     .Append("\n");
                     builder.Append("      Inverse Flattening:")
                     .Append((double)(1.0 / system2.Datum.Spheroid.Flattening))
                     .Append("\n");
                     builder.Append("X/Y Domain:\n");
                     try
                     {
                         double num  = 0.0;
                         double num2 = 0.0;
                         double num3 = 0.0;
                         double num4 = 0.0;
                         double num5 = 0.0;
                         sr.GetDomain(out num, out num3, out num2, out num4);
                         sr.GetFalseOriginAndUnits(out num, out num2, out num5);
                         builder.Append(" Min X:").Append(num).Append("\n");
                         builder.Append(" Min Y:").Append(num2).Append("\n");
                         builder.Append(" Max X:").Append(num3).Append("\n");
                         builder.Append(" Max Y:").Append(num4).Append("\n");
                         builder.Append(" XYScale:").Append(num5).Append("\n");
                         builder.Append("\n");
                     }
                     catch (Exception exception1)
                     {
                         exception = exception1;
                     }
                     builder.Append("Z Domain:\n");
                     try
                     {
                         double num6;
                         double num7;
                         double num8 = 0.0;
                         sr.GetZDomain(out num6, out num7);
                         sr.GetZFalseOriginAndUnits(out num6, out num8);
                         builder.Append("  Min Z:").Append(num6).Append("\n");
                         builder.Append("  Max Z:").Append(num7).Append("\n");
                         builder.Append("  ZScale:").Append(num8).Append("\n");
                         builder.Append("\n");
                     }
                     catch (Exception exception2)
                     {
                         exception = exception2;
                     }
                     try
                     {
                         double num9;
                         double num10;
                         builder.Append("M Domain:\n");
                         double num11 = 0.0;
                         sr.GetMDomain(out num9, out num10);
                         sr.GetMFalseOriginAndUnits(out num9, out num11);
                         builder.Append("  Min M:").Append(num9).Append("\n");
                         builder.Append("  Max M:").Append(num10).Append("\n");
                         builder.Append("  MScale:").Append(num11).Append("\n");
                     }
                     catch (Exception exception3)
                     {
                         exception = exception3;
                     }
                 }
                 else if (sr is IGeographicCoordinateSystem)
                 {
                     builder.Append("Geographic Coordinate System:\n");
                     system2 = sr as IGeographicCoordinateSystem;
                     builder.Append("  Name:").Append(system2.Name).Append("\n");
                     builder.Append("  Alias:").Append(system2.Alias).Append("\n");
                     builder.Append("  Abbreviation:").Append(system2.Abbreviation).Append("\n");
                     builder.Append("  Remarks:").Append(system2.Remarks).Append("\n");
                     builder.Append("  Angular Unit:")
                     .Append(system2.CoordinateUnit.Name)
                     .Append("(")
                     .Append(system2.CoordinateUnit.RadiansPerUnit)
                     .Append(")\n");
                     builder.Append("  Prime Meridian:")
                     .Append(system2.PrimeMeridian.Name)
                     .Append("(")
                     .Append(system2.PrimeMeridian.Longitude)
                     .Append(")\n");
                     builder.Append("  Datum:").Append(system2.Datum.Name).Append("\n");
                     builder.Append("    Spheroid:").Append(system2.Datum.Spheroid.Name).Append("\n");
                     builder.Append("      Semimajor Axis:")
                     .Append(system2.Datum.Spheroid.SemiMajorAxis)
                     .Append("\n");
                     builder.Append("      Semiminor Axis:")
                     .Append(system2.Datum.Spheroid.SemiMinorAxis)
                     .Append("\n");
                     builder.Append("      Inverse Flattening:")
                     .Append((double)(1.0 / system2.Datum.Spheroid.Flattening))
                     .Append("\n");
                 }
             }
         }
         return(builder.ToString());
     }
     catch (Exception ex)
     {
         return("");
     }
 }
        public static void WriteProjectedCoordinateSystem(IProjectedCoordinateSystem projectedCoordinateSystem, IndentedTextWriter writer)
        {
            writer.WriteLine("PROJCS[");
            writer.Indent=writer.Indent+1;
            writer.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "\"{0}\",",projectedCoordinateSystem.Name));
            WriteGeographicCoordinateSystem(projectedCoordinateSystem.GeographicCoordinateSystem, writer);
            writer.WriteLine(",");
            WriteProjection( projectedCoordinateSystem.Projection, writer);
            for(int dimension=0;  dimension<projectedCoordinateSystem.Dimension; dimension++)
            {
                WriteAxis( projectedCoordinateSystem.GetAxis(dimension), writer );
            }
            writer.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "AUTHORITY[\"{0}\",\"{1}\"]", projectedCoordinateSystem.Authority, projectedCoordinateSystem.AuthorityCode));

            writer.Indent=writer.Indent-1;
            writer.WriteLine("]");
        }
Exemple #29
0
        /// <summary>
        /// 检查坐标系统
        /// </summary>
        /// <param name="cFeatCls">源数据要素</param>
        /// <param name="tuFeatCls">待匹配数据要素</param>
        /// <returns></returns>
        public static bool CheckCoordinateSystem(IFeatureClass cFeatCls, IFeatureClass tuFeatCls)
        {
            try
            {
                IDataset          cDataset          = cFeatCls as IDataset;
                IGeoDataset       cGeoDataset       = cDataset as IGeoDataset;
                ISpatialReference cSpatialReference = cGeoDataset.SpatialReference;

                IDataset          tuDataset          = tuFeatCls as IDataset;
                IGeoDataset       tuGeoDataset       = tuDataset as IGeoDataset;
                ISpatialReference tuSpatialReference = tuGeoDataset.SpatialReference;

                if (cSpatialReference is IGeographicCoordinateSystem)
                {
                    if (tuSpatialReference is IGeographicCoordinateSystem)
                    {
                        IGeographicCoordinateSystem cGeoCS  = cSpatialReference as IGeographicCoordinateSystem;
                        IGeographicCoordinateSystem tuGeoCS = tuSpatialReference as IGeographicCoordinateSystem;

                        if (cGeoCS.Name == tuGeoCS.Name)
                        {
                            if (cGeoCS.CoordinateUnit.Name == tuGeoCS.CoordinateUnit.Name)
                            {
                                return(true);
                            }
                            else
                            {
                                MessageBox.Show("坐标系统单位不一致!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return(false);
                            }
                        }
                        else
                        {
                            MessageBox.Show("坐标系统投影不一致!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return(false);
                        }
                    }
                    else
                    {
                        MessageBox.Show("坐标系统不一致!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return(false);
                    }
                }
                else if (cSpatialReference is IProjectedCoordinateSystem)
                {
                    if (tuSpatialReference is IProjectedCoordinateSystem)
                    {
                        IProjectedCoordinateSystem cProCS  = cSpatialReference as IProjectedCoordinateSystem;
                        IProjectedCoordinateSystem tuProCS = tuSpatialReference as IProjectedCoordinateSystem;

                        if (cProCS.Name == tuProCS.Name)
                        {
                            if (cProCS.CoordinateUnit.Name == tuProCS.CoordinateUnit.Name)
                            {
                                return(true);
                            }
                            else
                            {
                                MessageBox.Show("坐标系统单位不一致!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return(false);
                            }
                        }
                        else
                        {
                            MessageBox.Show("坐标系统投影不一致!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return(false);
                        }
                    }
                    else
                    {
                        MessageBox.Show("坐标系统不一致!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return(false);
                    }
                }
                else
                {
                    MessageBox.Show("更新图层坐标系统未知!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(false);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #30
0
        private void btnSelect_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog flg = new OpenFileDialog();
            flg.Filter = "�����ļ�(*prj)|*.prj";

            string coordPath = Application.StartupPath + "\\����ϵͳ";

            if (!System.IO.Directory.Exists(coordPath))
                System.IO.Directory.CreateDirectory(coordPath);
            flg.InitialDirectory = coordPath;

            if (flg.ShowDialog() == DialogResult.OK)
            {
                ISpatialReferenceFactory SpRefFac = new SpatialReferenceEnvironmentClass();
                ISpatialReference SpRef = SpRefFac.CreateESRISpatialReferenceFromPRJFile(flg.FileName);

                this.m_SpatialReferenceName = SpRef.Name;

                if (flg.FileName.Contains("�������ϵ"))
                {
                    this.m_CurGeoCoord = SpRef as IGeographicCoordinateSystem;
                    this.m_Datum = m_CurGeoCoord.Datum.Name;
                    this.txtName.Text = m_CurGeoCoord.Name;
                    this.LoadGeoCoord(true, this.m_CurGeoCoord);
                    this.LoadFileContent(flg.FileName);
                }
                else if (flg.FileName.Contains("ƽ������ϵ"))
                {
                    this.m_CurProCoord = SpRef as IProjectedCoordinateSystem;
                    this.m_Datum = m_CurProCoord.GeographicCoordinateSystem.Datum.Name;
                    this.txtName.Text = m_CurProCoord.Name;
                    this.LoadProCoord(true, this.m_CurProCoord);
                    this.LoadFileContent(flg.FileName);
                }
            }
        }
Exemple #31
0
        private void method_1(ISpatialReference ispatialReference_1)
        {
            IGeographicCoordinateSystem geographicCoordinateSystem;
            string str;

            this.textBoxName.Text = ispatialReference_1.Name;
            if (ispatialReference_1 is IGeographicCoordinateSystem)
            {
                geographicCoordinateSystem = (IGeographicCoordinateSystem)ispatialReference_1;
                str = ("别名: " + geographicCoordinateSystem.Alias + "\r\n") + "缩略名: " +
                      geographicCoordinateSystem.Abbreviation + "\r\n";
                string[] strArray = new string[21];
                strArray[0]  = str;
                strArray[1]  = "说明: ";
                strArray[2]  = geographicCoordinateSystem.Remarks;
                strArray[3]  = "\r\n角度单位: ";
                strArray[4]  = geographicCoordinateSystem.CoordinateUnit.Name;
                strArray[5]  = " (";
                strArray[6]  = geographicCoordinateSystem.CoordinateUnit.RadiansPerUnit.ToString();
                strArray[7]  = ")\r\n本初子午线: ";
                strArray[8]  = geographicCoordinateSystem.PrimeMeridian.Name;
                strArray[9]  = " (";
                strArray[10] = geographicCoordinateSystem.PrimeMeridian.Longitude.ToString();
                strArray[11] = ")\r\n数据: ";
                strArray[12] = geographicCoordinateSystem.Datum.Name;
                strArray[13] = "\r\n  椭球体: ";
                strArray[14] = geographicCoordinateSystem.Datum.Spheroid.Name;
                strArray[15] = "\r\n    长半轴: ";
                strArray[16] = geographicCoordinateSystem.Datum.Spheroid.SemiMajorAxis.ToString();
                strArray[17] = "\r\n    短半轴: ";
                strArray[18] = geographicCoordinateSystem.Datum.Spheroid.SemiMinorAxis.ToString();
                strArray[19] = "\r\n    扁率倒数: ";
                double num = 1.0 / geographicCoordinateSystem.Datum.Spheroid.Flattening;
                strArray[20]            = num.ToString();
                str                     = string.Concat(strArray);
                this.textBoxDetail.Text = str;
                if (this.bool_0)
                {
                    this.btnModify.Enabled = true;
                    this.btnClear.Enabled  = true;
                    this.btnSaveAs.Enabled = true;
                }
            }
            else if (!(ispatialReference_1 is IProjectedCoordinateSystem))
            {
                if (ispatialReference_1 is IUnknownCoordinateSystem)
                {
                    str = "未知坐标系统";
                    this.textBoxDetail.Text = str;
                    if (this.ispatialReference_0 is IUnknownCoordinateSystem)
                    {
                        this.btnModify.Enabled = false;
                        this.btnClear.Enabled  = false;
                        this.btnSaveAs.Enabled = false;
                    }
                    else if (this.bool_0)
                    {
                        this.btnModify.Enabled = true;
                        this.btnClear.Enabled  = true;
                        this.btnSaveAs.Enabled = true;
                    }
                }
                else
                {
                    this.btnClear.Enabled   = false;
                    this.btnModify.Enabled  = false;
                    this.textBoxDetail.Text = "";
                }
            }
            else
            {
                IProjectedCoordinateSystem system2 = (IProjectedCoordinateSystem)ispatialReference_1;
                geographicCoordinateSystem = system2.GeographicCoordinateSystem;
                IProjection  projection = system2.Projection;
                IParameter[] parameters = new IParameter[25];
                ((IProjectedCoordinateSystem4GEN)system2).GetParameters(ref parameters);
                string str2 = "  ";
                for (int i = 0; i < parameters.Length; i++)
                {
                    if (parameters[i] == null)
                    {
                        break;
                    }
                    str2 = str2 + parameters[i].Name + ": " + parameters[i].Value.ToString() + "\r\n ";
                }
                str = (((("别名: " + system2.Alias + "\r\n") + "缩略名: " + system2.Abbreviation + "\r\n") + "说明: " +
                        system2.Remarks + "\r\n") + "投影: " + system2.Projection.Name + "\r\n") + "参数:\r\n" + str2;
                str = ((((str + "线性单位: " + system2.CoordinateUnit.Name + " (" +
                          system2.CoordinateUnit.MetersPerUnit.ToString() + ")\r\n") + "地理坐标系:\r\n") + "  名称: " +
                        geographicCoordinateSystem.Name + "\r\n") + "  缩略名: " + geographicCoordinateSystem.Abbreviation +
                       "\r\n") + "  说明: " + geographicCoordinateSystem.Remarks + "\r\n";
                str = str + "  角度单位: " + geographicCoordinateSystem.CoordinateUnit.Name + " (" +
                      geographicCoordinateSystem.CoordinateUnit.RadiansPerUnit.ToString() + ")\r\n";
                str = (((((str + "  本初子午线: " + geographicCoordinateSystem.PrimeMeridian.Name + " (" +
                           geographicCoordinateSystem.PrimeMeridian.Longitude.ToString() + ")\r\n") + "  数据: " +
                          geographicCoordinateSystem.Datum.Name + "\r\n") + "    椭球体: " +
                         geographicCoordinateSystem.Datum.Spheroid.Name + "\r\n") + "    长半轴: " +
                        geographicCoordinateSystem.Datum.Spheroid.SemiMajorAxis.ToString() + "\r\n") + "    短半轴: " +
                       geographicCoordinateSystem.Datum.Spheroid.SemiMinorAxis.ToString() + "\r\n") + "    扁率倒数: " +
                      ((1.0 / geographicCoordinateSystem.Datum.Spheroid.Flattening)).ToString();
                this.textBoxDetail.Text = str;
                if (this.bool_0)
                {
                    this.btnModify.Enabled = true;
                    this.btnClear.Enabled  = true;
                    this.btnSaveAs.Enabled = true;
                }
            }
        }
 private static ICoordinateTransformation Proj2Geog(IProjectedCoordinateSystem source, IGeographicCoordinateSystem target)
 {
     if (source.GeographicCoordinateSystem.EqualParams(target))
     {
         IMathTransform mathTransform = CreateCoordinateOperation(source.Projection, source.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid, source.LinearUnit).Inverse();
         return new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform,
             String.Empty, String.Empty, -1, String.Empty, String.Empty);
     }
     else
     {	// Geographic coordinatesystems differ - Create concatenated transform
         ConcatenatedTransform ct = new ConcatenatedTransform();
         CoordinateTransformationFactory ctFac = new CoordinateTransformationFactory();
         ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source, source.GeographicCoordinateSystem));
         ct.CoordinateTransformationList.Add(ctFac.CreateFromCoordinateSystems(source.GeographicCoordinateSystem, target));
         return new CoordinateTransformation(source,
             target, TransformType.Transformation, ct,
             String.Empty, String.Empty, -1, String.Empty, String.Empty);
     }
 }
        /// <summary>
        /// Creates the appropriate object given a string containing XML.
        /// </summary>
        /// <param name="wkt">String containing XML.</param>
        /// <returns>Object representation of the XML.</returns>
        /// <exception cref="ParseException">If a token is not recognised.</exception>
        public static object Create(string wkt)
        {
            object             returnObject = null;
            StringReader       reader       = new StringReader(wkt);
            WktStreamTokenizer tokenizer    = new WktStreamTokenizer(reader);

            tokenizer.NextToken();
            string objectName = tokenizer.GetStringValue();

            switch (objectName)
            {
            case "UNIT":
                IUnit unit = ReadUnit(tokenizer);
                returnObject = unit;
                break;

            case "VERT_DATUM":
                IVerticalDatum verticalDatum = ReadVerticalDatum(tokenizer);
                returnObject = verticalDatum;
                break;

            case "SPHEROID":
                IEllipsoid ellipsoid = ReadEllipsoid(tokenizer);
                returnObject = ellipsoid;
                break;

            case "TOWGS84":
                WGS84ConversionInfo wgsInfo = ReadWGS84ConversionInfo(tokenizer);
                returnObject = wgsInfo;
                break;

            case "DATUM":
                IHorizontalDatum horizontalDatum = ReadHorizontalDatum(tokenizer);
                returnObject = horizontalDatum;
                break;

            case "PRIMEM":
                IPrimeMeridian primeMeridian = ReadPrimeMeridian(tokenizer);
                returnObject = primeMeridian;
                break;

            case "VERT_CS":
                IVerticalCoordinateSystem verticalCS = ReadVerticalCoordinateSystem(tokenizer);
                returnObject = verticalCS;
                break;

            case "GEOGCS":
                IGeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer);
                returnObject = geographicCS;
                break;

            case "PROJCS":
                IProjectedCoordinateSystem projectedCS = ReadProjectedCoordinateSystem(tokenizer);
                returnObject = projectedCS;
                break;

            case "COMPD_CS":
                ICompoundCoordinateSystem compoundCS = ReadCompoundCoordinateSystem(tokenizer);
                returnObject = compoundCS;
                break;

            case "GEOCCS":
            case "FITTED_CS":
            case "LOCAL_CS":
                throw new NotSupportedException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} is not implemented.", objectName));

            default:
                throw new ParseException(String.Format(System.Globalization.CultureInfo.InvariantCulture, "'{0'} is not recongnized.", objectName));
            }
            reader.Close();
            return(returnObject);
        }
		private void MakeCoordinateSystems()
		{
			//Create a spatial reference environment and get theISpatialReferenceFactory2 interface
			ISpatialReferenceFactory2 spatRefFact = new SpatialReferenceEnvironmentClass();
			//Create a geographic coordinate system and get the IGeographicCoordinateSystem interface
			m_GeographicCoordinateSystem = spatRefFact.CreateGeographicCoordinateSystem((int) esriSRGeoCSType.esriSRGeoCS_WGS1984);
			//Create a projected coordinate system and get the IProjectedCoordinateSystem interface
			m_ProjectedCoordinateSystem = spatRefFact.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_World_Mollweide);
			//Set the map controls spatial reference property
			m_MapControl.SpatialReference = m_ProjectedCoordinateSystem;
		}
Exemple #35
0
        public override void SendCommand()
        {
            if (masterpos.Lat == 0 || masterpos.Lng == 0)
            {
                return;
            }

            //Console.WriteLine(DateTime.Now);
            //Console.WriteLine("Leader {0} {1} {2}", masterpos.Lat, masterpos.Lng, masterpos.Alt);

            int a = 0;

            foreach (var port in MainV2.Comports)
            {
                foreach (var mav in port.MAVlist)
                {
                    if (mav == Leader)
                    {
                        continue;
                    }

                    PointLatLngAlt target = new PointLatLngAlt(masterpos);

                    try
                    {
                        int utmzone = (int)((masterpos.Lng - -186.0) / 6.0);

                        IProjectedCoordinateSystem utm = ProjectedCoordinateSystem.WGS84_UTM(utmzone,
                                                                                             masterpos.Lat < 0 ? false : true);

                        ICoordinateTransformation trans = ctfac.CreateFromCoordinateSystems(wgs84, utm);

                        double[] pll1 = { target.Lng, target.Lat };

                        double[] p1 = trans.MathTransform.Transform(pll1);

                        double heading = -Leader.cs.yaw;

                        double length = offsets[mav].length();

                        var x = ((HIL.Vector3)offsets[mav]).x;
                        var y = ((HIL.Vector3)offsets[mav]).y;

                        // add offsets to utm
                        p1[0] += x * Math.Cos(heading * MathHelper.deg2rad) - y * Math.Sin(heading * MathHelper.deg2rad);
                        p1[1] += x * Math.Sin(heading * MathHelper.deg2rad) + y * Math.Cos(heading * MathHelper.deg2rad);

                        if (mav.cs.firmware == MainV2.Firmwares.ArduPlane)
                        {
                            // project the point forwards gs*5
                            var gs = mav.cs.groundspeed * 5;

                            p1[1] += gs * Math.Cos((-heading) * MathHelper.deg2rad);
                            p1[0] += gs * Math.Sin((-heading) * MathHelper.deg2rad);
                        }
                        // convert back to wgs84
                        IMathTransform inversedTransform = trans.MathTransform.Inverse();
                        double[]       point             = inversedTransform.Transform(p1);

                        target.Lat  = point[1];
                        target.Lng  = point[0];
                        target.Alt += ((HIL.Vector3)offsets[mav]).z;

                        if (mav.cs.firmware == MainV2.Firmwares.ArduPlane)
                        {
                            var dist =
                                target.GetDistance(new PointLatLngAlt(mav.cs.lat, mav.cs.lng, mav.cs.alt));

                            dist -= mav.cs.groundspeed * 5;

                            var leadergs = Leader.cs.groundspeed;

                            var newspeed = (leadergs + (float)(dist / 10));

                            if (newspeed < 5)
                            {
                                newspeed = 5;
                            }

                            port.setParam(mav.sysid, mav.compid, "TRIM_ARSPD_CM", newspeed * 100.0f);

                            // send position
                            port.setGuidedModeWP(mav.sysid, mav.compid, new Locationwp()
                            {
                                alt = (float)target.Alt,
                                lat = target.Lat,
                                lng = target.Lng,
                                id  = (ushort)MAVLink.MAV_CMD.WAYPOINT
                            });
                        }
                        else
                        {
                            Vector3 vel =
                                new Vector3(Math.Cos(Leader.cs.groundcourse * MathHelper.deg2rad) * Leader.cs.groundspeed,
                                            Math.Sin(Leader.cs.groundcourse * MathHelper.deg2rad) * Leader.cs.groundspeed,
                                            Leader.cs.verticalspeed);

                            // do pos/vel
                            port.setPositionTargetGlobalInt(mav.sysid, mav.compid, true,
                                                            true, false,
                                                            MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT_INT, target.Lat, target.Lng, target.Alt, vel.x,
                                                            vel.y, -vel.z);

                            // do yaw
                            if (!gimbal)
                            {
                                // within 3 degrees dont send
                                if (Math.Abs(mav.cs.yaw - Leader.cs.yaw) > 3)
                                {
                                    port.doCommand(mav.sysid, mav.compid, MAVLink.MAV_CMD.CONDITION_YAW, Leader.cs.yaw,
                                                   100.0f, 0, 0, 0, 0, 0, false);
                                }
                            }
                            else
                            {
                                // gimbal direction
                                if (Math.Abs(mav.cs.yaw - Leader.cs.yaw) > 3)
                                {
                                    port.setMountControl(mav.sysid, mav.compid, 45, 0, Leader.cs.yaw, false);
                                }
                            }
                        }

                        //Console.WriteLine("{0} {1} {2} {3}", port.ToString(), target.Lat, target.Lng, target.Alt);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to send command " + mav.ToString() + "\n" + ex.ToString());
                    }

                    a++;
                }
            }
        }
 private static ICoordinateTransformation Proj2Geog(IProjectedCoordinateSystem source, IGeographicCoordinateSystem target)
 {
     if (source.GeographicCoordinateSystem.EqualParams(target))
     {
         return new CoordinateTransformation(source, target, TransformType.Transformation, CreateCoordinateOperation(source.Projection, source.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid).Inverse(), string.Empty, string.Empty, -1L, string.Empty, string.Empty);
     }
     ConcatenatedTransform mathTransform = new ConcatenatedTransform();
     CoordinateTransformationFactory factory = new CoordinateTransformationFactory();
     mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source, source.GeographicCoordinateSystem));
     mathTransform.CoordinateTransformationList.Add(factory.CreateFromCoordinateSystems(source.GeographicCoordinateSystem, target));
     return new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform, string.Empty, string.Empty, -1L, string.Empty, string.Empty);
 }
 public void TestCreateProjectedCoordinateSystem3()
 {
     IProjectedCoordinateSystem uknationalgrid = _factory.CreateProjectedCoordinateSystem("27700");
     IProjectedCoordinateSystem utm32          = _factory.CreateProjectedCoordinateSystem("32206");
 }
 private static ICoordinateTransformation Proj2Geog(IProjectedCoordinateSystem source, IGeographicCoordinateSystem target)
 {
     IMathTransform mathTransform = CreateCoordinateOperation(source.Projection, source.GeographicCoordinateSystem.HorizontalDatum.Ellipsoid).Inverse();
     return new CoordinateTransformation(source, target, TransformType.Transformation, mathTransform,
         String.Empty, String.Empty, -1, String.Empty, String.Empty);
 }
        private void CalculateStatedArea(IQueryFilter m_pQF, ITable pParcelsTable, ICadastralEditor pCadEd, ISpatialReference pMapSR,
                                         double SquareMetersPerUnitFactor, string Suffix, int DecimalPlaces, ref Dictionary <int, string> dict_ParcelSelection2CalculatedArea, ITrackCancel pTrackCancel)
        {
            bool bTrackCancel = (pTrackCancel != null);
            //ILine pLine = new LineClass();

            ICursor   pCursor       = pParcelsTable.Search(m_pQF, false);
            IRow      pParcelRecord = pCursor.NextRow();
            Utilities Utils         = new Utilities();

            IArray                     pParcelFeatArr = new ArrayClass();
            IGeoDataset                pGeoDS         = (IGeoDataset)((IFeatureClass)pParcelsTable).FeatureDataset;
            ISpatialReference          pFabricSR      = pGeoDS.SpatialReference;
            IProjectedCoordinateSystem pPCS           = null;
            double                     dMetersPerUnit = 1;
            bool bFabricIsInGCS = !(pFabricSR is IProjectedCoordinateSystem);

            if (!bFabricIsInGCS)
            {
                pPCS           = (IProjectedCoordinateSystem)pFabricSR;
                dMetersPerUnit = pPCS.CoordinateUnit.MetersPerUnit;
            }
            else
            {
                pPCS           = (IProjectedCoordinateSystem)pMapSR;
                dMetersPerUnit = pPCS.CoordinateUnit.MetersPerUnit;
            }

            //for each parcel record
            while (pParcelRecord != null)
            {
                IFeature pFeat = (IFeature)pParcelRecord;
                //IGeometry pGeom = pFeat.Shape;
                pParcelFeatArr.Add(pFeat);

                Marshal.ReleaseComObject(pParcelRecord);
                if (bTrackCancel)
                {
                    if (!pTrackCancel.Continue())
                    {
                        break;
                    }
                }

                pParcelRecord = pCursor.NextRow();
            }
            Marshal.ReleaseComObject(pCursor);

            ICadastralFeatureGenerator pFeatureGenerator = new CadastralFeatureGeneratorClass();
            IEnumGSParcels             pEnumGSParcels    = pFeatureGenerator.CreateParcelsFromFeatures(pCadEd, pParcelFeatArr, true);

            pEnumGSParcels.Reset();
            Dictionary <int, int>    dict_ParcelAndStartPt = new Dictionary <int, int>();
            Dictionary <int, IPoint> dict_PointID2Point    = new Dictionary <int, IPoint>();

            //dict_PointID2Point -->> this lookup makes an assumption that the fabric TO point geometry is at the same location as the line *geometry* endpoint
            IParcelLineFunctions3 ParcelLineFx = new ParcelFunctionsClass();

            IGSParcel pGSParcel      = pEnumGSParcels.Next();
            int       iFromPtIDX     = -1;
            int       iToPtIDX       = -1;
            int       iParcelIDX     = -1;
            int       iIsMajorFldIdx = -1;

            while (pGSParcel != null)
            {
                IEnumCELines pCELines     = new EnumCELinesClass();
                IEnumGSLines pEnumGSLines = (IEnumGSLines)pCELines;

                IEnumGSLines pGSLinesInner = pGSParcel.GetParcelLines(null, false);
                pGSLinesInner.Reset();
                IGSParcel         pTemp   = null;
                IGSLine           pGSLine = null;
                ICadastralFeature pCF     = (ICadastralFeature)pGSParcel;
                int iParcID = pCF.Row.OID;
                pGSLinesInner.Next(ref pTemp, ref pGSLine);
                bool bStartPointAdded = false;
                int  iFromPtID        = -1;
                while (pGSLine != null)
                {
                    if (pGSLine.Category == esriCadastralLineCategory.esriCadastralLineBoundary ||
                        pGSLine.Category == esriCadastralLineCategory.esriCadastralLineRoad ||
                        pGSLine.Category == esriCadastralLineCategory.esriCadastralLinePartConnection)
                    {
                        pCELines.Add(pGSLine);
                        ICadastralFeature pCadastralLineFeature = (ICadastralFeature)pGSLine;
                        IFeature          pLineFeat             = (IFeature)pCadastralLineFeature.Row;
                        if (iFromPtIDX == -1)
                        {
                            iFromPtIDX = pLineFeat.Fields.FindField("FROMPOINTID");
                        }
                        if (iToPtIDX == -1)
                        {
                            iToPtIDX = pLineFeat.Fields.FindField("TOPOINTID");
                        }
                        if (iParcelIDX == -1)
                        {
                            iParcelIDX = pLineFeat.Fields.FindField("PARCELID");
                        }
                        if (iIsMajorFldIdx == -1)
                        {
                            iIsMajorFldIdx = pLineFeat.Fields.FindField("ISMAJOR");
                        }

                        if (!bStartPointAdded)
                        {
                            iFromPtID        = (int)pLineFeat.get_Value(iFromPtIDX);
                            bStartPointAdded = true;
                        }
                        IPolyline pPolyline = (IPolyline)pLineFeat.ShapeCopy;
                        //if (bFabricIsInGCS)
                        pPolyline.Project(pPCS);
                        //dict_PointID2Point -->> this lookup makes an assumption that the fabric TO point geometry is at the same location as the line *geometry* endpoint
                        int iToPtID = (int)pLineFeat.get_Value(iToPtIDX);
                        //first make sure the point is not already added
                        if (!dict_PointID2Point.ContainsKey(iToPtID))
                        {
                            dict_PointID2Point.Add(iToPtID, pPolyline.ToPoint);
                        }
                    }
                    pGSLinesInner.Next(ref pTemp, ref pGSLine);
                }

                if (pGSParcel.Unclosed)
                {//skip unclosed parcels
                    pGSParcel = pEnumGSParcels.Next();
                    continue;
                }

                ICadastralFeature pCadastralPolygonFeature = (ICadastralFeature)pGSParcel;
                IFeature          pPolygonFeat             = (IFeature)pCadastralPolygonFeature.Row;
                IPolygon          pParcelPolygon           = (IPolygon)pPolygonFeat.ShapeCopy;

                IGSForwardStar pFwdStar = ParcelLineFx.CreateForwardStar(pEnumGSLines);
                //forward star is created for this parcel, now ready to find misclose for the parcel
                List <int>       LineIdsList               = new List <int>();
                List <IVector3D> TraverseCourses           = new List <IVector3D>();
                List <int>       FabricPointIDList         = new List <int>();
                List <double>    RadiusList                = new List <double>();
                List <bool>      IsMajorList               = new List <bool>();
                List <bool>      IsRunningCounterClockwise = new List <bool>();

                bool bPass = false;
                if (!bFabricIsInGCS)
                {
                    bPass = Utils.GetParcelTraverseEx(ref pFwdStar, iIsMajorFldIdx, iFromPtID, dMetersPerUnit,
                                                      ref LineIdsList, ref TraverseCourses, ref FabricPointIDList, ref RadiusList, ref IsMajorList, ref IsRunningCounterClockwise,
                                                      pParcelPolygon, 0, -1, -1, false);
                }
                else
                {
                    bPass = Utils.GetParcelTraverseEx(ref pFwdStar, iIsMajorFldIdx, iFromPtID, dMetersPerUnit * dMetersPerUnit,
                                                      ref LineIdsList, ref TraverseCourses, ref FabricPointIDList, ref RadiusList, ref IsMajorList, ref IsRunningCounterClockwise,
                                                      pParcelPolygon, 0, -1, -1, false);
                }
                //List<double> SysValList = new List<double>();
                IVector3D MiscloseVector = null;
                IPoint[]  FabricPoints   = new IPoint[FabricPointIDList.Count];//from control

                int f = 0;
                foreach (int j in FabricPointIDList)
                {
                    FabricPoints[f++] = dict_PointID2Point[j];
                }

                double dRatio = 10000;
                double dArea  = 0;
                double dGroundToGridFactor = pGSParcel.Scale;
                bool   bHasCircularArcs    = false;
                f = FabricPointIDList.Count - 1;
                IPoint[] AdjustedTraversePoints = Utils.BowditchAdjustEx(TraverseCourses, FabricPoints[f], FabricPoints[f],
                                                                         RadiusList, IsMajorList, IsRunningCounterClockwise, out MiscloseVector, out dRatio, out dArea,
                                                                         out bHasCircularArcs);

                if (MiscloseVector == null)
                {//skip if vector closure failed
                    pGSParcel = pEnumGSParcels.Next();
                    continue;
                }
                //now compare the Geometry polygon area with the computed area to see if we need to use parametric computed area
                // there needs to be at least one circular arc to warrant using this approach.
                IArea  pGeomArea           = pPolygonFeat.ShapeCopy as IArea;
                double dGroundArea         = pGeomArea.Area / (dGroundToGridFactor * dGroundToGridFactor);
                double dAreaPercentageDiff = Math.Abs(dGroundArea - Math.Abs(dArea)) / dGroundArea;

                if (dAreaPercentageDiff > 0.075 && bHasCircularArcs && dRatio > 250)
                {
                    dArea = dGroundArea;
                }
                else if (bHasCircularArcs && dArea < 0 && dRatio > 7500) //if dArea is negative then lines are running counter-clockwise
                {
                    dArea = Math.Abs(dArea);
                }
                else if (bHasCircularArcs && dArea < 0 && pParcelPolygon.ExteriorRingCount > 1)
                {
                    dArea = pGeomArea.Area;
                }

                dArea *= (dMetersPerUnit * dMetersPerUnit); //convert to square meters first
                dArea /= SquareMetersPerUnitFactor;         //convert to the given unit equivalent

                string sFormattedArea = Math.Round(dArea, DecimalPlaces).ToString() + Suffix;
                dict_ParcelSelection2CalculatedArea.Add(pGSParcel.DatabaseId, sFormattedArea);

                pGSParcel = pEnumGSParcels.Next();

                //if (bShowProgressor)
                //{
                //  if (pStepProgressor.Position < pStepProgressor.MaxRange)
                //    pStepProgressor.Step();
                //}
            }
        }