public Coordinate Reproject(Coordinate coordinate, ISpatialReference @from, ISpatialReference to)
 {
     double[] xy, z;
     ToDotSpatial(coordinate, out xy, out z);
     DotSpatial.Projections.Reproject.ReprojectPoints(xy, z, GetProjectionInfo(@from), GetProjectionInfo(to), 0, 1);
     return ToGeoAPI(xy, z);
 }
 public Envelope Reproject(Envelope envelope, ISpatialReference @from, ISpatialReference to)
 {
     double[] xy;
     ToDotSpatial(envelope, out xy);
     DotSpatial.Projections.Reproject.ReprojectPoints(xy, null, GetProjectionInfo(@from), GetProjectionInfo(to), 0, 4);
     return ToGeoAPI(xy);
 }
 public ICoordinateSequence Reproject(ICoordinateSequence sequence, ISpatialReference @from, ISpatialReference to)
 {
     double[] xy, z, m;
     ToDotSpatial(sequence, out xy, out z, out m);
     DotSpatial.Projections.Reproject.ReprojectPoints(xy, z, GetProjectionInfo(@from), GetProjectionInfo(to), 0, sequence.Count);
     return ToGeoAPI(DefaultSequenceFactory, xy, z, m);
 }
示例#4
0
 public QueryArgs(string featureClass, string[] returnValues, string predicate, ISpatialReference newSpatialRefefence=null)
 {
     FeatureClass = featureClass;
     ReturnValues = returnValues;
     WhereClause = predicate;
     SpatialRefefence = newSpatialRefefence;
 }
示例#5
0
        /// <summary> Class to handle a boundingbox, that make sure it is within Flanderers 
        /// and return string string in the wanted format from arcgis IEnvelope </summary>
        /// <param name="arcgisBbox">arcgis IEnvelope </param>
        public boundingBox(IEnvelope arcgisBbox)
        {
            //handle SRS
            inSRS = arcgisBbox.SpatialReference;

            //Set maxbounds
            Type factoryType = Type.GetTypeFromProgID("esriGeometry.SpatialReferenceEnvironment");
            System.Object obj = Activator.CreateInstance(factoryType);
            ISpatialReferenceFactory3 spatialReferenceFactory = obj as ISpatialReferenceFactory3;

            ISpatialReference lam72 = spatialReferenceFactory.CreateSpatialReference(31370);
            IEnvelope maxBounds = geopuntHelper.makeExtend(17750, 23720, 297240, 245340, lam72); //not outside flanders
            if (inSRS.FactoryCode != lam72.FactoryCode)
            {
                maxBounds = geopuntHelper.Transform(maxBounds as IGeometry, inSRS) as IEnvelope;
            }
            if (arcgisBbox.XMin > maxBounds.XMin) Xmin = arcgisBbox.XMin;
            else Xmin = maxBounds.XMin;
            if (arcgisBbox.YMin > maxBounds.YMin) Ymin = arcgisBbox.YMin;
            else Ymin = maxBounds.YMin;
            if (arcgisBbox.XMax < maxBounds.XMax) Xmax = arcgisBbox.XMax;
            else Xmax = maxBounds.XMax;
            if (arcgisBbox.YMax < maxBounds.YMax) Ymax = arcgisBbox.YMax;
            else Ymax = maxBounds.YMax;
        }
        public NetworkDataset(string configXML, IDataset osmDataset, string ndsName, IGPMessages messages, ITrackCancel trackCancel)
        {
            _xml = new NetworkDatasetXML(configXML, RESMGR);

            _osmDataset = osmDataset;
            _ndsName = ndsName;
            _messages = messages;
            _trackCancel = trackCancel;

            IDataElement deOSM = GPUtil.MakeDataElementFromNameObject(_osmDataset.FullName);
            _dsPath = deOSM.CatalogPath;

            _osmLineName = _osmDataset.Name + "_osm_ln";
            _osmLinePath = _dsPath + "\\" + _osmLineName;
            _osmPointName = _osmDataset.Name + "_osm_pt";
            _osmPointPath = _dsPath + "\\" + _osmPointName;

            // Get the extent from the point feature class
            // NOTE: the feature dataset is not used for this because exceptions occur (SDE only)
            //       if a feature class was recently deleted from the feature dataset.
            IFeatureClass fcPoint = ((IFeatureWorkspace)_osmDataset.Workspace).OpenFeatureClass(_osmPointName);
            IGeoDataset gds = (IGeoDataset)fcPoint;
            _extent = gds.Extent;
            _spatialReference = gds.SpatialReference;
        }
示例#7
0
        static IFeatureClass CreateFeatureClass(IFeatureWorkspace workspace, string name, ISpatialReference outSR)
        {
            IFieldsEdit fields = new FieldsClass();

            IFieldEdit field = new FieldClass();
            field.Type_2 = esriFieldType.esriFieldTypeOID;
            field.Name_2 = "OBJECTID";
            field.AliasName_2 = "OBJECTID";
            fields.AddField(field);

            IGeometryDefEdit geom = new GeometryDefClass();
            geom.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            geom.SpatialReference_2 = outSR;
            geom.HasM_2 = true;
            geom.HasZ_2 = false;

            field = new FieldClass();
            field.Name_2 = "SHAPE";
            field.AliasName_2 = "SHAPE";
            field.Type_2 = esriFieldType.esriFieldTypeGeometry;
            field.GeometryDef_2 = geom;
            fields.AddField(field);

            return workspace.CreateFeatureClass(name, fields, null, null, esriFeatureType.esriFTSimple, "SHAPE", "");
        }
        private static IGeometry BuildGeometry(string s, ISpatialReference spatialReference)
        {
            var wkt = new WktText(s);

            switch (wkt.Type)
            {
                case WktType.None:
                    return null;
                case WktType.Point:
                    return BuildPoint(wkt, spatialReference);
                case WktType.LineString:
                    return BuildPolyline(wkt, spatialReference);
                case WktType.Polygon:
                    return BuildPolygon(wkt, spatialReference);
                case WktType.Triangle:
                    return BuildPolygon(wkt, spatialReference);
                case WktType.PolyhedralSurface:
                    return BuildMultiPatch(wkt, spatialReference);
                case WktType.Tin:
                    return BuildMultiPolygon(wkt, spatialReference);
                case WktType.MultiPoint:
                    return BuildMultiPoint(wkt, spatialReference);
                case WktType.MultiLineString:
                    return BuildMultiPolyline(wkt, spatialReference);
                case WktType.MultiPolygon:
                    return BuildMultiPolygon(wkt, spatialReference);
                case WktType.GeometryCollection:
                    return BuildGeometryCollection(wkt, spatialReference);
                default:
                    throw new ArgumentOutOfRangeException("s", "Unsupported geometry type: " + wkt.Type);
            }
        }
        public static IGeometry ToGeneralGeometry(this ShapeBuffer fgdbGeometry, ISpatialReference spatialReference)
        {
            var geometryType = ShapeBuffer.GetGeometryType(fgdbGeometry.shapeType);

            IGeometry geometry;
            if (geometryType.ToString() == GeometryType.Point.ToString())
            {
                geometry = ToGeneralPoint(fgdbGeometry);
            }
            else if (geometryType.ToString() == GeometryType.Polygon.ToString())
            {
                geometry = ToGeneralMultiPart(fgdbGeometry, GeometryType.Polygon);
            }
            else if (geometryType.ToString() == GeometryType.Polyline.ToString())
            {
                geometry = ToGeneralMultiPart(fgdbGeometry, GeometryType.Polyline);
            }
            else if (geometryType.ToString() == GeometryType.Multipoint.ToString())
            {
                geometry = ToGeneralMultiPoint(fgdbGeometry);
            }
            else
            {
                throw new NotSupportedException(String.Format("The geometry type {0} cannot be read", geometryType));
            }

            geometry.SpatialReference = spatialReference;
            return geometry;
        }
示例#10
0
        public static IFeatureClass CreateFClassInPDB(IWorkspace accessworkspace, string feaDSname, string FCname, esriGeometryType esriGeometryType,ISpatialReference sprf)
        {
            try
            {
                IFeatureDataset featureDataset = ((IFeatureWorkspace)accessworkspace).OpenFeatureDataset(feaDSname);
                //IGeoDataset geoDataset = featureDataset as IGeoDataset;

                IFields pFields = new FieldsClass();
                IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
                IField pField = new FieldClass();
                IFieldEdit pFieldEdit = pField as IFieldEdit;
                pFieldEdit.Name_2 = "SHAPE";
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

                IGeometryDef pGeometryDef = new GeometryDefClass();
                IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
                pGeometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
                pFieldEdit.GeometryDef_2 = pGeometryDef;
                pFieldsEdit.AddField(pField);

                IFeatureClass fc = featureDataset.CreateFeatureClass(FCname, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
                return fc;
            }

            catch (Exception ee)
            {
                MessageBox.Show(ee.Message.ToString());
                return null;
            }
        }
示例#11
0
        private void txtSpatailRef_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            m_SpatailReference = null;
            m_SpatialReferenceString = null;

            dlgSpatialRef.Filter = "空间参考文件(*.Prj)|*.prj";
            if (dlgSpatialRef.ShowDialog(this) == DialogResult.OK)
            {
                //string[] strSpatialRef = System.IO.File.ReadAllLines(dlgSpatialRef.FileName);
                //if (strSpatialRef.Length > 0)
                //    m_SpatialReferenceString = strSpatialRef[0];

                try
                {
                    m_SpatailReference = SpatialReferenctHelper.CreateSpatialReference(dlgSpatialRef.FileName);
                    m_SpatialReferenceString = SpatialReferenctHelper.ToGpString(m_SpatailReference);

                    txtSpatailRef.Text = m_SpatailReference.Name;
                }
                catch
                {
                    XtraMessageBox.Show("非正确的空间参考文件!");
                }
            }
        }
示例#12
0
 public static IField AlterRasterFieldSR(IField pField, ISpatialReference sr)
 {
     IFieldEdit2 pEdit = pField as IFieldEdit2;
     IRasterDef pRDef = pEdit.RasterDef;
     pRDef.SpatialReference = sr;
     return pField;
 }
示例#13
0
 public Projection(ISpatialReference pSpatialReference, IWorkspace pWorkSpace)
 {
     IProjectedCoordinateSystem pProjectedCoordinateSys = pSpatialReference as IProjectedCoordinateSystem;
     m_pSpatialReference = pSpatialReference;
     m_pIProjection = pProjectedCoordinateSys.Projection;
     m_pWorkspace = pWorkSpace;
 }
        protected SpatialReferenceBaseTest(IReprojectorCore core)
        {
            _reprojector = new Reprojector(core);

            _fromSr = _reprojector.Factory.Create("EPSG:4326");
            _toSr = _reprojector.Factory.Create("EPSG:3857");
        }
示例#15
0
        public static ESRI.ArcGIS.Geometry.IEnvelope get_extent(OSGeo.OGR.Envelope ogr_envelope, ISpatialReference sr)
        {
            IEnvelope env = new EnvelopeClass();
            env.PutCoords(ogr_envelope.MinX, ogr_envelope.MinY, ogr_envelope.MaxX, ogr_envelope.MaxY);
            env.SpatialReference = sr;

            return env;
        }
