Exemplo n.º 1
0
 protected ISpatialReference GetProjectedSpatialReference(int pcsType)
 {
     var pSrf = new SpatialReferenceEnvironmentClass();
     var projectedCoordinateSystem = pSrf.CreateProjectedCoordinateSystem(pcsType);
     var spatialReference = (ISpatialReference)projectedCoordinateSystem;
     return spatialReference;
 }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="projectionCode">projectionCode (aka: WKID)</param>
        /// <returns></returns>
        public static ISpatialReference CreateProjectedSpatialReference(int projectionCode)
        {
            ISpatialReferenceFactory   spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem pcs = spatialReferenceFactory.CreateProjectedCoordinateSystem(projectionCode);
            ISpatialReference          sr  = pcs;

            return(sr);
        }
Exemplo n.º 3
0
        private IPoint GCStoPRJ(IPoint pPoint, int GCSType, int PRJType)
        {
            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();

            pPoint.SpatialReference = pSRF.CreateGeographicCoordinateSystem(GCSType);
            pPoint.Project(pSRF.CreateProjectedCoordinateSystem(PRJType));
            return(pPoint);
        }
        // this method is called when the tool is active and the user clicks down on the mouse - it captures the x,y coords and then reprojects them to wgs and opens a browser with streetview
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            try
            {
                //show busy mouse
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;


                //get access to the document (the current mxd), and the active view (data view or layout view), and the focus map (the data frame with focus, aka: the visible map)
                IMxDocument pMxDocument = clsGlobals.arcApplication.Document as IMxDocument;
                IActiveView pActiveView = pMxDocument.ActiveView;
                IMap        pMap        = pActiveView.FocusMap;

                //IScreenDisplay screenDisplay = pActiveView.ScreenDisplay;
                //IDisplayTransformation displayTransformation = screenDisplay.DisplayTransformation;
                //displayTransformation.ToMapPoint((System.Int32)X, (System.Int32)Y);


                IEnvelope pEnvelope = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y).Envelope;

                //the following lines of code are needed to reproject the map units into google maps lat long
                //Create Spatial Reference Factory
                ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();

                IProjectedCoordinateSystem  arcProjCoordSysUTM12_North = srFactory.CreateProjectedCoordinateSystem(26912);
                IGeographicCoordinateSystem arcGeographicCoordSysWgs84 = srFactory.CreateGeographicCoordinateSystem(4326);//esriSRGeoCS_WGS1984 4326 WGS 1984.


                //get the point on the map that was clicked on
                IPoint pMapPoint = new ESRI.ArcGIS.Geometry.Point();
                pMapPoint.X = Convert.ToDouble(pEnvelope.XMax);
                pMapPoint.Y = Convert.ToDouble(pEnvelope.YMax);

                //give the arcmap point a spatial reference
                pMapPoint.SpatialReference = arcProjCoordSysUTM12_North;

                //reproject that point to nad83 arizona central state plane
                pMapPoint.Project(arcGeographicCoordSysWgs84);

                //MessageBox.Show(pMapPoint.X + ",   " + pMapPoint.Y, "caption", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //open the default internet browser and pass in the apn number to the assessor's gis website, and then zoom to the apn
                System.Diagnostics.Process.Start("https://maps.google.com/maps?q=&layer=c&cbll=" + pMapPoint.Y + "," + pMapPoint.X + "&cbp=12,0,0,0,0");

                //deactivate the tool
                //this.m_deactivate = true;
                //this.Deactivate();
                //base.Deactivate();
                //this.Deactivate();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Message: " + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine +
                                "Error Source: " + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine +
                                "Error Location:" + Environment.NewLine + ex.StackTrace,
                                "UTRANS Editor tool error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// 坐标系转换-----投影坐标系转WGS84
 /// </summary>
 /// <param name="x">x坐标</param>
 /// <param name="y">y坐标</param>
 /// <returns>转换后的IPoint</returns>
 public static IPoint getGeoPoint(double x, double y)
 {
     IPoint pProjPoint = new PointClass();
     pProjPoint.PutCoords(x, y);
     ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
     pProjPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem((int)(esriSRProjCSType.esriSRProjCS_WGS1984UTM_31N));
     pProjPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984)));
     return pProjPoint;      //此时为经纬度点
 }
Exemplo n.º 6
0
        public static IGeometry ConvertProjToGeo(IGeometry geometry)
        {
            ISpatialReferenceFactory2 originalSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         originalSpatialReference        = originalSpatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_WGS1984UTM_49N);

            ISpatialReferenceFactory2 currentSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         currentSpatialReference        = currentSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

            return(GeometryUtilities.ConvertCS(geometry, originalSpatialReference, currentSpatialReference));
        }
Exemplo n.º 7
0
        /// <summary>
        /// 投影坐标转经纬坐标
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        private static IPoint PRJtoGCS(double x, double y)
        {
            IPoint pPoint = new PointClass();

            pPoint.PutCoords(x, y);
            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();

            pPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem(2414);
            pPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954));
            return(pPoint);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 坐标系转换-----投影坐标系转WGS84
        /// </summary>
        /// <param name="x">x坐标</param>
        /// <param name="y">y坐标</param>
        /// <returns>转换后的IPoint</returns>
        public static IPoint getGeoPoint(double x, double y)
        {
            IPoint pProjPoint = new PointClass();

            pProjPoint.PutCoords(x, y);
            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();

            pProjPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem((int)(esriSRProjCSType.esriSRProjCS_WGS1984UTM_31N));
            pProjPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984)));
            return(pProjPoint);      //此时为经纬度点
        }
Exemplo n.º 9
0
        private IFeatureClass CreateObserversFeatureClass(IFeatureWorkspace workspace)
        {
            // Create Srs
            ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        sr = spatialrefFactory.CreateProjectedCoordinateSystem(
                (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));

            IFeatureClass pointFc = RLOSViewModel.CreateObserversFeatureClass(workspace, sr, "tempFC");

            return(pointFc);
        }
Exemplo n.º 10
0
        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;
        }
Exemplo n.º 11
0
        private void button2_Click(object sender, EventArgs e)
        {
            //工作空间
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pFeatureWorkspace = pWorkspaceFactory.OpenFromFile(pFilePath, 0) as IFeatureWorkspace;

            //创建字段集2
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            //创建必要字段
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;

            //必要字段
            IFields pFields = new FieldsClass();

            pFields = ocDescription.RequiredFields;

            //要素类的几何类型、坐标系
            int              shapeFileIndex   = pFields.FindField(fcDescription.ShapeFieldName);
            IField           pField           = pFields.get_Field(shapeFileIndex);
            IGeometryDef     pGeometryDef     = pField.GeometryDef;
            IGeometryDefEdit pGeometryDefEdit = (IGeometryDefEdit)pGeometryDef;

            pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();

            //更改为可选的坐标系
            IProjectedCoordinateSystem pProjectedCoordinateSystem = pSpatialReferenceFactory.CreateProjectedCoordinateSystem(
                (int)esriSRProjCS4Type.esriSRProjCS_Xian1980_GK_Zone_21);

            pGeometryDefEdit.SpatialReference_2 = pProjectedCoordinateSystem;


            //自定义字段
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

            addField(pFieldsEdit, "FID");
            addField(pFieldsEdit, "Row");
            addField(pFieldsEdit, "Column");
            addField(pFieldsEdit, "Number");
            //传入字段
            IFieldChecker   pFieldChecker   = new FieldCheckerClass();
            IEnumFieldError pEnumFieldError = null;
            IFields         validatedFields = null;

            pFieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkspace;
            pFieldChecker.Validate(pFields, out pEnumFieldError, out validatedFields);

            //创建要素类
            IFeatureClass pFeatureClass = pFeatureWorkspace.CreateFeatureClass(pFileName, validatedFields
                                                                               , ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");

            MessageBox.Show("创建要素类成功");
        }
Exemplo n.º 12
0
        /// <summary>
        /// 获得空间参考
        /// </summary>
        /// <param name="spatialStr">空间参考参数</param>
        /// <returns></returns>
        private ISpatialReference GetSpatialRef(string spatialStr)
        {
            ISpatialReference         pSpaRef     = null;
            ISpatialReferenceFactory2 pSpatRefFac = new SpatialReferenceEnvironmentClass();

            switch (spatialStr)
            {
            case "西安高斯117度(3度带)":
                pSpaRef = pSpatRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_CM_117E) as ISpatialReference;
                break;

            case "西安高斯120度(3度带)":
                pSpaRef = pSpatRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_CM_120E) as ISpatialReference;
                break;

            case "西安高斯123度(3度带)":
                pSpaRef = pSpatRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_CM_123E) as ISpatialReference;
                break;
            }
            return(pSpaRef);
        }
Exemplo n.º 13
0
 /// <summary>
 /// 坐标系转换-----WGS84转投影坐标系
 /// </summary>
 /// <param name="point">转换前的IPoint</param>
 /// <returns>转换后的IPoint</returns>
 public static IPoint getProjectPoint(IPoint point)
 {
     try
     {
         ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
         point.SpatialReference = pSRF.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984));
         point.Project(pSRF.CreateProjectedCoordinateSystem((int)(esriSRProjCSType.esriSRProjCS_WGS1984UTM_31N)));
     }
     catch //(Exception e)
     {
         // MessageBox.Show(e.ToString());
     }
     return(point);
 }