示例#16
0
 public static IGraphic NewRectangle(double left, double top, double right, double bottom, ISpatialReference spatialRefe)
 {
     IMapPoint p1 = Runtime.geometryEngine.newMapPoint(left, top, spatialRefe);
     IMapPoint p2 = Runtime.geometryEngine.newMapPoint(right, top, spatialRefe);
     IMapPoint p3 = Runtime.geometryEngine.newMapPoint(right, bottom, spatialRefe);
     IMapPoint p4 = Runtime.geometryEngine.newMapPoint(left, bottom, spatialRefe);
     return NewQuadrilateral(p1, p2, p3, p4);
 }
示例#17
0
 public static IField AlterGeometryFieldSR(IField pField, ISpatialReference sr)
 {
     IFieldEdit pEdit = pField as IFieldEdit;
     IGeometryDef pGeoDef = pField.GeometryDef;
     IGeometryDefEdit pDEdit = pGeoDef as IGeometryDefEdit;
     pDEdit.SpatialReference_2 = sr;
     pEdit.GeometryDef_2 = pGeoDef;
     return pField;
 }
示例#18
0
        /// <summary>
        /// create feature class of output
        /// </summary>
        /// <param name="workspace">object workspace</param>
        /// <param name="spatialReference">spatial reference of feature class of output</param>
        /// <param name="nameFeatureClass">name of feature class</param>
        /// <returns>object feature class</returns>
        private static IFeatureClass CreateFeatureClassOutput(IWorkspace workspace, ISpatialReference spatialReference, string nameFeatureClass)
        {
            IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription objectClassDescription = (IObjectClassDescription)featureClassDescription;

            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

            // Create the fields collection.
            IFields fields = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            IField oidField = new FieldClass();
            IFieldEdit oidFieldEdit = (IFieldEdit)oidField;
            oidFieldEdit.Name_2 = "OBJECTID";
            oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            fieldsEdit.AddField(oidField);

            // Create the Shape field.
            IField shapeField = new Field();
            IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;

            // Set up the geometry definition for the Shape field.
            IGeometryDef geometryDef = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
            geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;

            // By setting the grid size to 0, you're allowing ArcGIS to determine the appropriate grid sizes for the feature class.
            // If in a personal geodatabase, the grid size will be 1000. If in a file or ArcSDE geodatabase, the grid size
            // will be based on the initial loading or inserting of features.
            geometryDefEdit.HasM_2 = false;
            geometryDefEdit.HasZ_2 = false;

            geometryDefEdit.SpatialReference_2 = spatialReference;

            // Set standard field properties.
            shapeFieldEdit.Name_2 = featureClassDescription.ShapeFieldName;
            shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            shapeFieldEdit.GeometryDef_2 = geometryDef;
            shapeFieldEdit.IsNullable_2 = true;
            shapeFieldEdit.Required_2 = true;
            fieldsEdit.AddField(shapeField);

            IField idField = new FieldClass();
            IFieldEdit idIsolaFieldEdit = (IFieldEdit)idField;
            idIsolaFieldEdit.Name_2 = Program.nameFieldIdOutput;
            idIsolaFieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
            fieldsEdit.AddField(idField);

            // Use IFieldChecker to create a validated fields collection.
            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = workspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            return featureWorkspace.CreateFeatureClass(nameFeatureClass, fields, objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, featureClassDescription.ShapeFieldName, string.Empty);
        }
示例#19
0
        public static string ToDisplayString(ISpatialReference spatialRef)
        {
            if (spatialRef == null)
                return null;

            string strDisplay = "名称:";
            strDisplay += spatialRef.Name;

            return strDisplay;
        }
        public OSMGPExport2OSM()
        {
            resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);

            osmGPFactory = new OSMGPFactory();
            _osmUtility = new OSMUtility();

            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
            m_wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;
        }
        public IFeatureClass CreatePolygonFile(String strFolder, String filename, IEnvelope pEnvBorder, ISpatialReference pSR)
        {
            // Open the folder to contain the shapefile as a workspace
            IWorkspaceFactory pWF = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pfws = (IFeatureWorkspace)pWF.OpenFromFile(strFolder, 0);

            //Set up a simple fields collection
            IField pField = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;
            IFields pFields = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;

            // Make the shape field
            //it will need a geometry definition, with a spatial reference

            pFieldEdit.Name_2 = "Shape";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

            IGeometryDef pGeomDef = new GeometryDef();
            IGeometryDefEdit pGeomDefEdit = (IGeometryDefEdit)pGeomDef;

            pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
            pGeomDefEdit.SpatialReference_2 = pSR;

            pFieldEdit.GeometryDef_2 = pGeomDef;
            pFieldsEdit.AddField(pField);

            // Add ID field
            IField pFieldOID = new Field();
            pFieldEdit = (IFieldEdit)pFieldOID;
            pFieldEdit.Name_2 = "OBJECTID";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            pFieldEdit.IsNullable_2 = false;

            pFieldsEdit.AddField(pFieldOID);

            //EulerPoleReFrmgwn eulerfrm=new EulerPoleReFrmgwn();

            if (File.Exists(strFolder + filename + ".shp") == true)
            {
                DialogResult result = MessageBox.Show("There is a shapefile have the same name in this foler, do you want to overwrite it?", "", MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    File.Delete(strFolder + filename);

                }
                else
                {
                    return null;
                }
            }

            IFeatureClass pFeatclass = pfws.CreateFeatureClass(filename, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
            return pFeatclass;
        }
示例#22
0
        public static string ToPrjString(ISpatialReference spatialRef)
        {
            if (spatialRef == null)
                spatialRef = new UnknownCoordinateSystemClass();

            int strCount = -1;
            string prjString = null;
            (spatialRef as IESRISpatialReferenceGEN).ExportToESRISpatialReference(out prjString, out strCount);

            return prjString;
        }
示例#23
0
        /// <summary>
        /// GP的空间参考只接受字符串
        /// </summary>
        /// <param name="spatialRef"></param>
        /// <returns></returns>
        public static string ToGpString(ISpatialReference spatialRef)
        {
            if (spatialRef == null)
                return null;

            int strCount = -1;
            string gpString = null;
            (spatialRef as IESRISpatialReferenceGEN).ExportToESRISpatialReference(out gpString, out strCount);

            return gpString;
        }
示例#24
0
 public Envelope Reproject(Envelope envelope, ISpatialReference @from, ISpatialReference to)
 {
     var transformation = GetMathTransform(@from, to);
     
     var res = new Envelope(transformation.Transform(new Coordinate(envelope.MinX, envelope.MinY)));
     res.ExpandToInclude(transformation.Transform(new Coordinate(envelope.MinX, envelope.MaxY)));
     res.ExpandToInclude(transformation.Transform(new Coordinate(envelope.MaxX, envelope.MaxY)));
     res.ExpandToInclude(transformation.Transform(new Coordinate(envelope.MaxX, envelope.MinY)));
     
     return res;
 }
示例#25
0
        protected override IFeatureDataset CreateFeatureDataset(IWorkspace wsTarget,ISpatialReference pSpatialRef)
        {
            if (wsTarget == null)
                return null;

            ISpatialReference spatialRef = pSpatialRef;
            if (spatialRef == null)
            {
                if (!string.IsNullOrEmpty(this.ReferenceLayer))
                {
                    IWorkspace wsSource = AEAccessFactory.OpenWorkspace(this.m_DataType, this.m_Datasource);
                    IGeoDataset geoDataset = null;
                    // Shp判断使用Try Catch
                    if (this.m_DataType == enumDataType.SHP)
                    {
                        try
                        {
                            geoDataset = (wsSource as IFeatureWorkspace).OpenFeatureClass(this.ReferenceLayer) as IGeoDataset;
                        }
                        catch
                        {
                        }
                    }
                    else
                    {

                        if ((wsSource as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass, this.ReferenceLayer))
                        {
                            geoDataset = (wsSource as IFeatureWorkspace).OpenFeatureClass(this.ReferenceLayer) as IGeoDataset;
                        }
                        else if ((wsSource as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureDataset, this.ReferenceLayer))
                        {
                            geoDataset = (wsSource as IFeatureWorkspace).OpenFeatureDataset(this.ReferenceLayer) as IGeoDataset;
                        }
                    }

                    if (geoDataset != null)
                    {
                        spatialRef = geoDataset.SpatialReference;
                    }
                    else
                    {
                        SendMessage(enumMessageType.Exception, "NoReferenceDataImport调用错误:数据源中未找到指定的空间参考图层,将按未知参考创建“Dataset”");
                    }
                }
                else
                {
                    SendMessage(enumMessageType.Exception, "NoReferenceDataImport调用错误:未指定空间参考图层,将按未知参考创建“Dataset”");
                }
            }

            return base.CreateFeatureDataset(wsTarget, spatialRef);
        }
示例#26
0
        public catalogForm()
        {
            view = ArcMap.Document.ActiveView;
            map = view.FocusMap;

            wgs = geopuntHelper.wgs84;

            gpExtension = geopunt4arcgisExtension.getGeopuntExtension();

            InitializeComponent();
            initGui();
        }
示例#27
0
        private static IGeometry CreateTurnGeometry(IPoint ptStart, IPoint ptVia, IPoint ptEnd, ISpatialReference sr)
        {
            IPolyline lineTurn = new PolylineClass();
            lineTurn.SpatialReference = sr;

            IPointCollection pcTurn = lineTurn as IPointCollection;
            pcTurn.AddPoint(ptStart);
            pcTurn.AddPoint(ptVia);
            pcTurn.AddPoint(ptEnd);

            return (IGeometry)lineTurn;
        }
示例#28
0
        public static bool IsBCAlbers(ISpatialReference test)
        {
            bool bIsBCAlbers = false;

            if (test != null
                && test is IProjectedCoordinateSystem2
                &&test.Name.ToUpper().IndexOf("ALBERS") >= 0)
            {
                bIsBCAlbers = AreProjectionsSame(test, BCAlbersSpatialReference);
            }

            return bIsBCAlbers;
        }
        private IGeometry GetGeometry(ISpatialReference spatialReference)
        {
            IGeometry geometry;

            IPolyline polyline = new PolylineClass();

            polyline.SpatialReference = spatialReference;

            geometry = polyline as IGeometry;

            MakeZAware(geometry);

            return geometry;
        }
示例#30
0
        //������ţ�RasterCreate-05
        //������:	createRasterDef
        //�������ܣ�����raster����
        //������
        public IRasterDef createRasterDef(bool isManaged, ISpatialReference spatialReference)
        {
            // Create rasterdef
            IRasterDef rasterDef = new RasterDefClass();

            rasterDef.Description = "Raster Dataset";
            if (spatialReference == null)
                spatialReference = new UnknownCoordinateSystemClass();

            rasterDef.SpatialReference = spatialReference;
            rasterDef.IsManaged = isManaged;

            return rasterDef;
        }
示例#31
0
        public void CanGetSegmentIndexMultipartPolyline()
        {
            const double xyTolerance = 0.0125;

            IPolyline polyline = GeometryFactory.CreatePolyline(1000, 2000, 1500, 2500);

            ISpatialReference lv95 = CreateSpatialReference(0.0125, 0.0125);

            polyline.SpatialReference = lv95;

            object missing = Type.Missing;

            ((IPointCollection)polyline).AddPoint(
                GeometryFactory.CreatePoint(2000, 3000), ref missing, ref missing);

            IGeometry secondLine = GeometryFactory.CreatePolyline(5000, 8000, 5500, 8500);

            ((IPointCollection)secondLine).AddPoint(
                GeometryFactory.CreatePoint(6000, 9000), ref missing, ref missing);

            ((IGeometryCollection)polyline).AddGeometryCollection(
                (IGeometryCollection)secondLine);

            GeometryUtils.Simplify(polyline);

            IPoint searchPoint = new PointClass();

            searchPoint.PutCoords(234, 34675);
            int partIndex;

            int?resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.IsNull(resultIndex,
                          "Point is not on geometry but non-null segment index returned.");

            // 1. point, segment from-point
            searchPoint.PutCoords(1000, 2000);
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.IsNotNull(resultIndex, "Point is on geometry but segment index not found.");
            Assert.AreEqual(0, resultIndex);
            Assert.AreEqual(0, partIndex);

            // 1. point, segment to-point (actually incorrect parameter combination)
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, false, true);

            Assert.AreEqual(0, resultIndex);
            Assert.AreEqual(0, partIndex);

            // 2. point, segment from-point
            searchPoint.PutCoords(1500, 2500);
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.AreEqual(1, resultIndex);
            Assert.AreEqual(0, partIndex);

            // 2. point, segment to-point
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, false, true);

            Assert.AreEqual(0, resultIndex);
            Assert.AreEqual(0, partIndex);

            // 3. point, segment from-point (actually incorrect parameter combination)
            searchPoint.PutCoords(2000, 3000);
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.AreEqual(1, resultIndex);
            Assert.AreEqual(0, partIndex);

            // 3. point, segment to-point
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, false, true);

            Assert.AreEqual(1, resultIndex);
            Assert.AreEqual(0, partIndex);

            // 1. point of second, segment from-point
            searchPoint.PutCoords(5000, 8000);
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.AreEqual(0, resultIndex);
            Assert.AreEqual(1, partIndex);

            // 1. point of inner ring, segment to-point (incorrect parameter combination)
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, false, true);

            Assert.AreEqual(0, resultIndex);
            Assert.AreEqual(1, partIndex);

            // 2. point of inner ring, segment from-point
            searchPoint.PutCoords(5500, 8500);
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.AreEqual(1, resultIndex);
            Assert.AreEqual(1, partIndex);

            // 2. point of inner ring, segment to-point
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, false, true);

            Assert.AreEqual(0, resultIndex);
            Assert.AreEqual(1, partIndex);

            // 3. point of inner ring, segment from-point (actually incorrect parameter combination)
            searchPoint.PutCoords(6000, 9000);
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, true, true);

            Assert.AreEqual(1, resultIndex);
            Assert.AreEqual(1, partIndex);

            // 3. point of inner ring, segment to-point
            resultIndex = SegmentReplacementUtils.GetSegmentIndex(
                polyline, searchPoint, xyTolerance, out partIndex, false, true);

            Assert.AreEqual(1, resultIndex);
            Assert.AreEqual(1, partIndex);
        }