Exemplo n.º 14
0
        /// 将经纬度点转换为平面坐标。
        private IPoint GetProject(double x, double y)
        {
            ISpatialReferenceFactory    pfactory = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem  flatref  = pfactory.CreateProjectedCoordinateSystem(102003);
            IGeographicCoordinateSystem earthref = pfactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);
            IPoint pt = new PointClass();

            pt.PutCoords(x, y);
            IGeometry geo = (IGeometry)pt;

            geo.SpatialReference = earthref;
            geo.Project(flatref);
            return(pt);
        }
Exemplo n.º 15
0
 public static IPoint JWD2XY(IPoint pJWDPoint, int gcsType, int pcsType)
 {
     try
     {
         ISpatialReferenceFactory factory = new SpatialReferenceEnvironmentClass();
         pJWDPoint.SpatialReference = factory.CreateGeographicCoordinateSystem(gcsType);
         pJWDPoint.Project(factory.CreateProjectedCoordinateSystem(pcsType));
         return(pJWDPoint);
     }
     catch
     {
         return(null);
     }
 }
Exemplo n.º 16
0
 private static bool IsProjectedSpatialReference(int pcsType)
 {
     try
     {
         var pSrf = new SpatialReferenceEnvironmentClass();
         var mProjectedCoordinateSystem = pSrf.CreateProjectedCoordinateSystem(pcsType);
         // ReSharper disable once UnusedVariable
         var spatialReference = (ISpatialReference)mProjectedCoordinateSystem;
         return true;
     }
     catch
     {
         return false;
     }
 }
Exemplo n.º 17
0
//---------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 用arcgis模型工具根据表格数据把表格转化为shp文件
        /// </summary>
        /// <param name="modelName">arcgis中模型的名称</param>
        /// <param name="excelpath">表格路径</param>
        /// <param name="xField">表格中作为X坐标的字段</param>
        /// <param name="yField">表格中作为Y坐标的字段</param>
        /// <param name="wkid">坐标系参数</param>
        /// <param name="shpPath">输出shp文件路径</param>
        /// <returns></returns>
        public bool ExcelToShp(string modelName, string excelpath, string xField, string yField, int wkid, string shpPath)
        {
            IVariantArray parameters = new VarArrayClass();

            parameters.Add(excelpath);
            parameters.Add(xField);
            parameters.Add(yField);
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        spatialReference        = spatialReferenceFactory.CreateProjectedCoordinateSystem(wkid);

            parameters.Add(spatialReference);
            parameters.Add(shpPath);
            RunModelTool(System.AppDomain.CurrentDomain.BaseDirectory + "gisModelTool\\Tool\\Toolbox.tbx", System.AppDomain.CurrentDomain.BaseDirectory + "gisModelTool\\Data", parameters, modelName);
            return(true);
        }
Exemplo n.º 18
0
 private static bool IsProjectedSpatialReference(int pcsType)
 {
     try
     {
         var pSrf = new SpatialReferenceEnvironmentClass();
         var mProjectedCoordinateSystem = pSrf.CreateProjectedCoordinateSystem(pcsType);
         // ReSharper disable once UnusedVariable
         var spatialReference = (ISpatialReference)mProjectedCoordinateSystem;
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Exemplo n.º 19
0
        private static ISpatialReference CreateDefaultSpatialReference()
        {
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            var spatialReference = (ISpatialReference)spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_World_PlateCarree);
            var controlPrecision = spatialReference as IControlPrecision2;

            controlPrecision.IsHighPrecision = false;
            var spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;

            spatialReferenceResolution.ConstructFromHorizon();
            var spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;

            spatialReferenceTolerance.SetDefaultXYTolerance();
            return(spatialReference);
        }
Exemplo n.º 20
0
 public static IPoint XY2JWD(double x, double y, int gcsType, int pcsType)
 {
     try
     {
         IPoint point = new PointClass();
         point.PutCoords(x, y);
         ISpatialReferenceFactory factory = new SpatialReferenceEnvironmentClass();
         point.SpatialReference = factory.CreateProjectedCoordinateSystem(pcsType);
         point.Project(factory.CreateGeographicCoordinateSystem(gcsType));
         return(point);
     }
     catch
     {
         return(null);
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// 创建要素集
        /// </summary>
        /// <param name="featureWorkspace"></param>
        /// <param name="featureDataName"></param>
        /// <returns></returns>
        public static IFeatureDataset CreateFeatureDataset(IFeatureWorkspace featureWorkspace, string featureDataName)
        {
            ISpatialReferenceFactory pSpatialReferebceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        pSpatialReference        = pSpatialReferebceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_40);
            IFeatureDataset          featureDataset           = null;

            try
            {
                featureDataset = featureWorkspace.CreateFeatureDataset(featureDataName, pSpatialReference);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("创建要素集{0}失败,错误信息:{1}", featureDataName, ex.Message));
            }
            return(featureDataset);
        }
Exemplo n.º 22
0
        public bool setNameAndGeotype(string className, esriGeometryType geoType, int sr, List <myFieldEdit> jsonFields, List <myFeatures> jsonFeatures)
        {
            this.FeatureClassName = className;
            this.GeometryType     = geoType; //(esriGeometryType)Enum.Parse(typeof(esriGeometryType),geoType);


            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference        spatialReference        =
                spatialReferenceFactory.CreateProjectedCoordinateSystem(sr);

            //添加字段
            IGeometryDefEdit pGeomDef = new GeometryDefClass();

            pGeomDef.GeometryType_2     = this.GeometryType;
            pGeomDef.SpatialReference_2 = spatialReference;
            //new UnknownCoordinateSystemClass();//
            this.Fields = new FieldsClass();

            IFieldEdit pField = new FieldClass();

            pField.Type_2        = esriFieldType.esriFieldTypeGeometry;
            pField.GeometryDef_2 = pGeomDef;
            pField.Name_2        = "Shape ";
            this.Fields.AddField(pField);


            for (int i = 0; i < jsonFields.Count; i++)
            {
                myFieldEdit myField = jsonFields[i];
                AddNewFields(myField, this.Fields);
            }

            string            folderName        = GetFloderName();
            IFeatureWorkspace pFeatureWorkspace = CreateFeatureWorkSpace(folderName);


            IFeatureClass pFeatureClass = CreateFeatureClass(pFeatureWorkspace, this.FeatureClassName, spatialReference,
                                                             esriFeatureType.esriFTSimple,
                                                             this.GeometryType, this.Fields, null, null, "");

            AddFeatures(pFeatureClass, jsonFeatures, jsonFields);

            MessageBox.Show("添加成功");
            return(true);
        }
Exemplo n.º 23
0
        public ILayer CreateTinLayer()
        {
            //定义一个几何字段,类型为多边形类型
            ISpatialReferenceFactory2 originalSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         originalSpatialReference        = originalSpatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_WGS1984UTM_50N);
            IGeometryDefEdit          pGeoDef     = new GeometryDefClass();
            IGeometryDefEdit          pGeoDefEdit = pGeoDef as IGeometryDefEdit;

            pGeoDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolygon;
            pGeoDefEdit.SpatialReference_2 = originalSpatialReference;

            //在featureclass定义的时候应该加上geometryDefEdit.HasZ_2 = true; 不然无法将3d数据强行赋给2d的
            pGeoDefEdit.HasZ_2 = true;

            //定义一个字段集合对象
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;


            //单独处理shape字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldsEdit.AddField(pField);
            pFieldEdit.GeometryDef_2 = pGeoDef;

            ////添加字段
            //addFiled("Id", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("GXID", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("GYID", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("eNodeB", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("CI", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("CellName", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("RecePower", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            //addFiled("PathLoss", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            //addFiled("Level", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("Longitude", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            //addFiled("Latitude", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("point1", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("point2", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("point3", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            return(GetLayer(workspaceDirectory, fileName, pFields));
        }
Exemplo n.º 24
0
        public IPoint ProjectPoint(IPoint inputPoint, CoordinateSystemModel singleProjectionModel)
        {
            if (inputPoint == null)
            {
                return(null);
            }

            //Create Spatial Reference Factory
            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            //Projected Coordinate System to project into
            var projectedCoordinateSystem = spatialReferenceFactory.CreateProjectedCoordinateSystem(singleProjectionModel.ESRIWellKnownID);

            projectedCoordinateSystem.SetFalseOriginAndUnits(singleProjectionModel.FalseOriginX, singleProjectionModel.FalseOriginY, singleProjectionModel.Units);

            inputPoint.Project(projectedCoordinateSystem);

            return(inputPoint);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 复制字段,包括几何字段、非几何字段,并设置新的几何字段的空间参考
        /// </summary>
        /// <param name="featureClass">源要素类</param>
        /// <param name="factoryCode">坐标系代码</param>
        /// <returns></returns>
        public static IFields CloneFeatureClassFields(this IFeatureClass featureClass, int factoryCode)
        {
            IFields         outputFields;
            IFieldChecker   fieldChecker = new FieldCheckerClass();
            IEnumFieldError obj          = null;

            fieldChecker.Validate(featureClass.Fields, out obj, out outputFields);
            IField           shapeField   = outputFields.get_Field(outputFields.FindField(featureClass.ShapeFieldName));
            IGeometryDefEdit sfGeoDefEdit = (IGeometryDefEdit)shapeField.GeometryDef;

            ISpatialReferenceFactory   spatialRefFac = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem pcsSys        = spatialRefFac.CreateProjectedCoordinateSystem(factoryCode);

            sfGeoDefEdit.SpatialReference_2 = pcsSys;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(fieldChecker);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(spatialRefFac);
            return(outputFields);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 计算空间参考
        /// </summary>
        /// <param name="envelope"></param>
        /// <returns></returns>
        private static ISpatialReference ComputeProjectedSpatialReference(IEnvelope envelope)
        {
            if (IsProjectedSpatialReference(envelope))  //判断是否是投影坐标系,若是,则直接返回原坐标系
            {
                return(envelope.SpatialReference);
            }
            double xMax = Math.Round(envelope.XMax, 3);
            double xMin = Math.Round(envelope.XMin, 3);
            double mean = (xMax + xMin) / 2;
            //esriSRProjCS_WGS1984UTM_1N 对应 pcsType:32601 中国UTM投影带计算公式:(经度+180)/6
            //因为浮点转为整型会省略小数点,所以加上32601而不是32600
            const int basedType = 32601;
            int       zone      = basedType + (int)(mean + 180) / 6;
            ISpatialReferenceFactory pfactory     = new SpatialReferenceEnvironmentClass();
            ISpatialReference        proReference = pfactory.CreateProjectedCoordinateSystem(zone);

            return(proReference);
        }
Exemplo n.º 27
0
        private void button5_Click(object sender, EventArgs e)
        {
            IPoint pPoint = new PointClass();

            pPoint.X = 40;
            pPoint.Y = -101;

            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();

            pPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem(4152);

            pPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983HARN));

            GeoToGra(pPoint);

            esriUnits eu = new esriUnits();

            axMapControl.MapUnits = esriUnits.esriMeters;
        }