示例#32
0
        public static List <IPolyline> ConvertLineToPrimitivePolylines(ProfileSurface profileSurface, ISpatialReference spatialReference)
        {
            var polylines = new List <IPolyline>();

            polylines.AddRange(SeparatePrimitives(profileSurface.ProfileSurfacePoints.Where(point => point.isVertex).ToList(), spatialReference));
            return(polylines);
        }
        private void OnExecute()
        {
            Console.WriteLine(this.FeatureClassName);
            IWorkspaceFactory workspaceFactory = null;
            IWorkspace        workspace        = null;
            IFeatureClass     featureClass     = null;

            switch (DataSourceType)
            {
            case DataSourceType.Sde:
            {
                workspaceFactory = new SdeWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Gdb:
            {
                workspaceFactory = new FileGDBWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Shp:
            {
                workspaceFactory = new ShapefileWorkspaceFactoryClass();
            }
            break;

            default:
                break;
            }
            workspace    = workspaceFactory.OpenFromFile(DataSource, 0);
            featureClass = ((IFeatureWorkspace)workspace).OpenFeatureClass(FeatureClassName);

            IWorkspaceFactory outWorkspaceFactory = null;
            IWorkspace        outWorkspace        = null;
            IFeatureClass     outFeatureClass     = null;

            switch (OutDataSourceType)
            {
            case DataSourceType.Sde:
            {
                outWorkspaceFactory = new SdeWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Gdb:
            {
                outWorkspaceFactory = new FileGDBWorkspaceFactoryClass();
            }
            break;

            case DataSourceType.Shp:
            {
                outWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            }
            break;

            default:
                break;
            }
            outWorkspace    = outWorkspaceFactory.OpenFromFile(OutDataSource, 0);
            outFeatureClass = ((IFeatureWorkspace)outWorkspace).OpenFeatureClass(OutFeatureClassName);

            ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass();
            FileInfo          projectionFile   = new FileInfo(ProJectionFile);
            ISpatialReference spatialReference = spatialReferenceFactory.CreateESRISpatialReferenceFromPRJFile(projectionFile.FullName);


            FileInfo scalesFile = new FileInfo(ScalesFile);

            System.IO.FileStream fs = scalesFile.OpenRead();
            StreamReader         sr = new StreamReader(fs);
            string scalesString     = sr.ReadToEnd();
            var    scales           = scalesString.Split('\r').Where(str => double.TryParse(str, out var d)).Select(str => double.Parse(str)).ToArray();

            sr.Close();

            ;
            try
            {
                _indexOfFieldScale = outFeatureClass.FindField(FieldScale);
            }
            catch (Exception)
            {
            }
            try
            {
                _indexOfFieldFrame = outFeatureClass.FindField(FieldFrame);
            }
            catch (Exception)
            {
            }
            switch (Mode)
            {
            case Mode.Data:
                GenerateAnimationLines(
                    featureClass: featureClass,
                    outFeatureClass: outFeatureClass,
                    spatialReference: Get3857Sr(),
                    frameRate: FrameRate,
                    lineLengthInPixel: LineLength,
                    intervalInPixel: Interval);
                break;

            case Mode.Mxd:
                ModifyMxd(outFeatureClass, scales, spatialReference);
                break;

            default:
                break;
            }
        }
示例#34
0
        static void Main(string[] args)
        {
            //ESRI License Initializer generated code.
            m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced },
                                                         new esriLicenseExtensionCode[] { });

            Dictionary <string, Vertex> nodeDict = new Dictionary <string, Vertex>();
            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(@"C:\Users\hellocomrade\NHDPlusV21_GL_04.gdb", 0);
            IFeatureWorkspace iFtrWs           = workspace as IFeatureWorkspace;

            if (null != iFtrWs)
            {
                IFeatureClass fcLine  = iFtrWs.OpenFeatureClass("NHD_Flowline");
                IFeatureClass fcPoint = iFtrWs.OpenFeatureClass("Hydro_Net_Junctions");
                System.Diagnostics.Debug.Assert(null != fcLine && null != fcPoint);

                var fldLst = new List <string> {
                    "OBJECTID", "FlowDir", "FTYPE", "V0001E_MA", "V0001E_MM", "V0001E_01", "V0001E_02", "V0001E_03", "V0001E_04", "V0001E_05", "V0001E_06", "V0001E_07", "V0001E_08", "V0001E_09", "V0001E_10", "V0001E_11", "V0001E_12"
                };
                Dictionary <string, int> fldDict = new Dictionary <string, int>();
                fldLst.ForEach(fldName => fldDict.Add(fldName, fcLine.FindField(fldName)));

                int lineFtrId = -1;
                //Find field index for oid in Hydro_Net_Junctions feature class
                int    pntFtrIdIdx = fcPoint.FindField("OBJECTID");
                string pntFtrId    = null;

                /*
                 * It has been observed that the most time consuming part of this script is on spatial query.
                 * We could take the same approach we had on Arcpy through fcLine.Search() with a spatial filter.
                 * However, it will make us have the same granularity as using arcpy.
                 * Instead, we took a different route here by using IFeatureIndex and IIndexQuery2
                 */
                IGeoDataset       geoLineDS = (IGeoDataset)fcLine;
                ISpatialReference srLine    = geoLineDS.SpatialReference;
                IFeatureIndex     lineIdx   = new FeatureIndexClass();
                lineIdx.FeatureClass = fcLine;
                lineIdx.Index(null, geoLineDS.Extent);
                IIndexQuery2 queryLineByIdx = lineIdx as IIndexQuery2;

                IFeatureIndex pointIdx = new FeatureIndexClass();
                pointIdx.FeatureClass = fcPoint;
                pointIdx.Index(null, ((IGeoDataset)fcPoint).Extent);
                IIndexQuery2 queryPointByIdx = pointIdx as IIndexQuery2;

                //Get a cursor on Hydro_Net_Junctions as the iterator
                IFeatureCursor pntCur        = fcPoint.Search(null, false);
                IFeature       pnt           = pntCur.NextFeature();
                IFeature       line          = null;
                IFeature       otherPnt      = null;
                List <string>  requiredTypes = new List <string> {
                    "StreamRiver", "ArtificialPath"
                };

                /*
                 * ITopologicalOpeartor is good for two geometries comparing with each other. It doesn't fit
                 * very well for our situation, which check the geometric relationships between a geometry
                 * against a feature class that may have more than 100K geometries.
                 */
                //ITopologicalOperator optor = null;

                /*
                 * It's a shame that we have to reference to a Server API in order to calcuate Geodesic
                 * distances for a polyline with lon/lat as coordinates.
                 *
                 * We could do Haversine ourselves, but we have to believe ESRI could definitely does a
                 * better job there, well, hard to figure out how to get this simple task done in an intutive
                 * way though...
                 */
                IGeometryServer2 geoOperator = new GeometryServerClass();

                IPolyline             polyLine = null;
                List <DownstreamNode> dsLst    = null;
                int[]         lineIds          = null;
                int[]         pntIds           = null;
                object        idobjs;
                object        idobjs1;
                PolylineArray tmpArr   = null;
                IDoubleArray  lengths  = null;
                double        lineLen  = 0.0;
                double        v        = 0.0;
                ILinearUnit   unit     = new LinearUnitClass();
                var           range    = Enumerable.Range(3, 14);
                int           count    = 0;
                int           incoming = 0;
                while (null != pnt)
                {
                    //get ftr id of the current vertex
                    pntFtrId = pnt.get_Value(pntFtrIdIdx).ToString();
                    //optor = pnt.Shape as ITopologicalOperator;

                    /*
                     * This should return feature ids that interects with the given geometry in the feature
                     * class having the index built.
                     */
                    queryLineByIdx.IntersectedFeatures(pnt.Shape, out idobjs);
                    lineIds = idobjs as int[];
                    if (null != lineIds && lineIds.Length > 0)
                    {
                        foreach (int id in lineIds)
                        {
                            line      = fcLine.GetFeature(id);
                            lineFtrId = int.Parse(line.get_Value(fldDict["OBJECTID"]).ToString());
                            if ("1" == line.get_Value(fldDict["FlowDir"]).ToString() && true == requiredTypes.Contains(line.get_Value(fldDict["FTYPE"]).ToString()))
                            {
                                polyLine = line.Shape as IPolyline;
                                if (isSamePoint(polyLine.FromPoint, pnt.Shape as IPoint))
                                {
                                    queryPointByIdx.IntersectedFeatures(line.Shape, out idobjs1);
                                    pntIds = idobjs1 as int[];
                                    if (null != pntIds && 2 == pntIds.Length)
                                    {
                                        foreach (int pid in pntIds)
                                        {
                                            otherPnt = fcPoint.GetFeature(pid);
                                            if (false == isSamePoint(otherPnt.Shape as IPoint, pnt.Shape as IPoint))
                                            {
                                                tmpArr = new PolylineArrayClass();
                                                tmpArr.Add(polyLine);
                                                lengths = geoOperator.GetLengthsGeodesic(srLine, tmpArr as IPolylineArray, unit);
                                                if (0 == lengths.Count)
                                                {
                                                    continue;
                                                }
                                                lineLen = lengths.get_Element(0) * 3.28084;
                                                //var velos = from idx in range select double.Parse(line.get_Value(fldDict[fldLst[idx]]).ToString());
                                                List <double> velos = new List <double>();
                                                foreach (int idx in range)
                                                {
                                                    v = double.Parse(line.get_Value(fldDict[fldLst[idx]]).ToString());
                                                    velos.Add(v == 0 ? 0 : lineLen / v);
                                                }
                                                if (null == dsLst)
                                                {
                                                    dsLst = new List <DownstreamNode>();
                                                }
                                                dsLst.Add(new DownstreamNode(pid, id, velos));
                                            }
                                        }
                                    }
                                }
                                else // pnt at the end of the polyline
                                {
                                    ++incoming;
                                }
                            }
                        }
                    }
                    if (null != dsLst || incoming > 0)
                    {
                        nodeDict.Add(pntFtrId, new Vertex(int.Parse(pntFtrId), incoming, dsLst));
                    }
                    pnt = pntCur.NextFeature();
                    if (++count % 1000 == 0)
                    {
                        Console.WriteLine("Processing Count: " + count);
                    }
                    incoming = 0;
                    dsLst    = null;
                }//end of while(null != pnt)
                ReleaseCOMObj(pntCur);
            }
            ReleaseCOMObj(workspaceFactory);
            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication()
            m_AOLicenseInitializer.ShutdownApplication();
        }
示例#35
0
        public static List <IPolyline> ConvertLineToEsriPolyline(List <ProfileLine> profileLines, ISpatialReference spatialReference)
        {
            return(profileLines.Select(l =>
            {
                var pointFrom = new Point {
                    X = l.PointFrom.X, Y = l.PointFrom.Y, SpatialReference = EsriTools.Wgs84Spatialreference
                };
                var pointTo = new Point {
                    X = l.PointTo.X, Y = l.PointTo.Y, SpatialReference = EsriTools.Wgs84Spatialreference
                };

                pointFrom.Project(spatialReference);
                pointTo.Project(spatialReference);

                return EsriTools.CreatePolylineFromPoints(pointFrom, pointTo);
            }
                                       ).ToList());
        }
示例#36
0
        //创建featureclass
        private IFeatureClass CreateFeatureClass(string name, IWorkspace pWorkspace, UID uidCLSID, UID uidCLSEXT, IGeometry pGeometry)
        {
            try
            {
                if (uidCLSID == null)
                {
                    uidCLSID       = new UIDClass();
                    uidCLSID.Value = "{52353152-891A-11D0-BEC6-00805F7C4268}";
                }

                // 设置 uidCLSEXT (if Null)
                //uidCLSEXT == null;

                IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
                IFields           fields            = new FieldsClass();
                IFieldsEdit       fieldsEdit        = (IFieldsEdit)fields;
                IField            oidField          = new FieldClass();
                IFieldEdit        oidFieldEdit      = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID";
                oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
                fieldsEdit.AddField(oidField);


                IGeometryDef     geometryDef     = new GeometryDefClass();
                IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
                geometryDefEdit.GeometryType_2 = pGeometry.GeometryType;
                ISpatialReferenceFactory    spatialReferenceFactory    = new SpatialReferenceEnvironmentClass();
                ISpatialReference           spatialReference           = pGeometry.SpatialReference;
                ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference;
                spatialReferenceResolution.ConstructFromHorizon();
                ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference;
                spatialReferenceTolerance.SetDefaultXYTolerance();
                geometryDefEdit.SpatialReference_2 = spatialReference;


                IField     geometryField     = new FieldClass();
                IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;
                geometryFieldEdit.Name_2        = "Shape";
                geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
                geometryFieldEdit.GeometryDef_2 = geometryDef;
                fieldsEdit.AddField(geometryField);

                // Use IFieldChecker to create a validated fields collection.
                IFieldChecker   fieldChecker    = new FieldCheckerClass();
                IEnumFieldError enumFieldError  = null;
                IFields         validatedFields = null;
                fieldChecker.ValidateWorkspace = pWorkspace;
                fieldChecker.Validate(fields, out enumFieldError, out validatedFields);
                IFeatureClass targetFeatureclass = null;
                targetFeatureclass = pFeatureWorkspace.CreateFeatureClass("" + name + "", fields, uidCLSID, uidCLSEXT, esriFeatureType.esriFTSimple, "Shape", "");
                return(targetFeatureclass);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Cannot create a low precision dataset in a high precision database.")
                {
                    MessageBox.Show("数据必须是ArcGis9.3的数据,请将数据处理成ArcGis9.2的数据!");
                }
            }
            IFeatureClass featureclass = null;

            return(featureclass);
        }
        private void GenerateAnimationLines(IFeatureClass featureClass, IFeatureClass outFeatureClass, ISpatialReference spatialReference = null, int frameRate = 60, double lineLengthInPixel = 5, double intervalInPixel = 10, string scaleFile = "Scales.txt")
        {
            FileInfo scalesFile = new FileInfo(ScalesFile);

            System.IO.FileStream fs = scalesFile.OpenRead();
            StreamReader         sr = new StreamReader(fs);
            string scalesString     = sr.ReadToEnd();
            var    scales           = scalesString.Split('\r').Where(str => int.TryParse(str, out var d)).Select(str => int.Parse(str)).ToArray();


            if (spatialReference == null)
            {
                spatialReference = Get3857Sr();
            }
            IFeatureCursor cursor  = featureClass.Search(null, false);
            IFeature       feature = null;

            while ((feature = cursor.NextFeature()) != null)
            {
                IGeometry geometry = feature.ShapeCopy;
                geometry.Project(spatialReference);

                foreach (int scale in scales)
                {
                    ProcessPolyline(geometry as IPolyline, outFeatureClass, scale, frameRate, lineLengthInPixel, intervalInPixel, spatialReference);
                }
                ;
            }
        }
示例#38
0
 /// <summary>
 /// Assigns projection to the layer if the layer doesn't have one.
 /// </summary>
 public void AssignProjection(ISpatialReference proj)
 {
     Logger.Current.Warn("VectorLayer: assign projection method isn't supported.");
 }
示例#39
0
        private List <byte> GetBlockUniqueValue(IRasterLayer rasterLyr, IElement element)
        {
            //get top visable raster
            if (rasterLyr == null)
            {
                XtraMessageBox.Show("读取分类结果文件失败!");
                return(null);
            }
            IRaster2 raster2 = rasterLyr.Raster as IRaster2;
            //element.Geometry.Project(rasterProps.SpatialReference);
            //if(element.Geometry.SpatialReference ==null)
            //    element.Geometry.SpatialReference = EnviVars.instance.MapControl.SpatialReference ;
            //element.Geometry.Project(rasterProps.SpatialReference);
            IRasterBandCollection rasterBandCollection = raster2.RasterDataset as IRasterBandCollection;
            IRasterBand           rasterBand           = rasterBandCollection.Item(0);
            IRawPixels            rawPixels            = rasterBand as IRawPixels;

            IPnt         pixelBlockOrigin = new DblPntClass();
            IPnt         pixelBlockSize   = new DblPntClass();
            IPixelBlock3 pixelBlock3      = null;
            //calculate element column and row in raster
            int       startColum, startRow, endColum, endRow = -1;
            IEnvelope envelope = element.Geometry.Envelope;
            //当前空间参考与栅格不一致时,重投影绘制坐标。
            IPoint            upleft        = new PointClass();
            IPoint            lowright      = new PointClass();
            ISpatialReference fromReference = EnviVars.instance.MapControl.Map.SpatialReference;
            ISpatialReference toReference   = (raster2 as IGeoDataset).SpatialReference;

            upleft.X = envelope.XMin;
            upleft.Y = envelope.YMax;
            upleft.SpatialReference = fromReference;
            lowright.X = envelope.XMax;
            lowright.Y = envelope.YMin;
            lowright.SpatialReference = fromReference;
            if (!GFS.Common.EngineAPI.IsEqualSpatialReference(fromReference, toReference))
            {
                upleft.Project(toReference);
                lowright.Project(toReference);
            }
            raster2.MapToPixel(upleft.X, upleft.Y, out startColum, out startRow);
            //raster2.MapToPixel(envelope.XMin, envelope.YMax, out startColum, out startRow);
            if (startColum < 0 && startRow < 0)
            {
                XtraMessageBox.Show("读取起始行列失败!");
                return(null);
            }
            pixelBlockOrigin.SetCoords(startColum, startRow);
            raster2.MapToPixel(lowright.X, lowright.Y, out endColum, out endRow);
            //raster2.MapToPixel(envelope.XMax, envelope.YMin, out endColum, out endRow);
            if (endColum < 0 && endRow < 0)
            {
                XtraMessageBox.Show("读取起始行列失败!");
                return(null);
            }
            pixelBlockSize.SetCoords(endColum - startColum + 1, endRow - startRow + 1);
            pixelBlock3 = rawPixels.CreatePixelBlock(pixelBlockSize) as IPixelBlock3;
            //read pixel
            rawPixels.Read(pixelBlockOrigin, pixelBlock3 as IPixelBlock);
            byte[,] pixelData = (byte[, ])pixelBlock3.get_PixelDataByRef(0);
            //get unique value
            List <byte> uniqueValue = new List <byte>();

            foreach (byte value in pixelData)
            {
                if (!uniqueValue.Contains(value))
                {
                    uniqueValue.Add(value);
                }
            }
            //sort
            uniqueValue.Sort();
            return(uniqueValue);
        }
示例#40
0
 public void SetSpatialReference(ISpatialReference sRef)
 {
 }
        public ClonableObjClass()
        {
            m_ID = Guid.NewGuid();

            m_spatialRef = new UnknownCoordinateSystemClass();
        }
示例#42
0
        async public Task <bool> MapRequest(gView.Framework.Carto.IDisplay display)
        {
            if (_dataset == null)
            {
                return(false);
            }
            if (!_dataset._opened)
            {
                await _dataset.Open();
            }

            IServiceRequestContext context = display.Map as IServiceRequestContext;

            try
            {
                ISpatialReference sRef = (display.SpatialReference != null) ?
                                         display.SpatialReference.Clone() as ISpatialReference :
                                         null;

                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml version='1.0' encoding='utf-8'?>");
                sb.Append("<ARCXML version='1.1'>");
                sb.Append("<REQUEST>");
                sb.Append("<GET_IMAGE>");
                sb.Append("<PROPERTIES>");
                sb.Append("<ENVELOPE minx='" + display.Envelope.minx.ToString() + "' miny='" + display.Envelope.miny.ToString() + "' maxx='" + display.Envelope.maxx.ToString() + "' maxy='" + display.Envelope.maxy.ToString() + "' />");
                sb.Append("<IMAGESIZE width='" + display.iWidth + "' height='" + display.iHeight + "' />");
                sb.Append("<BACKGROUND color='255,255,255' transcolor='255,255,255' />");
                //if (display.SpatialReference != null && !display.SpatialReference.Equals(_sRef))
                //{
                //    string map_param = gView.Framework.Geometry.SpatialReference.ToProj4(display.SpatialReference);
                //    sb.Append("<SPATIALREFERENCE name='" + display.SpatialReference.Name + "' param='" + map_param + "' />");
                //}

                if (sRef != null)
                {
                    string map_param = gView.Framework.Geometry.SpatialReference.ToProj4(display.SpatialReference);
                    sb.Append("<SPATIALREFERENCE name='" + display.SpatialReference.Name + "' param='" + map_param + "' />");

                    string wkt        = gView.Framework.Geometry.SpatialReference.ToESRIWKT(sRef);
                    string geotranwkt = gView.Framework.Geometry.SpatialReference.ToESRIGeotransWKT(sRef);

                    if (wkt != null)
                    {
                        wkt        = wkt.Replace("\"", "&quot;");
                        geotranwkt = geotranwkt.Replace("\"", "&quot;");
                        if (!String.IsNullOrEmpty(geotranwkt))
                        {
                            sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" datumtransformstring=\"" + geotranwkt + "\" />");
                            sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" datumtransformstring=\"" + geotranwkt + "\" />");
                        }
                        else
                        {
                            sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" />");
                            sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" />");
                        }
                    }
                }

                sb.Append("<LAYERLIST>");
                foreach (IWebServiceTheme theme in Themes)
                {
                    sb.Append("<LAYERDEF id='" + theme.LayerID + "' visible='" + (theme.Visible && !theme.Locked).ToString() + "' />");
                }
                sb.Append("</LAYERLIST>");
                sb.Append("</PROPERTIES>");
                sb.Append("</GET_IMAGE>");
                sb.Append("</REQUEST>");
                sb.Append("</ARCXML>");

                string user = ConfigTextStream.ExtractValue(_dataset._connection, "user");
                string pwd  = Identity.HashPassword(ConfigTextStream.ExtractValue(_dataset._connection, "pwd"));

                if ((user == "#" || user == "$") &&
                    context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null)
                {
                    string roles = String.Empty;
                    if (user == "#" && context.ServiceRequest.Identity.UserRoles != null)
                    {
                        foreach (string role in context.ServiceRequest.Identity.UserRoles)
                        {
                            if (String.IsNullOrEmpty(role))
                            {
                                continue;
                            }
                            roles += "|" + role;
                        }
                    }
                    user = context.ServiceRequest.Identity.UserName + roles;
                    // ToDo:
                    //pwd = context.ServiceRequest.Identity.HashedPassword;
                }