Exemplo n.º 28
0
        public ILayer CreateCellLayer()
        {
            //定义一个几何字段,类型为多边形类型
            ISpatialReferenceFactory2 originalSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         originalSpatialReference        = originalSpatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_WGS1984UTM_50N);
            IGeometryDefEdit          pGeoDef     = new GeometryDefClass();
            IGeometryDefEdit          pGeoDefEdit = pGeoDef as IGeometryDefEdit;

            pGeoDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolygon;
            pGeoDefEdit.SpatialReference_2 = originalSpatialReference;

            //定义一个字段集合对象
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

            //单独处理shape字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldsEdit.AddField(pField);
            pFieldEdit.GeometryDef_2 = pGeoDef;

            //添加字段
            addFiled("eNodeB", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("CI", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("CellName", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("Longitude", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("Latitude", esriFieldType.esriFieldTypeString, ref pFieldsEdit);
            addFiled("AntHeight", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("Azimuth", esriFieldType.esriFieldTypeInteger, ref pFieldsEdit);
            addFiled("EARFCN", esriFieldType.esriFieldTypeInteger, ref pFieldsEdit);
            addFiled("EIRP", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("Tilt", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("Radius", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);

            return(GetLayer(workspaceDirectory, fileName, pFields));
        }
Exemplo n.º 29
0
        public ILayer CreateDTLayer()
        {
            //定义一个几何字段,类型为多边形类型
            ISpatialReferenceFactory2 originalSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            ISpatialReference         originalSpatialReference        = originalSpatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_WGS1984UTM_50N);
            IGeometryDefEdit          pGeoDef     = new GeometryDefClass();
            IGeometryDefEdit          pGeoDefEdit = pGeoDef as IGeometryDefEdit;

            pGeoDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolygon;
            pGeoDefEdit.SpatialReference_2 = originalSpatialReference;

            //在featureclass定义的时候应该加上geometryDefEdit.HasZ_2 = true; 不然无法将3d数据强行赋给2d的
            pGeoDefEdit.HasZ_2 = true;

            //定义一个字段集合对象
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;


            //单独处理shape字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldsEdit.AddField(pField);
            pFieldEdit.GeometryDef_2 = pGeoDef;

            //添加字段
            addFiled("Id", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("x", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("y", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("RSRP", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("SINR", esriFieldType.esriFieldTypeDouble, ref pFieldsEdit);
            addFiled("Device", esriFieldType.esriFieldTypeString, ref pFieldsEdit);

            return(GetLayer(workspaceDirectory, fileName, pFields));
        }
Exemplo n.º 30
0
        public IFeatureClass CreateFeatureClassWithoutAttribute(string feaClassName, esriGeometryType enumGometryType)
        {
            string featureClassName = feaClassName + "Time" + DateTime.Now.ToString("yyyyMMddHHmmss");
            //Basic field settings of FeatureClass
            IFields     fields     = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();//SpatialReference settings
            ISpatialReference        spatialReference  = spatialrefFactory.CreateProjectedCoordinateSystem(
                (int)(esriSRProjCS4Type.esriSRProjCS_Xian1980_GK_CM_111E));
            IGeometryDef geometryDef = new GeometryDefClass();

            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;//Geometry field settings

            geometryDefEdit.GeometryType_2 = enumGometryType;
            geometryDefEdit.GridCount_2    = 1;
            geometryDefEdit.set_GridSize(0, 0);
            geometryDefEdit.SpatialReference_2 = spatialReference;

            IField     fieldUserDefined = new FieldClass();//Field creation
            IFieldEdit fieldEdit        = (IFieldEdit)fieldUserDefined;

            fieldEdit.Name_2        = "Shape";
            fieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
            fieldEdit.GeometryDef_2 = geometryDef;
            fieldEdit.IsNullable_2  = true;
            fieldEdit.Required_2    = true;

            fieldsEdit.AddField(fieldUserDefined);

            //Create FeatureClass
            UID CLSID = new UIDClass();

            CLSID.Value = "esriGeodatabase.Feature";
            IFeatureClass createdFeatureClass = pFeaWorkspace.CreateFeatureClass(featureClassName, fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", " ");

            return(createdFeatureClass);
        }
        public static void TestThumbnailBuilder(string rasterTypeName, string rasterTypeProductFilter,
            string rasterTypeProductName, string dataSource, string dataSourceFilter, string fgdbParentFolder,
            bool saveToArt, string customTypeFilePath, bool clearGdbDirectory)
        {
            try
            {
                string[] rasterProductNames = rasterTypeProductName.Split(';');
                string nameString = rasterTypeName.Replace(" ", "") + rasterTypeProductFilter.Replace(" ", "") +
                    rasterProductNames[0].Replace(" ", "");

                #region Directory Declarations
                string fgdbName = nameString + ".gdb";
                string fgdbDir = fgdbParentFolder + "\\" + fgdbName;
                string MosaicDatasetName = nameString + "MD";
                #endregion

                #region Global Declarations
                IMosaicDataset theMosaicDataset = null;
                IMosaicDatasetOperation theMosaicDatasetOperation = null;
                IMosaicWorkspaceExtensionHelper mosaicExtHelper = null;
                IMosaicWorkspaceExtension mosaicExt = null;
                #endregion

                #region Create File GDB
                Console.WriteLine("Creating File GDB: " + fgdbName);
                if (clearGdbDirectory)
                {
                    try
                    {
                        Console.WriteLine("Emptying Gdb folder.");
                        System.IO.Directory.Delete(fgdbParentFolder, true);
                        System.IO.Directory.CreateDirectory(fgdbParentFolder);
                    }
                    catch (System.IO.IOException EX)
                    {
                        Console.WriteLine(EX.Message);
                        return;
                    }
                }

                // Create a File Gdb
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                FgdbFactory.Create(fgdbParentFolder,
                    fgdbName, null, 0);
                #endregion

                #region Create Mosaic Dataset
                try
                {
                    Console.WriteLine("Create Mosaic Dataset: " + MosaicDatasetName);
                    // Setup workspaces.
                    IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                    IWorkspace fgdbWorkspace = workspaceFactory.OpenFromFile(fgdbDir, 0);
                    // Create Srs
                    ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                    ISpatialReference mosaicSrs = spatialrefFactory.CreateProjectedCoordinateSystem(
                        (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));
                    // Create the mosaic dataset creation parameters object.
                    ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass();
                    // Create the mosaic workspace extension helper class.
                    mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass();
                    // Find the right extension from the workspace.
                    mosaicExt = mosaicExtHelper.FindExtension(fgdbWorkspace);
                    // Use the extension to create a new mosaic dataset, supplying the 
                    // spatial reference and the creation parameters object created above.
                    theMosaicDataset = mosaicExt.CreateMosaicDataset(MosaicDatasetName,
                        mosaicSrs, creationPars, "");
                    theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset);
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Error: Failed to create Mosaic Dataset : {0}.", 
                        MosaicDatasetName + " " + exc.Message);
                    return;
                }
                #endregion

                #region Create Custom Raster Type
                Console.WriteLine("Preparing Raster Type");
                // Create a Raster Type Name object.
                IRasterTypeName theRasterTypeName = new RasterTypeNameClass();
                // Assign the name of the Raster Type to the name object.
                // The Name field accepts a path to an .art file as well 
                // the name for a built in Raster Type.
                theRasterTypeName.Name = rasterTypeName;
                // Use the Open function from the IName interface to get the Raster Type object.
                IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open());
                if (theRasterType == null)
                {
                    Console.WriteLine("Error:Raster Type not found " + rasterTypeName);
                    return;
                }
                #endregion

                #region Prepare Raster Type
                // Set the URI Filter on the loaded raster type.
                if (rasterTypeProductFilter != "")
                {
                    // Get the supported URI filters from the raster type object using the 
                    // raster type properties interface.
                    IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters;
                    IItemURIFilter productFilter = null;
                    for (int i = 0; i < mySuppFilters.Count; ++i)
                    {
                        // Set the desired filter from the supported filters.
                        productFilter = (IItemURIFilter)mySuppFilters.get_Element(i);
                        if (productFilter.Name == rasterTypeProductFilter)
                            theRasterType.URIFilter = productFilter;
                    }
                }
                // Enable the correct templates in the raster type.
                bool enableTemplate = false;
                if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != ""))
                {
                    // Get the supported item templates from the raster type.
                    IItemTemplateArray templateArray = theRasterType.ItemTemplates;
                    for (int i = 0; i < templateArray.Count; ++i)
                    {
                        // Go through the supported item templates and enable the ones needed.
                        IItemTemplate template = templateArray.get_Element(i);
                        enableTemplate = false;
                        for (int j = 0; j < rasterProductNames.Length; ++j)
                            if (template.Name == rasterProductNames[j])
                                enableTemplate = true;
                        if (enableTemplate)
                            template.Enabled = true;
                        else
                            template.Enabled = false;
                    }
                }
                ((IRasterTypeProperties)theRasterType).DataSourceFilter = dataSourceFilter;
                #endregion

                #region Save Custom Raster Type
                if (saveToArt)
                {
                    IRasterTypeProperties rasterTypeProperties = (IRasterTypeProperties)theRasterType;
                    IRasterTypeEnvironment rasterTypeHelper = new RasterTypeEnvironmentClass();
                    rasterTypeProperties.Name = customTypeFilePath;

                    IMemoryBlobStream ipBlob = rasterTypeHelper.SaveRasterType(theRasterType);
                    ipBlob.SaveToFile(customTypeFilePath);
                }
                #endregion

                #region Preparing Data Source Crawler
                Console.WriteLine("Preparing Data Source Crawler");
                // Create a new property set to specify crawler properties.
                IPropertySet crawlerProps = new PropertySetClass();
                // Specify a file filter
                crawlerProps.SetProperty("Filter", dataSourceFilter);
                // Specify whether to search subdirectories.
                crawlerProps.SetProperty("Recurse", true);
                // Specify the source path.
                crawlerProps.SetProperty("Source", dataSource);
                // Get the recommended crawler from the raster type based on the specified 
                // properties using the IRasterBuilder interface.
                // Pass on the Thumbnailtype to the crawler...
                IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps);
                #endregion

                #region Add Rasters
                try
                {                    
                    Console.WriteLine("Adding Rasters");
                    // Create a AddRaster parameters object.
                    IAddRastersParameters AddRastersArgs = new AddRastersParametersClass();
                    // Specify the data crawler to be used to crawl the data.
                    AddRastersArgs.Crawler = theCrawler;
                    // Specify the Thumbnail raster type to be used to add the data.
                    AddRastersArgs.RasterType = theRasterType;
                    // Use the mosaic dataset operation interface to add 
                    // rasters to the mosaic dataset.
                    theMosaicDatasetOperation.AddRasters(AddRastersArgs, null);
                }
                catch (Exception ex)
                {                    
                    Console.WriteLine("Error: Add raster Failed." + ex.Message);
                    return;
                }
                #endregion

                #region Compute Pixel Size Ranges
                Console.WriteLine("Computing Pixel Size Ranges.");
                try
                {
                    // Create a calculate cellsize ranges parameters object.
                    ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass();
                    // Use the mosaic dataset operation interface to calculate cellsize ranges.
                    theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
                }
                catch (Exception ex)
                {                    
                    Console.WriteLine("Error: Compute Pixel Size Failed." + ex.Message);
                    return;
                }
                #endregion

                #region Building Boundary
                Console.WriteLine("Building Boundary");
                try
                {
                    // Create a build boundary parameters object.
                    IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass();
                    // Set flags that control boundary generation.
                    boundaryArgs.AppendToExistingBoundary = true;
                    // Use the mosaic dataset operation interface to build boundary.
                    theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null);
                }
                catch (Exception ex)
                {                    
                    Console.WriteLine("Error: Build Boundary Failed." + ex.Message);
                    return;
                }
                #endregion

                #region Report
                Console.WriteLine("Successfully created MD: " + MosaicDatasetName + ". ");
                #endregion
            }
            catch (Exception exc)
            {                
                #region Report
                Console.WriteLine("Exception Caught in TestThumbnailBuilder: " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Shutting down.");
                #endregion
            }
        }
Exemplo n.º 32
0
 private ISpatialReference ToSpatialReference(int factoryCode)
 {
     ISpatialReferenceFactory spatialReferenceEnvironmentClass = new SpatialReferenceEnvironmentClass();
     if (this.IsGeographicType(factoryCode))
     {
         return spatialReferenceEnvironmentClass.CreateGeographicCoordinateSystem(factoryCode);
     }
     if (!this.IsProjectedType(factoryCode))
     {
         return null;
     }
     return spatialReferenceEnvironmentClass.CreateProjectedCoordinateSystem(factoryCode);
 }
 public static IPoint JWD2XY(IPoint pJWDPoint, int gcsType, int pcsType)
 {
     try
     {
         ISpatialReferenceFactory factory = new SpatialReferenceEnvironmentClass();
         pJWDPoint.SpatialReference = factory.CreateGeographicCoordinateSystem(gcsType);
         pJWDPoint.Project(factory.CreateProjectedCoordinateSystem(pcsType));
         return pJWDPoint;
     }
     catch
     {
         return null;
     }
 }
Exemplo n.º 34
0
        private void CreatePoint(double x, double y)
        {
            IPoint pPoint = new PointClass();
            IMap pMap = axMapControl.Map;
            IActiveView pActiveView = pMap as IActiveView;
            IGraphicsContainer pGraphicsContainer;
            IElement pElement = new MarkerElementClass();

            pGraphicsContainer = (IGraphicsContainer)pActiveView;
            IFormattedTextSymbol pTextSymbol = new TextSymbolClass();
            IBalloonCallout pBalloonCallout = CreateBalloonCallout(x, y);
            IRgbColor pColor = new RgbColorClass();
            pColor.Red = 150;
            pColor.Green = 0;
            pColor.Blue = 0;
            pTextSymbol.Color = pColor;
            ITextBackground pTextBackground;
            pTextBackground = (ITextBackground)pBalloonCallout;
            //pTextSymbol.Background = pTextBackground;
            //((ITextElement)pElement).Symbol = pTextSymbol;
            //((ITextElement)pElement).Text = "测试";
            pPoint.X = x + 42;
            pPoint.Y = y + 42;

            pPoint.PutCoords(x, y);
            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
            pPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem(2414);
            pPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954));

            pElement.Geometry = pPoint;
            pGraphicsContainer.AddElement(pElement, 1);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }
Exemplo n.º 35
0
        public void CreateXYLayer()
        {
            try
            {
            //IMxDocument pMxDoc;
            //IMap pMap = axMapControl.Map;
            ////IApplication m_app;
            //IApplication m_app = default(IApplication);
            ////IApplication m_app = Application;
            // //IMxApplication m_appsd;

            ////pMxDoc = (IMxDocument)m_app.Document;
            ////pMap = pMxDoc.FocusMap;
            //int i =pMap.MapSurroundCount;

            IApplication m_app = axMapControl.ActiveView.ScreenDisplay as IApplication;
            //IApplication m_app = ESRI.ArcGIS.ArcMap.Application;

            //IApplication m_app = axMapControl.app

            IMxDocument pMxDoc;
            IMap pMap;
            pMxDoc = (IMxDocument)m_app.Document;
            pMap = pMxDoc.FocusMap;

            // Get the table named XYSample.txt
            IStandaloneTableCollection pStTabCol;
            IStandaloneTable pStandaloneTable;
            ITable pTable = null;
            pStTabCol = (IStandaloneTableCollection) pMap;
            for (int intCount = 0; intCount < pStTabCol.StandaloneTableCount; intCount++)
            {
            pStandaloneTable = (IStandaloneTable) pStTabCol.get_StandaloneTable(intCount);
            if (pStandaloneTable.Name == @"c:\XYSample.txt")
            {
            pTable = pStandaloneTable.Table;
            break;
            }
            }
            if (pTable == null)
            {
            MessageBox.Show("The table was not found");
            return;
            }

            // Get the table name object
            IDataset pDataSet;
            IName pTableName;
            pDataSet = (IDataset) pTable;
            pTableName = pDataSet.FullName;

            // Specify the X and Y fields
            IXYEvent2FieldsProperties pXYEvent2FieldsProperties;
            pXYEvent2FieldsProperties = new XYEvent2FieldsPropertiesClass();
            pXYEvent2FieldsProperties.XFieldName = "x";
            pXYEvent2FieldsProperties.YFieldName = "y";
            pXYEvent2FieldsProperties.ZFieldName = "";

            // Specify the projection
            ISpatialReferenceFactory pSpatialReferenceFactory;
            pSpatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem pProjectedCoordinateSystem;
            pProjectedCoordinateSystem = pSpatialReferenceFactory.CreateProjectedCoordinateSystem(26911);
            // esriSRProjCS_NAD1983UTM_11N

            // Create the XY name object and set it's properties
            IXYEventSourceName pXYEventSourceName = new XYEventSourceNameClass();
            IName pXYName;
            IXYEventSource pXYEventSource;
            pXYEventSourceName.EventProperties = pXYEvent2FieldsProperties;
            pXYEventSourceName.SpatialReference = pProjectedCoordinateSystem;
            pXYEventSourceName.EventTableName = pTableName;
            pXYName = (IName) pXYEventSourceName;
            pXYEventSource = (IXYEventSource) pXYName.Open();

            // Create a new Map Layer
            IFeatureLayer pFLayer = new FeatureLayerClass();
            pFLayer.FeatureClass = (IFeatureClass) pXYEventSource;
            pFLayer.Name = "Sample XY Event layer";

            // Add the layer extension (this is done so that when you edit
            // the layer's Source properties and click the Set Data Source
            // button, the Add XY Events Dialog appears)
            ILayerExtensions pLayerExt;
            IFeatureLayerSourcePageExtension pRESPageExt = new XYDataSourcePageExtensionClass();
            pLayerExt = (ILayerExtensions) pFLayer;
            pLayerExt.AddExtension(pRESPageExt);

            pMap.AddLayer(pFLayer);
            }

            catch (System.Exception SysEx)
            {
            MessageBox.Show(SysEx.Message,".NET Error: ",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }
Exemplo n.º 36
0
 private IPoint PRJtoGCS(double x, double y)
 {
     IPoint pPoint = new PointClass();
     pPoint.PutCoords(x, y);
     ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
     pPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem(4269);
     pPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983));
     return pPoint;
 }
Exemplo n.º 37
0
 /// 将经纬度点转换为平面坐标。
 private IPoint GetProject2(double x, double y)
 {
     ISpatialReferenceFactory pfactory = new SpatialReferenceEnvironmentClass();
     IProjectedCoordinateSystem flatref = pfactory.CreateProjectedCoordinateSystem(102003);
     IGeographicCoordinateSystem earthref = pfactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983);
     IPoint pt = new PointClass();
     pt.PutCoords(x, y);
     IGeometry geo = (IGeometry)pt;
     geo.SpatialReference = earthref;
     geo.Project(flatref);
     return pt;
 }
        static void Main(string[] args)
        {
            #region Initialize License
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null;
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
                Console.WriteLine("Ready with license.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
            }
            #endregion

            try
            {
                #region Setup MD Parameters
                MDParameters.gdbParentFolder = @"c:\temp\CreateMD";
                // Choose which type of gdb to create/open.
                // 0 - Create File Gdb
                // 1 - Create Personal Gdb
                // 2 - Open SDE
                int gdbOption = 0;
                // Provide the proper extension based on the gdb you want to create. 
                // e.g. MDParameters.gdbName = "samplePGdb.mdb" to create a personal gdb.
                // To use an SDE, set SDE connection properties below.
                MDParameters.gdbName = @"sampleGdb.gdb";
                MDParameters.mosaicDatasetName = @"sampleMD";

                // Specify the srs of the mosaic dataset
                ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                MDParameters.mosaicDatasetSrs = spatialrefFactory.CreateProjectedCoordinateSystem(
                    (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));

                // 0 and PT_UNKNOWN for bits and bands = use defaults.
                MDParameters.mosaicDatasetBands = 0;
                MDParameters.mosaicDatasetBits = rstPixelType.PT_UNKNOWN;
                MDParameters.configKeyword = "";
                
                // Product Definition key choices:
                // None
                // NATURAL_COLOR_RGB
                // NATURAL_COLOR_RGBI
                // FALSE_COLOR_IRG
                // FORMOSAT-2_4BANDS
                // GEOEYE-1_4BANDS
                // IKONOS_4BANDS
                // KOMPSAT-2_4BANDS
                // LANDSAT_6BANDS
                // LANDSAT_MSS_4BANDS
                // QUICKBIRD_4BANDS
                // RAPIDEYE_5BANDS
                // SPOT-5_4BANDS
                // WORLDVIEW-2_8BANDS

                // Setting this property ensures any data added to the MD with its
                // metadata defined gets added with the correct band combination.
                MDParameters.productDefinitionKey = "FALSE_COLOR_IRG";

                MDParameters.rasterTypeName = "QuickBird";
                // The next two properties can be left blank for defaults
                // The product filter defines which specific product of the raster
                // type to add, e.g. To specfiy Quickbird Basic use value "Basic"
                MDParameters.rasterTypeProductFilter = "";
                // The product name specifies which template to use when adding data.
                // e.g. "Pansharpen and Multispectral" means both multispectral and 
                // pansharpened rasters are added to the mosaic dataset.
                MDParameters.rasterTypeProductName = "Multispectral";

                // Data source from which to read the data.
                MDParameters.dataSource = //@"\\Qalab_server\data\Raster\DOTNET\Input\DatasourcesRaster\FunctionRasterDataset\RasterDataset";
                @"\\qalab_server\data\Raster\DOTNET\Input\DatasourcesRaster\MosaicDataset\QB\Torino";
                //@"\\isdemo1\0_sampledata\SampleData\DataSets\QBBasic1b\Baghdad\X0388";
                MDParameters.dataSourceFilter = @"";
                // No need to set if data source has an srs or if you want to use the MD srs as data source srs.
                MDParameters.dataSourceSrs = null;

                MDParameters.buildOverviews = true;
                #endregion

                MDParameters.emptyFgdbFolder = true;
                MDParameters.createFgdbParentFolder = false;
                #region Empty/Create Output Directory
                if (MDParameters.emptyFgdbFolder)
                {
                    try
                    {
                        Console.WriteLine("Emptying Output Directory");
                        Directory.Delete(MDParameters.gdbParentFolder, true);
                        Directory.CreateDirectory(MDParameters.gdbParentFolder);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (MDParameters.createFgdbParentFolder && !System.IO.Directory.Exists(MDParameters.gdbParentFolder))
                {
                    Console.WriteLine("Creating Output Directory");
                    Directory.CreateDirectory(MDParameters.gdbParentFolder);
                }
                #endregion

                CreateMD createMD = new CreateMD();

                if (gdbOption == 0)
                {
                    #region Create MD in File GDB
                    Console.WriteLine("Creating File GDB: " + MDParameters.gdbName);
                    IWorkspace fgdbWorkspace = CreateFileGdbWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName);
                    createMD.CreateMosaicDataset(fgdbWorkspace);
                    #endregion
                }
                else if (gdbOption == 1)
                {
                    #region Create MD in Personal GDB
                    Console.WriteLine("Creating Personal GDB: " + MDParameters.gdbName);
                    IWorkspace pGdbWorkspace = CreateAccessWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName);
                    createMD.CreateMosaicDataset(pGdbWorkspace);
                    #endregion
                }
                else if (gdbOption == 2)
                {
                    #region Open SDE GDB
                    // Set SDE connection properties.
                    IPropertySet sdeProperties = new PropertySetClass();
                    sdeProperties.SetProperty("SERVER", "barbados");
                    sdeProperties.SetProperty("INSTANCE", "9411");
                    sdeProperties.SetProperty("VERSION", "sde.DEFAULT");
                    sdeProperties.SetProperty("USER", "gdb");
                    sdeProperties.SetProperty("PASSWORD", "gdb");
                    sdeProperties.SetProperty("DATABASE", "VTEST");
                    IWorkspace sdeWorkspace = CreateSdeWorkspace(sdeProperties);
                    if (sdeWorkspace == null)
                    {
                        Console.WriteLine("Could not open SDE workspace: ");
                        return;
                    }

                    #endregion

                    #region Create MD in SDE
                    MDParameters.mosaicDatasetName = @"sampleMD";
                    createMD.CreateMosaicDataset(sdeWorkspace);
                    #endregion
                }

                #region Shutdown
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Report
                Console.WriteLine("Exception Caught in Main: " + exc.Message);
                Console.WriteLine("Shutting down.");
                #endregion

                #region Shutdown
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
        }
Exemplo n.º 39
0
        static void Main(string[] args)
        {
            #region Initialize License
            ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null;
            try
            {
                Console.WriteLine("Obtaining license");
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
                aoInit = new AoInitializeClass();
                esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced);
                Console.WriteLine("Ready with license.");
            }
            catch (Exception exc)
            {
                // If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message);
            }
            #endregion

            try
            {
                #region Setup MD Parameters
                MDParameters.gdbParentFolder = @"e:\MD\CustomRasterType\DMCII";
                // Choose which type of gdb to create/open.
                // 0 - Create File Gdb
                // 1 - Create Personal Gdb
                // 2 - Open SDE
                int gdbOption = 0;
                // Provide the proper extension based on the gdb you want to create.
                // e.g. MDParameters.gdbName = "samplePGdb.mdb" to create a personal gdb.
                // To use an SDE, set SDE connection properties below.
                MDParameters.gdbName           = @"CustomTypeGdb.gdb";
                MDParameters.mosaicDatasetName = @"CustomTypeMD";

                // Specify the srs of the mosaic dataset
                ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                MDParameters.mosaicDatasetSrs = spatialrefFactory.CreateProjectedCoordinateSystem(
                    (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));

                // 0 and PT_UNKNOWN for bits and bands = use defaults.
                MDParameters.mosaicDatasetBands = 0;
                MDParameters.mosaicDatasetBits  = rstPixelType.PT_UNKNOWN;
                MDParameters.configKeyword      = "";

                // Product Definition key choices:
                // None
                // NATURAL_COLOR_RGB
                // NATURAL_COLOR_RGBI
                // FALSE_COLOR_IRG
                // FORMOSAT-2_4BANDS
                // GEOEYE-1_4BANDS
                // IKONOS_4BANDS
                // KOMPSAT-2_4BANDS
                // LANDSAT_6BANDS
                // LANDSAT_MSS_4BANDS
                // QUICKBIRD_4BANDS
                // RAPIDEYE_5BANDS
                // SPOT-5_4BANDS
                // WORLDVIEW-2_8BANDS

                // Setting this property ensures any data added to the MD with its
                // metadata defined gets added with the correct band combination.
                MDParameters.productDefinitionKey = "FALSE_COLOR_IRG";

                MDParameters.rasterTypeName = "DMCIIRasterType";
                // The next two properties can be left blank for defaults
                // The product filter defines which specific product of the raster
                // type to add, e.g. To specfiy Quickbird Basic use value "Basic"
                MDParameters.rasterTypeProductFilter = "";
                // The product name specifies which template to use when adding data.
                // e.g. "Pansharpen and Multispectral" means both multispectral and
                // pansharpened rasters are added to the mosaic dataset.
                MDParameters.rasterTypeProductName = "Raw";

                // Data source from which to read the data.
                MDParameters.dataSource       = @"F:\Data\DMCii";
                MDParameters.dataSourceFilter = @"";
                // No need to set if data source has an srs or if you want to use the MD srs as data source srs.
                MDParameters.dataSourceSrs = null;

                MDParameters.buildOverviews = false;
                #endregion

                MDParameters.emptyGdbFolder        = false;
                MDParameters.createGdbParentFolder = false;
                #region Empty/Create Output Directory
                if (MDParameters.emptyGdbFolder)
                {
                    try
                    {
                        Console.WriteLine("Emptying Output Directory");
                        Directory.Delete(MDParameters.gdbParentFolder, true);
                        Directory.CreateDirectory(MDParameters.gdbParentFolder);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (MDParameters.createGdbParentFolder && !System.IO.Directory.Exists(MDParameters.gdbParentFolder))
                {
                    Console.WriteLine("Creating Output Directory");
                    Directory.CreateDirectory(MDParameters.gdbParentFolder);
                }
                #endregion

                CreateMD createMD = new CreateMD();

                if (gdbOption == 0)
                {
                    #region Create MD in File GDB
                    Console.WriteLine("Creating File GDB: " + MDParameters.gdbName);
                    IWorkspace fgdbWorkspace = CreateFileGdbWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName);
                    createMD.CreateMosaicDataset(fgdbWorkspace);
                    #endregion
                }
                else if (gdbOption == 1)
                {
                    #region Create MD in Personal GDB
                    Console.WriteLine("Creating Personal GDB: " + MDParameters.gdbName);
                    IWorkspace pGdbWorkspace = CreateAccessWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName);
                    createMD.CreateMosaicDataset(pGdbWorkspace);
                    #endregion
                }
                else if (gdbOption == 2)
                {
                    #region Open SDE GDB
                    // Set SDE connection properties.
                    IPropertySet sdeProperties = new PropertySetClass();
                    sdeProperties.SetProperty("SERVER", "barbados");
                    sdeProperties.SetProperty("INSTANCE", "9411");
                    sdeProperties.SetProperty("VERSION", "sde.DEFAULT");
                    sdeProperties.SetProperty("USER", "gdb");
                    sdeProperties.SetProperty("PASSWORD", "gdb");
                    sdeProperties.SetProperty("DATABASE", "VTEST");
                    IWorkspace sdeWorkspace = CreateSdeWorkspace(sdeProperties);
                    if (sdeWorkspace == null)
                    {
                        Console.WriteLine("Could not open SDE workspace: ");
                        return;
                    }

                    #endregion

                    #region Create MD in SDE
                    MDParameters.mosaicDatasetName = @"sampleMD";
                    createMD.CreateMosaicDataset(sdeWorkspace);
                    #endregion
                }

                #region Shutdown
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
            catch (Exception exc)
            {
                #region Report
                Console.WriteLine("Exception Caught in Main: " + exc.Message);
                Console.WriteLine("Shutting down.");
                #endregion

                #region Shutdown
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                // Shutdown License
                aoInit.Shutdown();
                #endregion
            }
        }
Exemplo n.º 40
0
        /// <summary>
        ///     Handles the incoming rest requests
        /// </summary>
        /// <param name="boundVariables"> The bound variables. </param>
        /// <param name="operationInput"> The operation input. </param>
        /// <param name="outputFormat"> The output format. </param>
        /// <param name="requestProperties"> The request properties. </param>
        /// <param name="responseProperties"> The response properties. </param>
        /// <returns> </returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput,
                                     string outputFormat, string requestProperties,
                                     out string responseProperties)
        {
            responseProperties = null;
            var errors = new ErrorContainer(400);
            var wkid   = 26912;

            //pull out all the variables
            var featureClass = operationInput.GetStringValue("featureClass");
            var returnValues = operationInput.GetStringValue("returnValues");
            var predicate    = operationInput.GetStringValue("predicate", nullable: true);
            var geometryJson = operationInput.GetStringValue("geometry", nullable: true);
            var wkidInput    = operationInput.GetNumberValue("wkid", nullable: true);
            var bufferInput  = operationInput.GetNumberValue("buffer", nullable: true);

            if (wkidInput > 0)
            {
                wkid = Convert.ToInt32(wkidInput);
            }

            var isSafeSqlCommand = new IsSafeSqlCommand(new[]
            {
                featureClass, returnValues, predicate
            });

            if (!CommandExecutor.ExecuteCommand(isSafeSqlCommand))
            {
                errors.Add("Input appears to be unsafe. That is all I will tell you.");
            }

            GeometryContainer        container           = null;
            ISpatialReference        newSpatialRefefence = null;
            ISpatialReferenceFactory srFactory           = null;

            //reproject to our data's spatial reference
            if (wkid != 26912)
            {
                srFactory = new SpatialReferenceEnvironmentClass();

                var isProjected = true;
                try
                {
                    newSpatialRefefence = srFactory.CreateProjectedCoordinateSystem(wkid);
                }
                catch (ArgumentException)
                {
                    isProjected = false;
                }

                if (!isProjected)
                {
                    newSpatialRefefence = srFactory.CreateGeographicCoordinateSystem(wkid);
                }
            }

            //input has a geometry - deal with it
            if (!string.IsNullOrEmpty(geometryJson))
            {
                var extractGeometryCommand = new ExtractGeometryCommand(geometryJson, wkid);
                container = CommandExecutor.ExecuteCommand(extractGeometryCommand);

                if (container == null)
                {
                    var message = "Geometry coordinates appear to be invalid.";

                    if (!string.IsNullOrEmpty(extractGeometryCommand.ErrorMessage))
                    {
                        message += " Maybe this information can help: {0}".With(extractGeometryCommand.ErrorMessage);
                    }

                    errors.Add(message);
                }

                //input is in different projection - reproject it
                if (wkid != 26912)
                {
                    if (srFactory == null)
                    {
                        srFactory = new SpatialReferenceEnvironmentClass();
                    }

                    var toUtm = srFactory.CreateProjectedCoordinateSystem(26912);

                    if (container != null)
                    {
                        if ((container.Coordinates == null || container.Coordinates.Count < 1) && container.Geometry != null)
                        {
                            container.Geometry.Project(toUtm);
                        }
                        else
                        {
                            foreach (var points in container.Coordinates)
                            {
                                var point = new PointClass
                                {
                                    X = points[0],
                                    Y = points[1],
                                    SpatialReference = newSpatialRefefence
                                };

                                point.Project(toUtm);

                                if (point.IsEmpty)
                                {
                                    errors.Add("Input geometry is empty. Check your x and y values.");
                                    return(Json(errors));
                                }

                                container.Geometry = point;

                                points[0] = point.X;
                                points[1] = point.Y;
                            }
                        }
                    }
                }

                //buffer point - set container type to polygon
                if (bufferInput > 0 && container != null)
                {
                    container.Geometry = CommandExecutor.ExecuteCommand(new BufferGeometryCommand(container, bufferInput));
                    container.Type     = "POLYGON";
                }
            }

            var sdeConnector = SdeConnectorFactory.Create(featureClass);

            if (sdeConnector == null)
            {
                errors.Add("{0} was not found in our database. ".With(featureClass) +
                           "A valid example would be SGID10.BOUNDARIES.Counties.");
            }

            if (errors.HasErrors)
            {
                return(Json(errors));
            }

// ReSharper disable PossibleNullReferenceException because of returning errors if null
            var workspace = sdeConnector.Connect();

            // ReSharper restore PossibleNullReferenceException


            if (workspace is not IFeatureWorkspace featureWorkspace)
            {
                errors.Add("Error connecting to SDE.");
                return(Json(errors));
            }

            var values = returnValues.Split(',').Select(x => x.Trim()).ToArray();

            var commandToExecute = SpatialCommandFactory.Get(container, featureWorkspace, featureClass, values,
                                                             predicate, newSpatialRefefence);

            var result = CommandExecutor.ExecuteCommand(commandToExecute);

            if (!string.IsNullOrEmpty(commandToExecute.ErrorMessage))
            {
                errors.Add(commandToExecute.ErrorMessage);
                return(Json(errors));
            }

            return(Json(result));
        }
Exemplo n.º 41
0
        private byte[] Extracthandler(NameValueCollection boundVariables,
            JsonObject operationInput,
            string outputFormat,
            string requestProperties,
            out string responseProperties)
        {
            responseProperties = null;
            var errors = new ResponseContainer(HttpStatusCode.BadRequest, "");

            string base64Geometry;
            var found = operationInput.TryGetString("geometry", out base64Geometry);

            if (!found || string.IsNullOrEmpty(base64Geometry))
            {
                errors.Message = "geometry parameter is required.";

                return Json(errors);
            }

            JsonObject queryCriteria;
            found = operationInput.TryGetJsonObject("criteria", out queryCriteria);

            if (!found)
            {
                errors.Message = "criteria parameter is required.";

                return Json(errors);
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "Params received");
            #endif

            IGeometry geometry;
            int read;
            var factory = new GeometryEnvironmentClass() as IGeometryFactory3;
            factory.CreateGeometryFromWkbVariant(Convert.FromBase64String(base64Geometry), out geometry, out read);

            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            if (geometry.SpatialReference == null)
            {
                //Create a projected coordinate system and define its domain, resolution, and x,y tolerance.
                var spatialReferenceResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(3857) as ISpatialReferenceResolution;
                spatialReferenceResolution.ConstructFromHorizon();
                var spatialReferenceTolerance = spatialReferenceResolution as ISpatialReferenceTolerance;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                var spatialReference = spatialReferenceResolution as ISpatialReference;

                geometry.SpatialReference = spatialReference;
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "Geometry converted");
            #endif

            if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon)
            {
                var filterGeometry = (ITopologicalOperator4) geometry;
                filterGeometry.IsKnownSimple_2 = false;

                filterGeometry.Simplify();

                if (((IArea)geometry).Area < 0)
                {
                    ((ICurve)geometry).ReverseOrientation();
                }
            }

            var filter = new SpatialFilter
            {
                Geometry = geometry,
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            var utmResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(26912) as ISpatialReferenceResolution;
            utmResolution.ConstructFromHorizon();
            var utmTolerance = utmResolution as ISpatialReferenceTolerance;
            utmTolerance.SetDefaultXYTolerance();
            var utmSr = utmResolution as ISpatialReference;

            var notEsri = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(queryCriteria.ToJson());
            var searchResults = new Dictionary<string, IList<IntersectAttributes>>();

            foreach (var keyValue in notEsri)
            {
                var container = _featureClassIndexMap.Single(x => x.Index == int.Parse(keyValue.Key));
                var fields = keyValue.Value.Select(x => x.ToUpper());
                var fieldMap = container.FieldMap.Select(x => x.Value)
                    .Where(y => fields.Contains(y.Field.ToUpper()))
                    .ToList();
            #if !DEBUG
                _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Querying {0} at index {1}", container.LayerName, container.Index));
            #endif
                var cursor = container.FeatureClass.Search(filter, true);
                IFeature feature;
                while ((feature = cursor.NextFeature()) != null)
                {
                    var values = new GetValueAtIndexCommand(fieldMap, feature).Execute();
                    var attributes = new IntersectAttributes(values);

                    // line over polygon = 1D
                    // polygon over polygon = 2D

                    switch (geometry.GeometryType)
                    {
                        case esriGeometryType.esriGeometryPolygon:
                        {
            #if !DEBUG
                            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "User input polygon, intersecting " + container.LayerName);
            #endif
                            var gis = (ITopologicalOperator4)geometry;
                            gis.Simplify();

                            if (feature.ShapeCopy.GeometryType == esriGeometryType.esriGeometryPolygon)
                            {
                                try
                                {
                                    var intersection = gis.Intersect(feature.ShapeCopy, esriGeometryDimension.esriGeometry2Dimension);

                                    intersection.Project(utmSr);

                                    var utm = (IArea) intersection;
                                    attributes.Intersect = Math.Abs(utm.Area);
            #if !DEBUG
                                    _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Area: {0}", utm.Area));
            #endif
                                }
                                catch (Exception ex)
                                {
                                    return Json(new ResponseContainer(HttpStatusCode.InternalServerError, ex.Message));
                                }
                            }
                            else if (feature.ShapeCopy.GeometryType == esriGeometryType.esriGeometryPolyline)
                            {
                                var intersection = gis.Intersect(feature.ShapeCopy, esriGeometryDimension.esriGeometry1Dimension);

                                intersection.Project(utmSr);

                                var utm = (IPolyline5) intersection;
                                attributes.Intersect = Math.Abs(utm.Length);
            #if !DEBUG
                                _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Length: {0}", utm.Length));
            #endif
                            }

                        }
                            break;
                        case esriGeometryType.esriGeometryPolyline:
                        {
            #if !DEBUG
                            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, "User input polyline, acting on " + container.LayerName);
            #endif
                            var gis = (ITopologicalOperator5) geometry;
                            gis.Simplify();

                            var intersection = gis.Intersect(feature.ShapeCopy, esriGeometryDimension.esriGeometry1Dimension);

                            intersection.Project(utmSr);

                            var utm = (IPolyline) intersection;
                            attributes.Intersect = Math.Abs(utm.Length);
            #if !DEBUG
                            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Length: {0}", utm.Length));
            #endif
                        }
                            break;
                    }

                    if (searchResults.ContainsKey(container.LayerName))
                    {
                        if (searchResults[container.LayerName].Any(x => new MultiSetComparer<object>().Equals(x.Attributes, attributes.Attributes)))
                        {
                            var duplicate = searchResults[container.LayerName]
                                .Single(x => new MultiSetComparer<object>().Equals(x.Attributes, attributes.Attributes));

                            duplicate.Intersect += attributes.Intersect;
                        }
                        else
                        {
                            searchResults[container.LayerName].Add(attributes);
                        }
                    }
                    else
                    {
                        searchResults[container.LayerName] = new Collection<IntersectAttributes> {attributes};
                    }
                }
            }

            var response = new IntersectResponse(searchResults);

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "Extracthandler", MessageCode, string.Format("Returning results {0}", searchResults.Count));
            #endif

            return Json(new ResponseContainer<IntersectResponse>(response));
        }
Exemplo n.º 42
0
        private byte[] AreasAndLengthsHandler(NameValueCollection boundVariables,
            JsonObject operationInput,
            string outputFormat,
            string requesetProperties,
            out string responseProperties)
        {
            responseProperties = null;
            var errors = new ResponseContainer(HttpStatusCode.BadRequest, "");

            string base64Geometry;
            var found = operationInput.TryGetString("geometry", out base64Geometry);

            if (!found || string.IsNullOrEmpty(base64Geometry))
            {
                errors.Message = "geometry parameter is required.";

                return Json(errors);
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, "Params received");
            #endif

            IGeometry geometry;
            int read;
            var factory = new GeometryEnvironmentClass() as IGeometryFactory3;
            factory.CreateGeometryFromWkbVariant(Convert.FromBase64String(base64Geometry), out geometry, out read);

            var spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            if (geometry.SpatialReference == null)
            {
                //Create a projected coordinate system and define its domain, resolution, and x,y tolerance.
                var spatialReferenceResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(3857) as ISpatialReferenceResolution;
                spatialReferenceResolution.ConstructFromHorizon();
                var spatialReferenceTolerance = spatialReferenceResolution as ISpatialReferenceTolerance;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                var spatialReference = spatialReferenceResolution as ISpatialReference;

                geometry.SpatialReference = spatialReference;
            }

            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, "Geometry converted");
            #endif

            if (geometry.GeometryType == esriGeometryType.esriGeometryPolygon)
            {
                var filterGeometry = (ITopologicalOperator4)geometry;
                filterGeometry.IsKnownSimple_2 = false;

                filterGeometry.Simplify();

                if (((IArea)geometry).Area < 0)
                {
                    ((ICurve)geometry).ReverseOrientation();
                }
            }

            var utmResolution = spatialReferenceFactory.CreateProjectedCoordinateSystem(26912) as ISpatialReferenceResolution;
            utmResolution.ConstructFromHorizon();
            var utmTolerance = utmResolution as ISpatialReferenceTolerance;
            utmTolerance.SetDefaultXYTolerance();
            var utmSr = utmResolution as ISpatialReference;

            geometry.Project(utmSr);

            var size = 0D;
            switch (geometry.GeometryType)
            {
                case esriGeometryType.esriGeometryPolygon:
                    size = ((IArea) geometry).Area;
                    break;
                case esriGeometryType.esriGeometryPolyline:
                    size = ((IPolyline5) geometry).Length;
                    break;
            }
            #if !DEBUG
            _logger.LogMessage(ServerLogger.msgType.infoStandard, "AreasAndLengthsHandler", MessageCode, string.Format("Returning size {0}", size.ToString(CultureInfo.InvariantCulture)));
            #endif
            return Json(new ResponseContainer<SizeResponse>(new SizeResponse(size)));
        }