#if (DEBUG)
                //Logger.LogDebug("Start gView Mapserver Request");
#endif
                ServerConnection service = new ServerConnection(ConfigTextStream.ExtractValue(_dataset._connection, "server"));
                string           resp    = service.Send(_name, sb.ToString(), "BB294D9C-A184-4129-9555-398AA70284BC", user, pwd);

#if (DEBUG)
                //Logger.LogDebug("gView Mapserver Request Finished");
#endif

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resp);

                IBitmap bitmap = null;
                XmlNode output = doc.SelectSingleNode("//OUTPUT[@file]");
                if (_image != null)
                {
                    _image.Dispose();
                    _image = null;
                }

                try
                {
                    System.IO.FileInfo fi = new System.IO.FileInfo(output.Attributes["file"].Value);
                    if (fi.Exists)
                    {
                        bitmap = Current.Engine.CreateBitmap(fi.FullName);
                    }
                }
                catch { }

                if (bitmap == null)
                {
                    bitmap = WebFunctions.DownloadImage(output);
                }

                if (bitmap != null)
                {
                    _image = new GeorefBitmap(bitmap);
                    _image.SpatialReference = display.SpatialReference;
                    _image.Envelope         = display.Envelope;

                    if (AfterMapRequest != null)
                    {
                        AfterMapRequest(this, display, _image);
                    }
                }

                return(_image != null);
            }
            catch (Exception ex)
            {
                MapServerClass.ErrorLog(context, "MapRequest", ConfigTextStream.ExtractValue(_dataset._connection, "server"), _name, ex);
                return(false);
            }
        }