Exemplo n.º 43
0
        /// <summary>
        ///     Handles the incoming rest requests
        /// </summary>
        /// <param name="boundVariables"> The bound variables. </param>
        /// <param name="operationInput"> The operation input. </param>
        /// <param name="outputFormat"> The output format. </param>
        /// <param name="requestProperties"> The request properties. </param>
        /// <param name="responseProperties"> The response properties. </param>
        /// <returns> </returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput,
                                     string outputFormat, string requestProperties,
                                     out string responseProperties)
        {
            responseProperties = null;
            var errors = new ErrorContainer(400);
            var wkid = 26912;

            //pull out all the variables
            var featureClass = operationInput.GetStringValue("featureClass");
            var returnValues = operationInput.GetStringValue("returnValues");
            var predicate = operationInput.GetStringValue("predicate", nullable: true);
            var geometryJson = operationInput.GetStringValue("geometry", nullable: true);
            var wkidInput = operationInput.GetNumberValue("wkid", nullable: true);
            var bufferInput = operationInput.GetNumberValue("buffer", nullable: true);

            if (wkidInput > 0)
            {
                wkid = Convert.ToInt32(wkidInput);
            }

            var isSafeSqlCommand = new IsSafeSqlCommand(new[]
                {
                    featureClass, returnValues, predicate
                });

            if (!CommandExecutor.ExecuteCommand(isSafeSqlCommand))
            {
                errors.Add("Input appears to be unsafe. That is all I will tell you.");
            }

            GeometryContainer container = null;
            ISpatialReference newSpatialRefefence = null;
            ISpatialReferenceFactory srFactory = null;

            //reproject to our data's spatial reference
            if (wkid != 26912)
            {
                srFactory = new SpatialReferenceEnvironmentClass();

                var isProjected = true;
                try
                {
                    newSpatialRefefence = srFactory.CreateProjectedCoordinateSystem(wkid);
                }
                catch (ArgumentException)
                {
                    isProjected = false;
                }

                if (!isProjected)
                {
                    newSpatialRefefence = srFactory.CreateGeographicCoordinateSystem(wkid);
                }
            }

            //input has a geometry - deal with it
            if (!string.IsNullOrEmpty(geometryJson))
            {
                var extractGeometryCommand = new ExtractGeometryCommand(geometryJson);
                container = CommandExecutor.ExecuteCommand(extractGeometryCommand);

                if (container == null)
                {
                    var message = "Geometry coordinates appear to be invalid.";

                    if (!string.IsNullOrEmpty(extractGeometryCommand.ErrorMessage))
                    {
                        message += " Maybe this information can help: {0}".With(extractGeometryCommand.ErrorMessage);
                    }

                    errors.Add(message);
                }

                //input is in different projection - reproject it
                if (wkid != 26912)
                {
                    if (srFactory == null)
                    {
                        srFactory = new SpatialReferenceEnvironmentClass();
                    }

                    var toUtm = srFactory.CreateProjectedCoordinateSystem(26912);

                    if (container != null)
                    {
                        foreach (var points in container.Coordinates)
                        {
                            var point = new PointClass
                                {
                                    X = points[0],
                                    Y = points[1],
                                    SpatialReference = newSpatialRefefence
                                };

                            point.Project(toUtm);

                            if (point.IsEmpty)
                            {
                                errors.Add("Input geometry is empty. Check your x and y values.");
                                return Json(errors);
                            }

                            container.Geometry = point;

                            points[0] = point.X;
                            points[1] = point.Y;
                        }
                    }
                }

                //buffer point - set container type to polygon
                if (bufferInput > 0 && container != null)
                {
                    container.Geometry = CommandExecutor.ExecuteCommand(new BufferGeometryCommand(container, bufferInput));
                    container.Type = "POLYGON";
                }
            }

            var sdeConnector = SdeConnectorFactory.Create(featureClass);

            if (sdeConnector == null)
            {
                errors.Add("{0} was not found in our database. ".With(featureClass) +
                           "A valid example would be SGID10.BOUNDARIES.Counties.");
            }

            if (errors.HasErrors)
            {
                return Json(errors);
            }

// ReSharper disable PossibleNullReferenceException because of returning errors if null
            var workspace = sdeConnector.Connect();
// ReSharper restore PossibleNullReferenceException

            var featureWorkspace = workspace as IFeatureWorkspace;

            if (featureWorkspace == null)
            {
                errors.Add("Error connecting to SDE.");
                return Json(errors);
            }

            var values = returnValues.Split(',').Select(x => x.Trim()).ToArray();

            var commandToExecute = SpatialCommandFactory.Get(container, featureWorkspace, featureClass, values,
                                                             predicate, newSpatialRefefence);

            var result = CommandExecutor.ExecuteCommand(commandToExecute);

            if (!string.IsNullOrEmpty(commandToExecute.ErrorMessage))
            {
                errors.Add(commandToExecute.ErrorMessage);
                return Json(errors);
            }

            return Json(result);
        }
Exemplo n.º 44
0
 private void menuItem29_Click(object sender, EventArgs e)
 {
     Form form_current = Application.OpenForms["ParentForm"];//form_current为主窗口中的当前活动子窗体
     ChildForm activeMdiChild = (ChildForm)form_current.ActiveMdiChild;//activeMdiChild为childform类的当前活动子窗体
     ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();
     IProjectedCoordinateSystem pcs = srFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_WGS1984S_PoleStereographic);
     activeMdiChild.axMapControl1.SpatialReference = pcs;
     activeMdiChild.axMapControl1.Refresh();
     activeMdiChild.axMapControl2.SpatialReference = pcs;
     activeMdiChild.axMapControl2.Refresh();
 }
Exemplo n.º 45
0
        /// <summary>
        /// 从srid获取投影坐标系统
        /// </summary>
        /// <param name="srid"></param>
        /// <returns></returns>
        public static IProjectedCoordinateSystem getPcsById(int srid)
        {
            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();

            return(spatialReferenceFactory.CreateProjectedCoordinateSystem(SRID));
        }
Exemplo n.º 46
0
 private IPoint GCStoPRJ(IPoint pPoint, int GCSType, int PRJType)
 {
     ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
     pPoint.SpatialReference = pSRF.CreateGeographicCoordinateSystem(GCSType);
     pPoint.Project(pSRF.CreateProjectedCoordinateSystem(PRJType));
     return pPoint;
 }