示例#43
0
        public Task <bool> Open()
        {
            try
            {
                _opened = true;
                _themes.Clear();

                ServerConnection server = new ServerConnection(ConfigTextStream.ExtractValue(_connection, "server"));
                string           axl    = "<ARCXML version=\"1.1\"><REQUEST><GET_SERVICE_INFO fields=\"true\" envelope=\"true\" renderer=\"false\" extensions=\"false\" gv_meta=\"true\" /></REQUEST></ARCXML>";
                axl = server.Send(_name, axl, "BB294D9C-A184-4129-9555-398AA70284BC",
                                  ConfigTextStream.ExtractValue(_connection, "user"),
                                  ConfigTextStream.ExtractValue(_connection, "pwd"));

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(axl);

                if (_class == null)
                {
                    _class = new MapServerClass(this);
                }

                double  dpi    = 96.0;
                XmlNode screen = doc.SelectSingleNode("//ENVIRONMENT/SCREEN");
                if (screen != null)
                {
                    if (screen.Attributes["dpi"] != null)
                    {
                        dpi = Convert.ToDouble(screen.Attributes["dpi"].Value.Replace(".", ","));
                    }
                }
                double dpm = (dpi / 0.0254);

                XmlNode spatialReference = doc.SelectSingleNode("//PROPERTIES/SPATIALREFERENCE");
                if (spatialReference != null)
                {
                    if (spatialReference.Attributes["param"] != null)
                    {
                        SpatialReference sRef = new SpatialReference();
                        gView.Framework.Geometry.SpatialReference.FromProj4(sRef, spatialReference.Attributes["param"].Value);

                        if (spatialReference.Attributes["name"] != null)
                        {
                            sRef.Name = spatialReference.Attributes["name"].Value;
                        }

                        _class.SpatialReference = sRef;
                    }
                }
                else
                {
                    XmlNode FeatureCoordSysNode = doc.SelectSingleNode("ARCXML/RESPONSE/SERVICEINFO/PROPERTIES/FEATURECOORDSYS");
                    if (FeatureCoordSysNode != null)
                    {
                        if (FeatureCoordSysNode.Attributes["id"] != null)
                        {
                            _class.SpatialReference = gView.Framework.Geometry.SpatialReference.FromID("epsg:" + FeatureCoordSysNode.Attributes["id"].Value);
                        }
                        else if (FeatureCoordSysNode.Attributes["string"] != null)
                        {
                            _class.SpatialReference = gView.Framework.Geometry.SpatialReference.FromWKT(FeatureCoordSysNode.Attributes["string"].Value);
                        }

                        // TODO: Geogr. Datum aus "datumtransformid" und "datumtransformstring"
                        //if (_sRef != null && FeatureCoordSysNode.Attributes["datumtransformstring"] != null)
                        //{
                        //}
                    }
                }

                foreach (XmlNode envelopeNode in doc.SelectNodes("//ENVELOPE"))
                {
                    if (_envelope == null)
                    {
                        _envelope = (new Envelope(envelopeNode)).MakeValid();
                    }
                    else
                    {
                        _envelope.Union((new Envelope(envelopeNode)).MakeValid());
                    }
                }
                foreach (XmlNode layerNode in doc.SelectNodes("//LAYERINFO[@id]"))
                {
                    bool visible = true;

                    ISpatialReference sRef = _class.SpatialReference;

                    /*
                     * spatialReference = doc.SelectSingleNode("//PROPERTIES/SPATIALREFERENCE");
                     * if (spatialReference != null)
                     * {
                     *  if (spatialReference.Attributes["param"] != null)
                     *  {
                     *      sRef = new SpatialReference();
                     *      gView.Framework.Geometry.SpatialReference.FromProj4(sRef, spatialReference.Attributes["param"].Value);
                     *
                     *      if (spatialReference.Attributes["name"] != null)
                     *          ((SpatialReference)sRef).Name = spatialReference.Attributes["name"].Value;
                     *  }
                     * }
                     * else
                     * {
                     *  XmlNode FeatureCoordSysNode = doc.SelectSingleNode("ARCXML/RESPONSE/SERVICEINFO/PROPERTIES/FEATURECOORDSYS");
                     *  if (FeatureCoordSysNode != null)
                     *  {
                     *      if (FeatureCoordSysNode.Attributes["id"] != null)
                     *      {
                     *          sRef = gView.Framework.Geometry.SpatialReference.FromID("epsg:" + FeatureCoordSysNode.Attributes["id"].Value);
                     *      }
                     *      else if (FeatureCoordSysNode.Attributes["string"] != null)
                     *      {
                     *          sRef = gView.Framework.Geometry.SpatialReference.FromWKT(FeatureCoordSysNode.Attributes["string"].Value);
                     *      }
                     *
                     *      // TODO: Geogr. Datum aus "datumtransformid" und "datumtransformstring"
                     *      //if (_sRef != null && FeatureCoordSysNode.Attributes["datumtransformstring"] != null)
                     *      //{
                     *      //}
                     *  }
                     * }
                     */

                    if (layerNode.Attributes["visible"] != null)
                    {
                        bool.TryParse(layerNode.Attributes["visible"].Value, out visible);
                    }

                    IClass           themeClass = null;
                    IWebServiceTheme theme      = null;
                    if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "featureclass")
                    {
                        themeClass = new MapThemeFeatureClass(this, layerNode.Attributes["id"].Value);
                        ((MapThemeFeatureClass)themeClass).Name             = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
                        ((MapThemeFeatureClass)themeClass).fieldsFromAXL    = layerNode.InnerXml;
                        ((MapThemeFeatureClass)themeClass).SpatialReference = sRef;

                        XmlNode FCLASS = layerNode.SelectSingleNode("FCLASS[@type]");
                        if (FCLASS != null)
                        {
                            ((MapThemeFeatureClass)themeClass).fClassTypeString = FCLASS.Attributes["type"].Value;
                        }
                        theme = LayerFactory.Create(themeClass, _class) as IWebServiceTheme;
                        if (theme == null)
                        {
                            continue;
                        }
                        theme.Visible = visible;
                    }
                    else if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "image")
                    {
                        if (layerNode.SelectSingleNode("gv_meta/class/implements[@type='gView.Framework.Data.IPointIdentify']") != null)
                        {
                            themeClass = new MapThemeQueryableRasterClass(this, layerNode.Attributes["id"].Value);
                            ((MapThemeQueryableRasterClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
                        }
                        else
                        {
                            themeClass = new MapThemeRasterClass(this, layerNode.Attributes["id"].Value);
                            ((MapThemeRasterClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
                        }
                        theme = new WebServiceTheme(
                            themeClass,
                            themeClass.Name,
                            layerNode.Attributes["id"].Value,
                            visible,
                            _class);
                    }
                    else
                    {
                        continue;
                    }

                    try
                    {
                        if (layerNode.Attributes["minscale"] != null)
                        {
                            theme.MinimumScale = Convert.ToDouble(layerNode.Attributes["minscale"].Value.Replace(".", ",")) * dpm;
                        }
                        if (layerNode.Attributes["maxscale"] != null)
                        {
                            theme.MaximumScale = Convert.ToDouble(layerNode.Attributes["maxscale"].Value.Replace(".", ",")) * dpm;
                        }
                    }
                    catch { }
                    _themes.Add(theme);
                }
                _state = DatasetState.opened;
                return(Task.FromResult(true));
            }
            catch (Exception ex)
            {
                _state = DatasetState.unknown;
                _class = null;
                return(Task.FromResult(false));
            }
        }
        internal virtual void OnFlashPointCommand(object obj)
        {
            ProcessInput(InputCoordinate);
            Mediator.NotifyColleagues(CoordinateConversionLibrary.Constants.RequestOutputUpdate, null);


            IGeometry address = obj as IGeometry;

            if (address == null && amCoordGetter != null && amCoordGetter.Point != null)
            {
                address = amCoordGetter.Point;
            }

            if (address != null)
            {
                // Map und View
                IMxDocument mxdoc      = ArcMap.Application.Document as IMxDocument;
                IActiveView activeView = mxdoc.ActivatedView;
                IMap        map        = mxdoc.FocusMap;
                IEnvelope   envelope   = activeView.Extent;

                //ClearGraphicsContainer(map);

                IScreenDisplay screenDisplay = activeView.ScreenDisplay;
                short          screenCache   = Convert.ToInt16(esriScreenCache.esriNoScreenCache);

                ISpatialReference outgoingCoordSystem = map.SpatialReference;
                address.Project(outgoingCoordSystem);

                // is point within current extent
                // if so, pan to point
                var relationOp = envelope as IRelationalOperator;
                if (relationOp != null && activeView is IMap)
                {
                    if (!relationOp.Contains(address))
                    {
                        // pan to
                        envelope.CenterAt(address as IPoint);
                        activeView.Extent = envelope;
                        activeView.Refresh();
                    }
                }

                IRgbColor color = new RgbColorClass();
                color.Green = 80;
                color.Red   = 22;
                color.Blue  = 68;

                ISimpleMarkerSymbol simpleMarkerSymbol = new SimpleMarkerSymbol();
                simpleMarkerSymbol.Color = color;
                simpleMarkerSymbol.Size  = 15;
                simpleMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSDiamond;

                IElement element = null;

                IMarkerElement markerElement = new MarkerElementClass();

                markerElement.Symbol = simpleMarkerSymbol;
                element = markerElement as IElement;

                IPolygon poly = null;
                if (InputCoordinateType == CoordinateType.MGRS || InputCoordinateType == CoordinateType.USNG)
                {
                    poly = GetMGRSPolygon(address as IPoint);
                }

                if (poly != null)
                {
                    address = poly;
                }
                var av = mxdoc.FocusMap as IActiveView;
                ArcMapHelpers.FlashGeometry(address, color, av.ScreenDisplay, 500, av.Extent);

                //AddElement(map, address);

                // do not center if in layout view
                //if (mxdoc.ActiveView is IMap)
                //{
                //    if (poly != null && !poly.IsEmpty && (poly as IArea) != null)
                //        envelope.CenterAt((poly as IArea).Centroid);
                //    else
                //        envelope.CenterAt(amCoordGetter.Point);

                //    activeView.Extent = envelope;
                //    activeView.Refresh();
                //}
            }
        }
        private void ProcessPolyline(IPolyline polyline, IFeatureClass outFeatureClass, int scale, int frameRate = 60, double lineLengthInPixel = 5, double intervalInPixel = 10, ISpatialReference spatialReference = null)
        {
            if (spatialReference == null)
            {
                spatialReference = Get3857Sr();
            }
            var    pixelLength    = PixelLengthAtScale(polyline.Length, scale, 96);
            double lineLength     = LengthAtScaleOfPixelLength(lineLengthInPixel, scale);
            double intervalLength = LengthAtScaleOfPixelLength(intervalInPixel, scale);

            //too short
            if (pixelLength < intervalInPixel)
            {
            }
            else
            {
                for (int frame = 0; frame < frameRate; frame++)
                {
                    Console.WriteLine($"SCALE:{scale}, FRAME:{frame}");
                    double startLengthOfEachDrawLine = 0 + (((double)frame) / ((double)frameRate)) * intervalLength;
                    while (startLengthOfEachDrawLine < polyline.Length)
                    {
                        var endPointLength = startLengthOfEachDrawLine + lineLength;
                        if (endPointLength >= polyline.Length)
                        {
                            endPointLength = polyline.Length;
                        }
                        polyline.GetSubcurve(startLengthOfEachDrawLine, endPointLength, false, out ICurve curve);
                        IFeature createdFeature = outFeatureClass.CreateFeature();
                        createdFeature.Shape.SpatialReference = spatialReference;
                        createdFeature.Shape = (IPolyline)curve;
                        if (_indexOfFieldFrame >= 0)
                        {
                            try
                            {
                                createdFeature.Value[_indexOfFieldFrame] = frame;
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (_indexOfFieldScale >= 0)
                        {
                            try
                            {
                                createdFeature.Value[_indexOfFieldScale] = scale;
                            }
                            catch (Exception)
                            {
                            }
                        }
                        createdFeature.Store();
                        startLengthOfEachDrawLine += intervalLength;
                    }
                }
            }
            ;
        }
示例#46
0
        /// <summary>
        /// 创建shape图层
        /// </summary>
        /// <param name="strShpPath"></param>
        /// <param name="strFtName"></param>
        /// <returns></returns>
        private IFeatureClass CreateShpFile(string strShpPath, string strFtName, string strAliasFtName, ISpatialReference pSpatial)
        {
            string             connectionstring = "DATABASE=" + strShpPath;
            IWorkspaceFactory2 pFactory         = (IWorkspaceFactory2) new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
            IWorkspace         workspace        = pFactory.OpenFromString(connectionstring, 0);
            IFeatureWorkspace  ipFtWs           = (IFeatureWorkspace)workspace;

            //创建字段IFields
            IFields     pFields     = new FieldsClass();
            IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields;
            ///创建几何类型字段
            IField     pField     = new FieldClass();
            IFieldEdit pFieldEdit = (IFieldEdit)pField;

            ////设置FID字段
            //IFieldEdit ipFldEdit = new FieldClass(); //(__uuidof(Field));
            //ipFldEdit.Name_2 = "FID";
            //ipFldEdit.AliasName_2 = "唯一标志码";
            //ipFldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            //pFieldsEdit.AddField(ipFldEdit);


            pFieldEdit.Name_2      = "Shape";
            pFieldEdit.AliasName_2 = "几何类型";
            pFieldEdit.Type_2      = esriFieldType.esriFieldTypeGeometry;


            IGeometryDef     pGeomDef     = new GeometryDefClass();
            IGeometryDefEdit pGeomDefEdit = (IGeometryDefEdit)pGeomDef;

            pGeomDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPoint;
            pGeomDefEdit.SpatialReference_2 = pSpatial;
            pFieldEdit.GeometryDef_2        = pGeomDef;
            pFieldsEdit.AddField(pField);


            IFeatureClass _featureClass =
                ipFtWs.CreateFeatureClass(strFtName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            //更新图层别名
            //IClassSchemaEdit ipEdit = (IClassSchemaEdit)_featureClass;
            //ipEdit.AlterAliasName(strAliasFtName);

            pFactory  = null;
            workspace = null;
            ipFtWs    = null;

            return(_featureClass);
        }
 public PolygonGeometry(ISpatialReference spatialReference)
 {
     _geometry = GetGeometry(spatialReference);
 }
        /// <summary>
        /// Export graphics to a shapefile
        /// </summary>
        /// <param name="fileNamePath">Path to shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Created featureclass</returns>
        private IFeatureClass ExportToShapefile(string fileNamePath, List <Graphic> graphicsList, ISpatialReference ipSpatialRef, bool polyLineFC)
        {
            int           index           = fileNamePath.LastIndexOf('\\');
            string        folder          = fileNamePath.Substring(0, index);
            string        nameOfShapeFile = fileNamePath.Substring(index + 1);
            string        shapeFieldName  = "Shape";
            IFeatureClass featClass       = null;

            using (ComReleaser oComReleaser = new ComReleaser())
            {
                try
                {
                    IWorkspaceFactory workspaceFactory = null;
                    workspaceFactory = new ShapefileWorkspaceFactoryClass();
                    IWorkspace        workspace        = workspaceFactory.OpenFromFile(folder, 0);
                    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
                    IFields           fields           = null;
                    IFieldsEdit       fieldsEdit       = null;
                    fields     = new Fields();
                    fieldsEdit = (IFieldsEdit)fields;
                    IField     field     = null;
                    IFieldEdit fieldEdit = null;
                    field            = new FieldClass();///###########
                    fieldEdit        = (IFieldEdit)field;
                    fieldEdit.Name_2 = "Shape";
                    fieldEdit.Type_2 = (esriFieldType.esriFieldTypeGeometry);
                    IGeometryDef     geomDef     = null;
                    IGeometryDefEdit geomDefEdit = null;
                    geomDef     = new GeometryDefClass();///#########
                    geomDefEdit = (IGeometryDefEdit)geomDef;

                    if (polyLineFC)
                    {
                        geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                    }
                    else
                    {
                        geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                    }

                    geomDefEdit.SpatialReference_2 = ipSpatialRef;

                    fieldEdit.GeometryDef_2 = geomDef;
                    fieldsEdit.AddField(field);

                    featClass = featureWorkspace.CreateFeatureClass(nameOfShapeFile, fields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, "");

                    foreach (Graphic graphic in graphicsList)
                    {
                        IFeature feature = featClass.CreateFeature();

                        if (polyLineFC)
                        {
                            feature.Shape = graphic.Geometry;
                        }
                        else
                        {
                            feature.Shape = PolylineToPolygon(graphic.Geometry);
                        }

                        feature.Store();
                    }

                    IFeatureLayer featurelayer = null;
                    featurelayer = new FeatureLayerClass();
                    featurelayer.FeatureClass = featClass;
                    featurelayer.Name         = featClass.AliasName;

                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace);
                    workspace = null;
                    GC.Collect();

                    return(featClass);
                }
                catch (Exception ex)
                {
                    return(featClass);
                }
            }
        }
示例#49
0
        /// <summary>
        /// 向字段集添加或修改ObjectID和拥有指定几何类型与坐标系Shape字段,若字段存在且符合要求则不添加或修改
        /// (ObjectID会在不同数据源中自动转换为OID/FID/OJBECTID)
        /// </summary>
        /// <param name="fields">字段集</param>
        /// <param name="geometryType">需要添加的Shape字段存储的几何类型</param>
        /// <param name="spatialRef">需要添加的Shape字段存储的坐标系</param>
        /// <returns></returns>
        public static IFields AddBaseFields(this IFields fields, esriGeometryType geometryType, ISpatialReference spatialRef)
        {
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
            var         oidField   = fields.GetFirstFieldsByType(esriFieldType.esriFieldTypeOID);

            if (oidField == null)
            {
                fieldsEdit.AddField(CreateOidField());
            }

            var shapeField = fields.GetFirstFieldsByType(esriFieldType.esriFieldTypeGeometry);

            if (shapeField == null)
            {
                fieldsEdit.AddField(CreateShapeField(geometryType, spatialRef));
            }
            else if (shapeField.GeometryDef.GeometryType != geometryType ||
                     shapeField.GeometryDef.SpatialReference != spatialRef)
            {
                IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;
                shapeFieldEdit.GeometryDef_2 = CreateGeometryDef(geometryType, spatialRef);
            }

            return(fields);
        }
示例#50
0
        public static List <GroupedLines> GetSegmentsFromProfileLine(ProfileSurface[] profileSurfaces, ISpatialReference spatialReference)
        {
            var polylines = new List <IPolyline>();

            foreach (var surface in profileSurfaces)
            {
                polylines.AddRange(ConvertLineToPrimitivePolylines(surface, spatialReference));
            }
            var lines = new GroupedLines()
            {
                Polylines   = polylines,
                Lines       = ConvertEsriPolylineToLine(polylines),
                LineId      = 1,
                IsPrimitive = true
            };

            lines.Vertices = lines.Lines.Select(line => line.PointFrom).ToList();

            return(new List <GroupedLines>()
            {
                lines
            });
        }
示例#51
0
        public int SearchClosestFeatureInCollection(Collection pFeatureCollection, IMap pMap, IGeometry pPosGeometry)
        {
            try
            {
                if (pFeatureCollection != null)
                {
                    if (pMap == null)
                    {
                        return(-1);
                    }
                    if (pPosGeometry == null)
                    {
                        return(-1);
                    }
                    if (pFeatureCollection.Count <= 0)
                    {
                        return(-1);
                    }
                    IActiveView pActiveView = null;
                    pActiveView = pMap as IActiveView;
                    ISpatialReference pProject = null;
                    pProject = pMap.SpatialReference;
                    double num = 0.0;
                    num = GISFunFactory.UnitFun.ConvertPixelsToMapUnits(pActiveView, 6.0, true);
                    double num2 = 0.0;
                    num2 = GISFunFactory.UnitFun.ConvertPixelsToMapUnits(pActiveView, 4.0, true);
                    double num3 = 0.0;
                    num3 = GISFunFactory.UnitFun.ConvertPixelsToMapUnits(pActiveView, 3.0, true);
                    int num4 = -1;
                    int num5 = -1;
                    int num6 = -1;
                    IProximityOperator @operator = null;
                    @operator = pPosGeometry as IProximityOperator;
                    IFeature  feature = null;
                    IGeometry other   = null;
                    double    num7    = 0.0;
                    long      num8    = 0L;
                    for (num8 = 1L; num8 <= pFeatureCollection.Count; num8 += 1L)
                    {
                        feature = pFeatureCollection[num8] as IFeature;
                        other   = GISFunFactory.GeometryFun.ConvertGeometrySpatialReference(feature.Shape, null, pProject);
                        num7    = @operator.ReturnDistance(other);
                        switch (other.GeometryType)
                        {
                        case esriGeometryType.esriGeometryPoint:
                            if (num < 0.0)
                            {
                                num = num7 + 1.0;
                            }
                            if (num7 < num)
                            {
                                num  = num7;
                                num4 = (int)num8;
                            }
                            break;

                        case esriGeometryType.esriGeometryPolyline:
                            if (num2 < 0.0)
                            {
                                num2 = num7 + 1.0;
                            }
                            if (num7 < num2)
                            {
                                num2 = num7;
                                num5 = (int)num8;
                            }
                            break;

                        case esriGeometryType.esriGeometryPolygon:
                            if (num3 < 0.0)
                            {
                                num3 = num7 + 1.0;
                            }
                            if (num7 < num3)
                            {
                                num3 = num7;
                                num6 = (int)num8;
                            }
                            break;

                        case esriGeometryType.esriGeometryLine:
                            if (num2 < 0.0)
                            {
                                num2 = num7 + 1.0;
                            }
                            if (num7 < num2)
                            {
                                num2 = num7;
                                num5 = (int)num8;
                            }
                            break;
                        }
                    }
                    if (num4 > 0)
                    {
                        return(num4);
                    }
                    if (num5 > 0)
                    {
                        return(num5);
                    }
                    if (num6 > 0)
                    {
                        return(num6);
                    }
                }
                return(-1);
            }
            catch (Exception exception)
            {
                this.mErrOpt.ErrorOperate(this.mSubSysName, "FunFactory.FeatureFun", "SearchClosestFeatureInCollection", exception.GetHashCode().ToString(), exception.Source, exception.Message, "", "", "");
                return(-1);
            }
        }
示例#52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FootprintProvider"/> class.
 /// </summary>
 /// <param name="alternateSpatialReference">
 /// An optional alternate spatial reference to get the multipatch in
 /// (must have the same coordinate system; resolution/tolerance may be different).</param>
 protected FootprintProvider(
     [CanBeNull] ISpatialReference alternateSpatialReference)
 {
     _alternateSpatialReference = alternateSpatialReference;
 }
示例#53
0
 public int CreateDataset(string name, ISpatialReference sRef)
 {
     return(Create(name) ? 0 : -1);
 }
示例#54
0
        /// <summary>
        /// 复制字段,按照指定的字段名列表复制featureClass中的字段
        /// </summary>
        /// <param name="featureClass">源要素类</param>
        /// <param name="spatialRef">空间坐标系</param>
        /// <param name="fieldNames">指定的字段名列表,若指定的字段在源要素类中找不到,则跳过该字段</param>
        /// <returns></returns>
        public static IFields CloneFeatureClassFields(this IFeatureClass featureClass, ISpatialReference spatialRef, IEnumerable <string> fieldNames)
        {
            IFields     fields     = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            //设置坐标系
            IGeometryDef     geometryDef     = new GeometryDefClass();
            IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;

            geometryDefEdit.GeometryType_2     = esriGeometryType.esriGeometryPolygon;
            geometryDefEdit.SpatialReference_2 = spatialRef;

            //添加Shape字段
            IField     geometryField     = new FieldClass();
            IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField;

            geometryFieldEdit.Name_2        = featureClass.ShapeFieldName;
            geometryFieldEdit.Type_2        = esriFieldType.esriFieldTypeGeometry;
            geometryFieldEdit.GeometryDef_2 = geometryDef;
            fieldsEdit.AddField(geometryField);

            for (int i = 0; i < fieldNames.Count(); i++)
            {
                int index = featureClass.Fields.FindField(fieldNames.ElementAt(i));
                if (index == -1)
                {
                    continue;
                }
                IField     fieldSource = featureClass.Fields.get_Field(index);
                IField     field       = new FieldClass();
                IFieldEdit fieldEdit   = (IFieldEdit)field;
                fieldEdit.Name_2         = fieldSource.Name;
                fieldEdit.AliasName_2    = fieldSource.AliasName;
                fieldEdit.DefaultValue_2 = fieldSource.DefaultValue;
                fieldEdit.Type_2         = fieldSource.Type;
                fieldEdit.Length_2       = fieldSource.Length;
                fieldsEdit.AddField(field);
            }
            return(fields);
        }
 public PointGeometry(double longitude, double latitude, double altitudeInKilometers, ISpatialReference spatialReference)
 {
     _geometry = GetGeometry(longitude, latitude, altitudeInKilometers, spatialReference);
 }
示例#56
0
        private bool InsertTopoError(IFeatureClass destFClass)
        {
            try
            {
                string strSQL = @"SELECT
                            b.CheckType,
                            IIF(b.TargetFeatClass1 is Null,'',b.TargetFeatClass1) as YSTC,
                            IIF(a.SourceBSM is Null,'',a.SourceBSM) as SourceBSM,
                            IIF(a.MBTC is Null,'',a.MBTC) as MBTC,
                            IIF(a.TargetBSM is Null,'',a.TargetBSM) as BSM2,
                            a.TPTC as TopoLayerName,
                            a.Reason as Description,
                            a.IsException as IsException,
                            IIf(a.Remark is Null,'',a.Remark) as Remark,
                            b.GZBM ,
                            a.ArcGisRule as ArcGisRule,
                            a.JHLX as JHLX,
                            a.SourceLayerID,
                            a.TargetLayerID,
                            a.SourceOID as OID,
                            a.TargetOID as OID2
                            from LR_ResAutoTopo as a, LR_ResultEntryRule as b where a.RuleInstID=b.RuleInstID
                            ";


                DataTable dtError = Hy.Common.Utility.Data.AdoDbHelper.GetDataTable(this.ResultConnection, strSQL);

                IFeatureCursor        fCusorInsert   = destFClass.Insert(false);
                Dictionary <int, int> dictFieldIndex = new Dictionary <int, int>();
                for (int i = 0; i < m_FieldCaptions.Count; i++)
                {
                    dictFieldIndex.Add(i, destFClass.FindField(m_FieldCaptions[i]));
                }
                int xFieldIndex = destFClass.FindField("X坐标");
                int yFieldIndex = destFClass.FindField("Y坐标");

                IErrorFeatureContainer errFeatureContainer = this.Topology as IErrorFeatureContainer;
                ISpatialReference      spatialRef          = (this.Topology as IGeoDataset).SpatialReference;
                for (int i = 0; i < dtError.Rows.Count; i++)
                {
                    DataRow              rowError  = dtError.Rows[i];
                    int                  fClassID  = Convert.ToInt32(rowError["SourceLayerID"]);
                    int                  fClassID2 = Convert.ToInt32(rowError["TargetLayerID"]);
                    int                  oid       = Convert.ToInt32(rowError["OID"]);
                    int                  oid2      = Convert.ToInt32(rowError["OID2"]);
                    esriGeometryType     geoType   = (esriGeometryType)Convert.ToInt32(rowError["JHLX"]);
                    esriTopologyRuleType ruleType  = (esriTopologyRuleType)Convert.ToInt32(rowError["ArcGISRule"]);

                    IFeature srcFeature = errFeatureContainer.get_ErrorFeature(spatialRef, ruleType, geoType, fClassID, fClassID2, oid, oid2) as IFeature;

                    IFeatureBuffer fNew = destFClass.CreateFeatureBuffer();
                    for (int j = 0; j < m_FieldCaptions.Count; j++)
                    {
                        int fIndex = dictFieldIndex[j];
                        if (fIndex < 0)
                        {
                            continue;
                        }

                        fNew.set_Value(fIndex, rowError[j]);
                    }
                    fNew.Shape = GetErrorGeometry(srcFeature);
                    IPoint point = fNew.Shape as IPoint;
                    fNew.set_Value(xFieldIndex, point.X);
                    fNew.set_Value(yFieldIndex, point.Y);

                    fCusorInsert.InsertFeature(fNew);

                    if (i % 2000 == 0)
                    {
                        fCusorInsert.Flush();
                    }
                }

                fCusorInsert.Flush();

                return(true);
            }
            catch (Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());
                return(false);
            }
        }
        private IGeometry GetGeometry(double longitude, double latitude, double altitudeInKilometers, ISpatialReference spatialReference)
        {
            IGeometry geometry;

            IPoint point = new PointClass();

            point.X = longitude;
            point.Y = latitude;
            point.Z = altitudeInKilometers;

            point.SpatialReference = spatialReference;

            geometry = point as IGeometry;

            MakeZAware(geometry);

            return(geometry);
        }
        /// <summary>
        /// Creates the output featureclass, either fgdb featureclass or a shapefile
        /// </summary>
        /// <param name="outputPath">location of featureclass</param>
        /// <param name="saveAsType">Type of output selected, either fgdb featureclass or shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Output featureclass</returns>
        public IFeatureClass CreateFCOutput(string outputPath, SaveAsType saveAsType, List <Graphic> graphicsList, ISpatialReference ipSpatialRef)
        {
            string        fcName     = System.IO.Path.GetFileName(outputPath);
            string        folderName = System.IO.Path.GetDirectoryName(outputPath);
            IFeatureClass fc         = null;

            try
            {
                bool isGraphicLineOrRangeRing = graphicsList[0].GraphicType == GraphicTypes.Line || graphicsList[0].GraphicType == GraphicTypes.RangeRing;
                if (saveAsType == SaveAsType.FileGDB)
                {
                    IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactory();
                    IWorkspace        workspace        = workspaceFactory.OpenFromFile(folderName, 0);
                    IFeatureWorkspace fWorkspace       = (IFeatureWorkspace)workspace;

                    if (DoesFeatureClassExist(folderName, fcName))
                    {
                        DeleteFeatureClass(fWorkspace, fcName);
                    }

                    fc = CreateFeatureClass(fWorkspace, fcName, isGraphicLineOrRangeRing);

                    foreach (Graphic graphic in graphicsList)
                    {
                        IFeature feature = fc.CreateFeature();

                        if (graphic.GraphicType != GraphicTypes.Line && graphic.GraphicType != GraphicTypes.RangeRing)
                        {
                            feature.Shape = PolylineToPolygon(graphic.Geometry);
                        }
                        else
                        {
                            feature.Shape = graphic.Geometry;
                        }

                        feature.Store();
                    }
                }
                else if (saveAsType == SaveAsType.Shapefile)
                {
                    // already asked them for confirmation to overwrite file
                    if (File.Exists(outputPath))
                    {
                        DeleteShapeFile(outputPath);
                    }

                    fc = ExportToShapefile(outputPath, graphicsList, ipSpatialRef, isGraphicLineOrRangeRing);
                }
                return(fc);
            }
            catch (Exception ex)
            {
                return(fc);
            }
        }
示例#59
0
        private void ValidateFeature(IFeature feature)
        {
            if (feature.FeatureType != esriFeatureType.esriFTSimpleJunction)
            {
                MessageService.Current.Warn("请选择管线点");
                return;
            }
            if (!_pipelineConfig.IsPipelineLayer(feature.Class.AliasName, enumPipelineDataType.Point))
            {
                MessageService.Current.Warn("请选择管线点");
                return;
            }
            double snapDist = CommonUtils.ConvertPixelsToMapUnits(_context.ActiveView,
                                                                  _context.Config.SnapTolerance);

            if (this._startPoint == null && _startEid == 0)
            {
                //开始记录起始点
                IPipelineLayer oldLayer = _pipelineConfig.GetPipelineLayer(feature.Class.AliasName,
                                                                           enumPipelineDataType.Point);
                if (oldLayer == null)
                {
                    MessageService.Current.Warn("你选择的图层不是合法的管线图层!");
                    return;
                }
                List <IBasicLayerInfo> basicInfos = oldLayer.GetLayers(enumPipelineDataType.Junction);

                IFeatureClass featureClass = basicInfos.Count > 0 ? basicInfos[0].FeatureClass : null;
                if (featureClass == null)
                {
                    MessageService.Current.Warn("管线图层没有构建网络图层!");
                    return;
                }
                INetworkClass networkClass = featureClass as INetworkClass;
                _geometricNetwork = networkClass.GeometricNetwork;
                IPointToEID pnToEid = new PointToEIDClass();
                pnToEid.GeometricNetwork = _geometricNetwork;
                pnToEid.SnapTolerance    = snapDist;
                pnToEid.SourceMap        = _context.FocusMap;
                pnToEid.GetNearestJunction(feature.Shape as IPoint, out _startEid, out _startPoint);
                return;
            }

            IPipelineLayer newLayer = _pipelineConfig.GetPipelineLayer(feature.Class.AliasName,
                                                                       enumPipelineDataType.Point);

            if (newLayer == null)
            {
                MessageService.Current.Warn("你选择的图层不是合法的管线图层!");
                return;
            }
            List <IBasicLayerInfo> basicInfos1 = newLayer.GetLayers(enumPipelineDataType.Junction);

            IFeatureClass featureClass2 = basicInfos1.Count > 0 ? basicInfos1[0].FeatureClass : null;

            if (featureClass2 == null)
            {
                MessageService.Current.Warn("第二个管线图层没有构建网络图层!");
                return;
            }
            INetworkClass networkClass2 = featureClass2 as INetworkClass;

            if (networkClass2.GeometricNetwork != _geometricNetwork)
            {
                if (MessageService.Current.Ask("两个点位属于不同的网络图层,使用第二个网络图层作为分析图层吗?") == false)
                {
                    return;
                }
                _geometricNetwork = networkClass2.GeometricNetwork;
                IPointToEID pnToEid = new PointToEIDClass();
                pnToEid.GeometricNetwork = _geometricNetwork;
                pnToEid.SnapTolerance    = snapDist;
                pnToEid.SourceMap        = _context.FocusMap;
                pnToEid.GetNearestJunction(feature.Shape as IPoint, out _startEid, out _startPoint);
                return;
            }


            try
            {
                IPointToEID pntEid = new PointToEIDClass();
                pntEid.GeometricNetwork = _geometricNetwork;
                pntEid.SourceMap        = _context.FocusMap;
                pntEid.SnapTolerance    = snapDist;

                pntEid.GetNearestJunction(feature.Shape as IPoint, out _endEid, out _endPoint);
                if (_endEid < 1)
                {
                    MessageService.Current.Warn("未能找到第二个分析点!");
                    return;
                }
                if (_startEid == _endEid)
                {
                    MessageService.Current.Warn("起点终点为同一个点!");
                    return;
                }

                INetElements    netElements = _geometricNetwork.Network as INetElements;
                IJunctionFlag[] array       = new JunctionFlag[2];
                INetFlag        netFlag     = new JunctionFlag() as INetFlag;

                int userClassID;
                int userID;
                int userSubID;
                netElements.QueryIDs(_endEid, esriElementType.esriETJunction, out userClassID,
                                     out userID, out userSubID);
                netFlag.UserClassID = (userClassID);
                netFlag.UserID      = (userID);
                netFlag.UserSubID   = (userSubID);
                IJunctionFlag value = netFlag as IJunctionFlag;
                array.SetValue(value, 0);
                INetFlag netFlag2 = new JunctionFlag() as INetFlag;
                netElements.QueryIDs(_startEid, esriElementType.esriETJunction, out userClassID,
                                     out userID, out userSubID);
                netFlag2.UserClassID = (userClassID);
                netFlag2.UserID      = (userID);
                netFlag2.UserSubID   = (userSubID);
                value = (netFlag2 as IJunctionFlag);
                array.SetValue(value, 1);
                ITraceFlowSolverGEN traceFlowSolverGEN = new TraceFlowSolver() as ITraceFlowSolverGEN;
                INetSolver          netSolver          = traceFlowSolverGEN as INetSolver;
                netSolver.SourceNetwork = _geometricNetwork.Network;
                traceFlowSolverGEN.PutJunctionOrigins(ref array);
                object[]    array2 = new object[1];
                IEnumNetEID enumNetEID;
                IEnumNetEID enumNetEID2;
                traceFlowSolverGEN.FindPath(esriFlowMethod.esriFMConnected,
                                            (esriShortestPathObjFn.esriSPObjFnMinMax), out enumNetEID, out enumNetEID2, 1, ref array2);
                if (this.ipolyline_0 == null)
                {
                    this.ipolyline_0 = new Polyline() as IPolyline;
                }
                IGeometryCollection geometryCollection = this.ipolyline_0 as IGeometryCollection;
                geometryCollection.RemoveGeometries(0, geometryCollection.GeometryCount);
                if (enumNetEID2.Count <= 0)
                {
                    this._iFeature = null;
                    MessageService.Current.Warn("两点之间不存在路径可以连通!");
                    return;
                }
                else
                {
                    ISpatialReference spatialReference = _context.FocusMap.SpatialReference;
                    IEIDHelper        eIDHelperClass   = new EIDHelper();
                    eIDHelperClass.GeometricNetwork       = _geometricNetwork;
                    eIDHelperClass.OutputSpatialReference = (spatialReference);
                    eIDHelperClass.ReturnGeometries       = (true);
                    IEnumEIDInfo enumEIDInfo = eIDHelperClass.CreateEnumEIDInfo(enumNetEID2);
                    int          count       = enumEIDInfo.Count;
                    enumEIDInfo.Reset();
                    double num2 = 0.0;
                    for (int i = 0; i < count; i++)
                    {
                        IEIDInfo  iEIDInfo = enumEIDInfo.Next();
                        IGeometry geometry = iEIDInfo.Geometry;
                        IPolyline polyline = geometry as IPolyline;
                        num2 += polyline.Length;
                        geometryCollection.AddGeometryCollection(geometry as IGeometryCollection);
                    }

                    EsriUtils.ZoomToGeometry(this.ipolyline_0, _context.MapControl.Map, 1.3);
                    FlashUtility.FlashGeometry(this.ipolyline_0, _context.MapControl);

                    //_context.ActiveView.Refresh();
                    //CMapOperator.ShowFeatureWithWink(_context.ActiveView.ScreenDisplay, this.ipolyline_0);
                    this._iFeature    = null;
                    _startEid         = 0;
                    _startPoint       = null;
                    _geometricNetwork = null;

                    string text3 = string.Format("两个管线点之间连通,最短路径为{0}米", num2.ToString("f2"));
                    MessageService.Current.Info(text3);
                }
            }
            catch (Exception ex)
            {
                this._iFeature    = null;
                _startEid         = 0;
                _startPoint       = null;
                _geometricNetwork = null;
                MessageService.Current.Warn(ex.Message);
            }
        }
示例#60
0
 protected InnerRingsFootprintProviderBase(
     [CanBeNull] ISpatialReference alternateSpatialReference)
     : base(alternateSpatialReference)
 {
 }