Exemplo n.º 47
0
        private static double GetProjectedLength(IPolyline line)
        {
            var copy = new ObjectCopyClass();
            var l2 = copy.Copy(line) as IPolyline;

            var factory = new SpatialReferenceEnvironmentClass();
            var fromSR = factory.CreateGeographicCoordinateSystem((int)esriSRGeoCS3Type.esriSRGeoCS_Xian1980);//西安80
            var toSR = factory.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_40);//西安80
            l2.SpatialReference = fromSR;
            l2.Project(toSR);
            return l2.Length;
        }
Exemplo n.º 48
0
 /// <summary>
 /// 坐标系转换-----WGS84转投影坐标系 
 /// </summary>
 /// <param name="point">转换前的IPoint</param>
 /// <returns>转换后的IPoint</returns>
 public static IPoint getProjectPoint(IPoint point)
 {
     try
     {
         ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
         point.SpatialReference = pSRF.CreateGeographicCoordinateSystem((int)(esriSRGeoCSType.esriSRGeoCS_WGS1984));
         point.Project(pSRF.CreateProjectedCoordinateSystem((int)(esriSRProjCSType.esriSRProjCS_WGS1984UTM_31N)));
     }
     catch //(Exception e)
     {
         // MessageBox.Show(e.ToString());
     }
     return point;
 }
		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;
		}
Exemplo n.º 50
0
        /// <summary>
        /// 创建多边形shp
        /// </summary>
        /// <param name="pPolygon"></param>
        /// <param name="shpPath"></param>
        public static void CreatePolygonFeatureClass(IPolygon pPolygon, string shpfolder, string shpname)
        {
            IWorkspaceFactory pWorkSpaceFac = new ShapefileWorkspaceFactoryClass();
            IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit)pWorkSpaceFac;
            IFeatureWorkspace pFeatureWorkSpace = pWorkSpaceFac.OpenFromFile(shpfolder, 0) as IFeatureWorkspace;

            //创建字段集2
            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription;//创建必要字段
            IFields fields = ocDescription.RequiredFields;
            int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName);
            IField field = fields.get_Field(shapeFieldIndex);
            IGeometryDef geometryDef = field.GeometryDef;
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            //geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
            //geometryDefEdit.SpatialReference_2 = spatialReference;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;

            ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass();
            IProjectedCoordinateSystem pcsSys = pSpatialRefFac.CreateProjectedCoordinateSystem((int)esriSRProjCS4Type.esriSRProjCS_Xian1980_3_Degree_GK_Zone_39);
            geometryDefEdit.SpatialReference_2 = pcsSys;

            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null; //将传入字段 转成 validatedFields
            fieldChecker.ValidateWorkspace = (IWorkspace)pFeatureWorkSpace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            field = new FieldClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)fields;
            IFieldEdit pFieldEdit = (IFieldEdit)field;
            pFieldEdit = (IFieldEdit)field;
            pFieldEdit.Name_2 = "面积";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            pFieldsEdit.AddField(field);

            pWorkspaceEdit.StartEditOperation();
            IFeatureClass pFeatureClass = pFeatureWorkSpace.CreateFeatureClass(shpname, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, "");
            pPolygon = new PolygonClass();
            IArea s = pPolygon as IArea;
             double area = s.Area;
            IFeature pfeature = pFeatureClass.CreateFeature();
            pfeature.Shape = pPolygon;
            try
            {
                pfeature.set_Value(pfeature.Fields.FindField("面积"), area.ToString());
                pfeature.Store();
            }
            catch
            {
                MessageBox.Show(area.ToString());
            }
            pWorkspaceEdit.StopEditOperation();
        }
Exemplo n.º 51
0
        private void button5_Click(object sender, EventArgs e)
        {
            IPoint pPoint = new PointClass();
            pPoint.X = 40;
            pPoint.Y = -101;

            ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();

            pPoint.SpatialReference = pSRF.CreateProjectedCoordinateSystem(4152);

            pPoint.Project(pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983HARN));

            GeoToGra(pPoint);

            esriUnits eu = new esriUnits();

            axMapControl.MapUnits = esriUnits.esriMeters;
        }
 public static IPoint XY2JWD(double x, double y, int gcsType, int pcsType)
 {
     try
     {
         IPoint point = new PointClass();
         point.PutCoords(x, y);
         ISpatialReferenceFactory factory = new SpatialReferenceEnvironmentClass();
         point.SpatialReference = factory.CreateProjectedCoordinateSystem(pcsType);
         point.Project(factory.CreateGeographicCoordinateSystem(gcsType));
         return point;
     }
     catch
     {
         return null;
     }
 }
Exemplo n.º 53
0
 private static ISpatialReference CreateDefaultSpatialReference()
 {
     ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
     var spatialReference = (ISpatialReference)spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_World_PlateCarree);
     var controlPrecision = spatialReference as IControlPrecision2;
     controlPrecision.IsHighPrecision = false;
     var spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
     spatialReferenceResolution.ConstructFromHorizon();
     var spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
     spatialReferenceTolerance.SetDefaultXYTolerance();
     return spatialReference;
 }