public ISpatialReference CreateSpatialReferenceFromDefinitionStr(string str) { ISpatialReference spatialRef = new UnknownCoordinateSystem() as ISpatialReference; try { string tempFile = System.IO.Path.GetTempFileName(); string prjFile = System.IO.Path.ChangeExtension(tempFile, ".prj"); File.Move(tempFile, prjFile); //修改文件扩展名 using (FileStream fs = new FileStream(prjFile, FileMode.Open)) { StreamWriter sw = new StreamWriter(fs, Encoding.Unicode); sw.WriteLine(str); sw.Flush(); sw.Close(); spatialRef = new SpatialReferenceEnvironment().CreateESRISpatialReferenceFromPRJFile(prjFile); File.Delete(prjFile); } } catch (Exception ex) { ErrorMessage = ex.Message; } return(spatialRef); }
private void buttonX_ok_Click(object sender, EventArgs e) { CGmpPoint xml = new CGmpPoint(); bool result = xml.ReadGmpXML(XMLPath); Regex regNum = new Regex("^[0-9]"); if (regNum.IsMatch(textBoxX3.Text) == true) { MessageBox.Show("数据集名称不能以数字开头命名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (result == true) { try { IWorkspaceFactory workspaceFactory = new FileGDBWorkspaceFactoryClass(); gdbPath = textBoxX2.Text; IFeatureWorkspace pFeatureWorkspace = workspaceFactory.OpenFromFile(gdbPath, 0) as IFeatureWorkspace; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment(); //ISpatialReference pSpatialReference = new UnknownCoordinateSystemClass(); ISpatialReference pSpatialReference = ClsGDBDataCommon.CreateProjectedCoordinateSystem(); pSpatialReference.SetDomain(-8000000, 8000000, -800000, 8000000); IFeatureDataset pFeatureDataset = pFeatureWorkspace.CreateFeatureDataset(textBoxX3.Text, pSpatialReference); IFeatureClass pFeatureclass = CreatePointFeatureClass(pFeatureDataset, xml); IFeatureClass pFCLine = CreatLineFC(pFeatureDataset, pFeatureclass); if (pFeatureclass == null || pFCLine == null) { MessageBox.Show("数据生成失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } IFeatureLayer pFPointLayer = new FeatureLayerClass(); pFPointLayer.FeatureClass = pFeatureclass; pFPointLayer.Name = textBoxX3.Text + "_Gmppoint"; IFeatureLayer pFLintLayer = new FeatureLayerClass(); pFLintLayer.FeatureClass = pFCLine; pFLintLayer.Name = textBoxX3.Text + "_GmpLine"; m_pMapCtl.AddLayer(pFLintLayer as ILayer, 0); m_pMapCtl.AddLayer(pFPointLayer as ILayer, 0); m_pMapCtl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); if (cmbImpSymbol.Text != null && symFilePath != null) { ImpSymbolFromFile(symFilePath, pFPointLayer, pFLintLayer); } //MessageBox.Show("数据已经生成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } }
public static string latlongCoordinates(IFeatureClass SiteLayer) { // Get the feature and its geometry given an Object ID. IFeature stateFeature = SiteLayer.GetFeature(0); IGeometry shapeGeometry = stateFeature.Shape; IArea pArea; pArea = shapeGeometry as IArea; IPoint pPoint; pPoint = pArea.Centroid; IGeometry pGeometry = (IGeometry)pPoint; ISpatialReferenceFactory pSpatFactory = new SpatialReferenceEnvironment(); IGeographicCoordinateSystem pGeoSystem = pSpatFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_NAD1983); ISpatialReference pSpatReference = (ISpatialReference)pGeoSystem; pSpatReference.SetFalseOriginAndUnits(-180, -90, 1000000); pGeometry.Project(pSpatReference); double Longitude = Math.Abs(pPoint.X); double Latitude = Math.Abs(pPoint.Y); return(Longitude.ToString("#.######") + "° W, " + Latitude.ToString("#.######") + "° N"); }
private void GoogleMap() { // ERROR: Not supported in C#: OnErrorStatement IActiveView pMapsActiveView; IEnvelope pEnvelope; ISpatialReference pEnvSpatRef; ISpatialReferenceInfo pSRI; IProjectedCoordinateSystem pPCS; pMapsActiveView = (IActiveView)m_hookHelper.FocusMap; pEnvelope = pMapsActiveView.ScreenDisplay.DisplayTransformation.VisibleBounds; pCenterPt = new ESRI.ArcGIS.Geometry.Point(); pEnvSpatRef = pEnvelope.SpatialReference; ISpatialReference pSpRef2; SpatialReferenceEnvironment pSpRFc; IGeographicCoordinateSystem pGCS; pSpRFc = new SpatialReferenceEnvironment(); pGCS = pSpRFc.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); pSpRef2 = pGCS; pSpRef2.SetFalseOriginAndUnits(-180, -90, 1000000); pEnvelope.Project(pSpRef2); pCenterPt.PutCoords((pEnvelope.LowerLeft.X + pEnvelope.LowerRight.X) / 2, (pEnvelope.LowerLeft.Y + pEnvelope.UpperRight.Y) / 2); return; E: return; }
// Get the default spatial reference (used for output) private ISpatialReference GetSpatialReference() { ISpatialReferenceFactory srFact = new SpatialReferenceEnvironment() as ISpatialReferenceFactory; IGeographicCoordinateSystem projectedCS = srFact.CreateGeographicCoordinateSystem( (int)SPATIAL_REF); return(projectedCS); }
internal static ISpatialReference GetSpatialReference(int wkid) { return(WkidToSpatialReference.GetOrAdd(wkid, n => { var spatialReferenceEnvironment = new SpatialReferenceEnvironment(); try { return spatialReferenceEnvironment.CreateGeographicCoordinateSystem(wkid); } catch { return spatialReferenceEnvironment.CreateProjectedCoordinateSystem(wkid); } })); }
internal static ISpatialReference GetSpatialReference(string wkt) { var spatialReferenceEnvironment = new SpatialReferenceEnvironment(); ISpatialReference spatialReference; int n; spatialReferenceEnvironment.CreateESRISpatialReference(wkt, out spatialReference, out n); return(spatialReference); }
static void CreateGrid(TileInfo tiles, int level, IFeatureWorkspace destination, String name) { ISpatialReferenceFactory2 sEnv = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2; ISpatialReference sr = sEnv.CreateSpatialReference((int)tiles.spatialReference); sr.SetMDomain(-137434824702, 0); IFeatureClass fc = CreateFeatureClass(destination, name, sr); LOD lod = tiles.lods[level]; double width = tiles.width * lod.resolution; double height = tiles.height * lod.resolution; double y = tiles.originY; long row = 0; double maxX = -(tiles.originX + width); double minY = -(tiles.originY - height); while (y > minY) { double x = tiles.originX; long col = 0; while (x < maxX) { RingClass ring = new RingClass(); IPoint tl = new PointClass(); tl.PutCoords(x, y); tl.M = -(((col & 0xFFFF) << 16) + (row & 0xFFFF)); ring.AddPoint(tl); IPoint tr = new PointClass(); tr.PutCoords(x + width, y); tr.M = -((((col + 1) & 0xFFFF) << 16) + (row & 0xFFFF)); ring.AddPoint(tr); IPoint br = new PointClass(); br.PutCoords(x + width, y - width); br.M = -((((col + 1) & 0xFFFF) << 16) + ((row + 1) & 0xFFFF)); ring.AddPoint(br); IPoint bl = new PointClass(); bl.PutCoords(x, y - width); bl.M = -(((col & 0xFFFF) << 16) + ((row + 1) & 0xFFFF)); ring.AddPoint(bl); ring.AddPoint(tl); ring.Close(); PolygonClass polygon = new PolygonClass(); polygon.AddGeometry(ring); IFeature polyFeature = fc.CreateFeature(); polyFeature.Shape = polygon; polyFeature.Store(); x += width; col += 1; } row += 1; y -= height; } IFeatureClassDescriptor fd = new FeatureClassDescriptorClass(); fd.Create(fc, null, "OBJECTID"); }
public static IGeometry ProjectGeometry(IGeometry pGeo) { //如果是地理坐标系,则投影到投影坐标系 if (pGeo.SpatialReference is IGeographicCoordinateSystem) { ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); IProjectedCoordinateSystem pcs = srFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_World_Mercator); //投影到 Mercator 坐标系 pGeo.Project(pcs); } return(pGeo); }
//默认的参考 private ISpatialReference spatialReference() { ISpatialReferenceFactory pSpatialReferenceEnvironemnt = new SpatialReferenceEnvironment(); ISpatialReferenceFactory2 pSpatialReferenceFactory2 = pSpatialReferenceEnvironemnt as ISpatialReferenceFactory2; ISpatialReference pSpatialReference = pSpatialReferenceFactory2.CreateSpatialReference(4326); //esriSRProjCS4Type //esriSRGeoCS3Type //esriSRDatum3Type return(pSpatialReference); }
public static IGeometry ProjectGeometryGeo(IGeometry pGeo) { //如果是地理坐标系,则投影到投影坐标系 if (pGeo.SpatialReference is IProjectedCoordinateSystem) { ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); IGeographicCoordinateSystem pcs = srFactory.CreateGeographicCoordinateSystem(4326); //投影到 Mercator 坐标系 pGeo.Project(pcs); } return(pGeo); }
public static IPoint JWD2XY(IPoint pJWDPoint, int gcsType, int pcsType) { try { ISpatialReferenceFactory factory = new SpatialReferenceEnvironment(); pJWDPoint.SpatialReference = factory.CreateGeographicCoordinateSystem(gcsType); pJWDPoint.Project(factory.CreateProjectedCoordinateSystem(pcsType)); return(pJWDPoint); } catch { return(null); } }
private ESRI.ArcGIS.Geometry.ISpatialReference getWGS84() { ISpatialReferenceFactory oSpatialReferenceFactory; try { oSpatialReferenceFactory = new SpatialReferenceEnvironment(); return(oSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984)); } catch //(Exception ex) { return(GetSpatialReference(esriSRGeoCSType.esriSRGeoCS_WGS1984)); } }
public static IPoint XY2JWD(double x, double y, int gcsType, int pcsType) { try { IPoint point = new ESRI.ArcGIS.Geometry.Point(); point.PutCoords(x, y); ISpatialReferenceFactory factory = new SpatialReferenceEnvironment(); point.SpatialReference = factory.CreateProjectedCoordinateSystem(pcsType); point.Project(factory.CreateGeographicCoordinateSystem(gcsType)); return(point); } catch { return(null); } }
private ISpatialReference GetSpatialReference(ESRI.ArcGIS.Geometry.esriSRGeoCSType FactoryCode) { ISpatialReferenceFactory oSpatialReferenceFactory; IGeographicCoordinateSystem oGCS; try { oSpatialReferenceFactory = new SpatialReferenceEnvironment(); oGCS = oSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)FactoryCode); return(oGCS); } catch { return(null); } }
// 将经纬度点转换为平面坐标 private static IPoint GetProCoordinate(double x, double y) { //投影坐标系转换,经纬度到平面坐标 ISpatialReferenceFactory SRFactory = new SpatialReferenceEnvironment(); IProjectedCoordinateSystem flatref = SRFactory.CreateProjectedCoordinateSystem(2372); //80坐标 IGeographicCoordinateSystem earthref = SRFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //输入坐标 IPoint pt = new PointClass(); pt.PutCoords(x, y); IGeometry geo = (IGeometry)pt; geo.SpatialReference = earthref; geo.Project(flatref); return(pt); }
static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { }); //ESRI License Initializer generated code. //Get a path to the raster workspace and create a RasterWorkspace object Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IRasterWorkspace2 rasterWorkspace = (IRasterWorkspace2)workspaceFactory.OpenFromFile("\\\\Filepath\\ToRaster\\Folder", 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset("DEM_Resample.tif"); //Create a raster layer to get the raster object from it IRasterLayer rasterLayer = new RasterLayer(); rasterLayer.CreateFromDataset(rasterDataset); IRaster raster = rasterLayer.Raster; //Get the raster properties so we can modify them later and get details about them if we so choose. IRasterProps rasterProps = raster as IRasterProps; double cellSize = 60; //Declate a new spatial reference if you want to change the spatial reference used. ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); ISpatialReference2 srReference = srFactory.CreateProjectedCoordinateSystem(26917) as ISpatialReference2; //Create an IRasterGeometryProc object as this has the projectFast method we are looking for. IRasterGeometryProc rasterGeometryProc = new RasterGeometryProc(); rasterGeometryProc.ProjectFast(rasterProps.SpatialReference, rstResamplingTypes.RSP_NearestNeighbor, ((object)cellSize), raster); //Create a new rasterBandCollection to store the raster in and save it there. IRasterBandCollection rasterBandCollection = raster as IRasterBandCollection; String outName = "NewImage.tif"; String outType = "TIFF"; rasterBandCollection.SaveAs(outName, ((IWorkspace)rasterWorkspace), outType); Console.WriteLine("DONE"); Console.ReadLine(); //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); }
public static IRaster reprojectRasterDataset(string string_0, string string_1, int int_0) { IWorkspaceFactory factory = new RasterWorkspaceFactory(); IRasterWorkspace workspace = factory.OpenFromFile(string_0, 0) as IRasterWorkspace; IRaster raster = workspace.OpenRasterDataset(string_1).CreateDefaultRaster(); Console.WriteLine("Created default raster: " + string_1); SpatialReferenceEnvironment environment = new SpatialReferenceEnvironment(); ISpatialReference reference = environment.CreateProjectedCoordinateSystem(int_0); IRasterProps props = raster as IRasterProps; Console.WriteLine("Orig Raster Coordinate System: ." + props.SpatialReference.Name.ToString()); props.SpatialReference = reference; Console.WriteLine("New Raster Coordinate System: ." + props.SpatialReference.Name.ToString()); props.Height /= 2; props.Width /= 2; return(raster); }
public static IFeatureClass CreatePtTest(string filepath, string ptname) { //创建最后所需的点图层 IFeatureClass feaclass = null; //创建工作空间 IWorkspaceFactory pWorkspacefactory = new ShapefileWorkspaceFactoryClass(); IWorkspace pWorkspace = pWorkspacefactory.OpenFromFile(filepath, 0); IFeatureWorkspace pFeaWorkspace = pWorkspace as IFeatureWorkspace; IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = pFields as IFieldsEdit; //IFieldEdit提供了添加字段名称类型的方法 IField pField = new FieldClass(); IFieldEdit pFieldEdit = pField as IFieldEdit; pFieldEdit.Name_2 = "shape"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //定义了矢量数据是点矢量 IGeometryDef pGeomtryDef = new GeometryDefClass(); IGeometryDefEdit pGeomtryDefEdit = pGeomtryDef as IGeometryDefEdit; pGeomtryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //坐标系统的创建 ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment(); //esri自身能够支持的强制数据类型装换。 IGeographicCoordinateSystem pGeographicCoordinateSystem = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); pGeomtryDefEdit.SpatialReference_2 = pGeographicCoordinateSystem as ISpatialReference; //将坐标系参数传回到属性字段 pFieldEdit.GeometryDef_2 = pGeomtryDef; pFieldsEdit.AddField(pField); feaclass = pFeaWorkspace.CreateFeatureClass(ptname, pFieldsEdit, null, null, esriFeatureType.esriFTSimple, "shape", ""); return(feaclass); }
static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { }); //ESRI License Initializer generated code. //Get a path to the raster workspace and create a RasterWorkspace object Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory; IRasterWorkspace2 rasterWorkspace = (IRasterWorkspace2) workspaceFactory.OpenFromFile("\\\\Filepath\\ToRaster\\Folder", 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset("DEM_Resample.tif"); //Create a raster layer to get the raster object from it IRasterLayer rasterLayer = new RasterLayer(); rasterLayer.CreateFromDataset(rasterDataset); IRaster raster = rasterLayer.Raster; //Get the raster properties so we can modify them later and get details about them if we so choose. IRasterProps rasterProps = raster as IRasterProps; double cellSize = 60; //Declate a new spatial reference if you want to change the spatial reference used. ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); ISpatialReference2 srReference = srFactory.CreateProjectedCoordinateSystem(26917) as ISpatialReference2; //Create an IRasterGeometryProc object as this has the projectFast method we are looking for. IRasterGeometryProc rasterGeometryProc = new RasterGeometryProc(); rasterGeometryProc.ProjectFast(rasterProps.SpatialReference, rstResamplingTypes.RSP_NearestNeighbor, ((object)cellSize), raster); //Create a new rasterBandCollection to store the raster in and save it there. IRasterBandCollection rasterBandCollection = raster as IRasterBandCollection; String outName = "NewImage.tif"; String outType = "TIFF"; rasterBandCollection.SaveAs(outName, ((IWorkspace)rasterWorkspace), outType); Console.WriteLine("DONE"); Console.ReadLine(); //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); }
/// <summary> /// Creates a WGS1984 Spatial Reference. /// </summary> /// <returns></returns> public static ISpatialReference CreateGeographicSR() { ISpatialReference pSR = null; ISpatialReferenceFactory pSpatialRefFactory = new SpatialReferenceEnvironment(); IGeographicCoordinateSystem pGeogCoorSystem = pSpatialRefFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); try { pSR = pGeogCoorSystem; pSR.SetFalseOriginAndUnits(-180, -90, 1000000); } catch (Exception oErr) { MessageBox.Show(oErr.ToString(), "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } //clean up pGeogCoorSystem = null; pSpatialRefFactory = null; return(pSR); }
/// <summary> /// Creates a WGS1984 Spatial Reference. /// </summary> /// <returns></returns> private ISpatialReference CreateGeographicSR() { ISpatialReference pSR = null; ISpatialReferenceFactory pSpatialRefFactory = new SpatialReferenceEnvironment(); IGeographicCoordinateSystem pGeogCoorSystem = pSpatialRefFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); try { pSR = pGeogCoorSystem; pSR.SetFalseOriginAndUnits(-180, -90, 1000000); } catch (Exception ex) { clsStatic.ShowErrorMessage(ex.ToString()); } //clean up pGeogCoorSystem = null; pSpatialRefFactory = null; return(pSR); }
private IProjectedCoordinateSystem GetProjectedCoordinateSystem() { //以下结果均不加带号 //if(北京54and三度带)2397+带号 4 //if(北京54and六度带)21400+带号 //if(西安80and三度带)2345+带号 4 //if(西安80and六度带)2325+带号 4 //创建投影坐标系 try { SpatialReferenceEnvironment spatialReferenceEnvironment = new SpatialReferenceEnvironment(); IProjectedCoordinateSystem projectedCoordinateSystem = new UnknownCoordinateSystemClass() as IProjectedCoordinateSystem; if (cbbCoordinateSystem.Text == "北京54坐标系" && cbbfendai.Text == "三度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(2397 + Convert.ToInt32(cbbnumber.Text)); } else if (cbbCoordinateSystem.Text == "北京54坐标系" && cbbfendai.Text == "六度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(21400 + Convert.ToInt32(cbbnumber.Text)); } else if (cbbCoordinateSystem.Text == "西安80坐标系" && cbbfendai.Text == "三度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(2345 + Convert.ToInt32(cbbnumber.Text)); } else if (cbbCoordinateSystem.Text == "西安80坐标系" && cbbfendai.Text == "六度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(2325 + Convert.ToInt32(cbbnumber.Text)); } return(projectedCoordinateSystem); } catch (Exception ex) { string exception = ex.Message; MessageBox.Show(exception); return(null); } }
private void PointToLatLong(IPoint Point, out double Latitude, out double Longitude) { Latitude = 39.759444; Longitude = -84.191667; try { var spatialReferenceEnvironment = new SpatialReferenceEnvironment(); var geographicCoordinateSystem = spatialReferenceEnvironment.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); var spatialReferenceOutput = geographicCoordinateSystem; spatialReferenceOutput.SetFalseOriginAndUnits(-180, -90, 1000000); var geometry2 = (IGeometry2)Point; var spatialReference = _map.SpatialReference; if (spatialReference == null) { return; } geometry2.SpatialReference = spatialReference; geometry2.Project(spatialReferenceOutput); IPoint newPoint = (Point)geometry2; Latitude = newPoint.Y; Longitude = newPoint.X; return; } catch (Exception) { // ignored } return; }
IFields CreateFields(baseFieldList pNewFields) { IFields pFields = new FieldsClass(); IFieldsEdit fieldsEdit = pFields as IFieldsEdit; //Shape Field IField fd1 = new FieldClass(); IFieldEdit fde1 = fd1 as IFieldEdit; fde1.Name_2 = "Shape"; fde1.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeomDef = new GeometryDefClass(); IGeometryDefEdit pGeomDefEdit = pGeomDef as IGeometryDefEdit; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment(); pGeomDefEdit.GeometryType_2 = m_nGeometryType; pGeomDefEdit.SpatialReference_2 = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; fde1.GeometryDef_2 = pGeomDef; fieldsEdit.AddField(fde1); for (int i = 0; i < pNewFields.Count; i++) { baseField pNewField = pNewFields.get_Element(i); IField pField; pField = new FieldClass(); IFieldEdit pFieldEdit; pFieldEdit = pField as IFieldEdit; pFieldEdit.Type_2 = pNewField.ftFieldType; pFieldEdit.Name_2 = pNewField.strFieldName; pFieldEdit.AliasName_2 = pNewField.strFieldAliasName; if (pNewField.ftFieldType == esriFieldType.esriFieldTypeString) { pFieldEdit.Length_2 = pNewField.nFieldLen; } fieldsEdit.AddField(pField); } return(pFields); }
public static IFeatureClass createGoogleMapsEngineCatalogFeatureClass(ref log4net.ILog log, ref GoogleMapsEngineToolsExtensionForArcGIS ext) { try { // temporary directory to store workspace string workspacedirectory = ext.getLocalWorkspaceDirectory().FullName; // add the directory to the cleanup list // TODO: Replace with scratch ext.addTemporaryDirectory(new System.IO.DirectoryInfo(workspacedirectory)); // determine the workspace name for the geodatabase //string workspacefoldername = Properties.Settings.Default.extension_gdb_workspacename; // TODO: Use sctach workspace instead of creating a temporary one string workspacefoldername = "GME_Data_" + System.Guid.NewGuid().ToString().Replace("-", ""); // define a workspace to do work IWorkspace workspace = null; // attempt to open or create the workspace try { // check to see if the workspace already exists, if so, open it if (System.IO.Directory.Exists(workspacedirectory + "\\" + workspacefoldername)) { workspace = Extension.Data.GeodatabaseUtilities.openFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername); ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName); ESRI.ArcGIS.Geodatabase.IDataset pdataset = (ESRI.ArcGIS.Geodatabase.IDataset)featureClass; if (pdataset.CanDelete()) pdataset.Delete(); pdataset = null; featureClass = null; featureWorkspace = null; // TODO: Open instead of delete/replace //if (arcgis.ext.gdb.GeodatabaseUtilities.deleteFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername)) //workspace = arcgis.ext.gdb.GeodatabaseUtilities.createFileGeodatabaseWorkspace(workspacedirectory, workspacefoldername); } else { // workspace doesn't exist, create the workspace workspace = Extension.Data.GeodatabaseUtilities.createFileGeodatabaseWorkspace(ref log, workspacedirectory, workspacefoldername); } } catch (System.Exception ex) { // unable to create the fgdb or unable to delete the fc within the fgdb log.Error(ex); System.Windows.Forms.MessageBox.Show("Unable to create or delete an existing feature class."); } // verify the workspace is open if (workspace != null) { // create a new feature workspace to work spatially IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; // create a spatial reference for the Google Earth Builder data (always in 4326) SpatialReferenceEnvironment sRefEnvGEB = new SpatialReferenceEnvironment(); ISpatialReference sGEBRef = sRefEnvGEB.CreateGeographicCoordinateSystem(4326); // for this feature class, create and determine the field IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = 10; //Create the Object ID field. IField fusrDefinedField = new Field(); IFieldEdit fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_OBJECTID_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.set_Field(0, fusrDefinedField); //Create the CustomerId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_CustomerId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(1, fusrDefinedField); //Create the MapAssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapAssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(2, fusrDefinedField); //Create the AssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(3, fusrDefinedField); //Create the ParentAssetId field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_ParentAssetId_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(4, fusrDefinedField); //Create the AssetType field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetType_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(5, fusrDefinedField); //Create the AssetName field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetName_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(6, fusrDefinedField); //Create the AssetDescription field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_AssetDescription_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(7, fusrDefinedField); //Create the MapSharedWith field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; fusrDefinedFieldEdit.Name_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_Name; fusrDefinedFieldEdit.AliasName_2 = Properties.Resources.GeodatabaseUtilities_schema_MapSharedWith_AliasName; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldsEdit.set_Field(8, fusrDefinedField); // Create the Shape field. fusrDefinedField = new Field(); fusrDefinedFieldEdit = (IFieldEdit)fusrDefinedField; // Set up the geometry definition for the Shape field. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.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.GridCount_2 = 1; geometryDefEdit.set_GridSize(0, 0); geometryDefEdit.HasM_2 = false; geometryDefEdit.HasZ_2 = false; //Assign the spatial reference that was passed in, possibly from //IGeodatabase.SpatialReference for the containing feature dataset. geometryDefEdit.SpatialReference_2 = sGEBRef; // Set standard field properties. fusrDefinedFieldEdit.Name_2 = "SHAPE"; fusrDefinedFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; fusrDefinedFieldEdit.GeometryDef_2 = geometryDef; fusrDefinedFieldEdit.IsNullable_2 = true; fusrDefinedFieldEdit.Required_2 = true; fieldsEdit.set_Field(9, fusrDefinedField); // Create a feature class description object to use for specifying the CLSID and EXTCLSID. IFeatureClassDescription fcDesc = new FeatureClassDescriptionClass(); IObjectClassDescription ocDesc = (IObjectClassDescription)fcDesc; IFeatureClass fc = featureWorkspace.CreateFeatureClass( Properties.Resources.GeodatabaseUtilities_schema_FeatureClassName, // Feature Class Name fields, // Feature Class Fields (defined above) ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDesc.ShapeFieldName, // Shape Field Name "" // Keyword Configurations ); // return the feature class return fc; } else { // end gracefully, maybe prompt the user that the toolbar wasn't able to create a workspcae throw new Exception("Unable to open local geodatabase."); } } catch (System.Exception ex) { // an error occured log.Error(ex); // throw an exception throw new Exception("An unknown exception occured while attempting to create a local feature class."); } }
private byte[] CreateWatershedHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; #region Process the REST arguments // hydroshed_id - REQUIRED - to identify the overall result string search_id; bool found = operationInput.TryGetString("search_id", out search_id); if (!found || string.IsNullOrEmpty(search_id)) { throw new ArgumentNullException("search_id"); } // input point - REQUIRED - the search location JsonObject jsonPoint; found = operationInput.TryGetJsonObject("location", out jsonPoint); if (!found) { throw new ArgumentNullException("location"); } IPoint locationpoint = Conversion.ToGeometry(jsonPoint, esriGeometryType.esriGeometryPoint) as IPoint; long? jsonWkid; found = operationInput.TryGetAsLong("input_wkid", out jsonWkid); if (!found) { throw new ArgumentNullException("input_wkid", "WKID numeric value for spatial reference of input point must be provided"); } if (jsonWkid.HasValue) { int wkid = (int)jsonWkid.Value; ISpatialReferenceFactory2 tInSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2; ISpatialReference tInSR = tInSRFac.CreateSpatialReference(wkid); locationpoint.SpatialReference = tInSR; } // extent - OPTIONAL - we will use full extent if not provided but this is slow!! // TODO maybe preferable to have the extent looked up in the SOE rather than expecting it as a parameter JsonObject jsonExtent; found = operationInput.TryGetJsonObject("extent", out jsonExtent); IGeometry tAnalysisEnvelope; if (found && jsonExtent != null) { logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "Found input extent json object "); tAnalysisEnvelope = convertAnyJsonGeometry(jsonExtent); logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "Input extent processed ok "); try { logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "Input extent height*width are: " + tAnalysisEnvelope.Envelope.Height.ToString() + " * " + tAnalysisEnvelope.Envelope.Width.ToString()); } catch (NullReferenceException nre) { logger.LogMessage(ServerLogger.msgType.debug, "Processing parameters", 8000, "Problem reading input extent, exception was " + nre.Message + " at " + nre.StackTrace); } } else { tAnalysisEnvelope = null; logger.LogMessage(ServerLogger.msgType.debug, "process input params", 8000, "No input extent parameter requested "); } List<ExtractionLayerConfig> extractionRequests = new List<ExtractionLayerConfig>(); foreach (ExtractionLayerConfig tExtLayerInfo in m_ExtractableParams) { string jsonParam = tExtLayerInfo.ParamName; bool? wasRequested; found = operationInput.TryGetAsBoolean(jsonParam, out wasRequested); if (found && wasRequested.HasValue && (bool)wasRequested) { extractionRequests.Add(tExtLayerInfo); } } // check whether to return as json structured object or all flattened onto attributes of the // polygon bool returnAsPolygonAttributes=false; if (extractionRequests.Count > 0) { bool? nullableBool; found = operationInput.TryGetAsBoolean("extractToPolygonAttributes", out nullableBool); if (found && nullableBool.HasValue) { returnAsPolygonAttributes = (bool)nullableBool; } } #endregion #region Do the actual watershed extraction // Modified the computeWatershed method to return both the raster and converted polygon versions of the // watershed. Because the polygon version, if made by unioning separate polygons, is multipart, and // although this is what we want to return to the user, the raster extraction operations can't handle // that so we run them with a raster mask input instead. Returning both here saves the extraction methods // from converting back to a raster. IGeoDataset tWatershedPolyGDS; IGeoDataset tWatershedRasterGDS; if (tAnalysisEnvelope != null) { KeyValuePair<IGeoDataset, IGeoDataset> tPair = computeWatershed(locationpoint, tAnalysisEnvelope.Envelope); tWatershedPolyGDS = tPair.Value; tWatershedRasterGDS = tPair.Key; } else { try { IEnvelope tAnalysisActuallyAnEnvelope = GetAnalysisEnvelope(locationpoint); KeyValuePair<IGeoDataset, IGeoDataset> tPair = computeWatershed(locationpoint, tAnalysisActuallyAnEnvelope); tWatershedPolyGDS = tPair.Value; tWatershedRasterGDS = tPair.Key; } catch { // error getting the extent. Compute watershed without one (will be slow). KeyValuePair<IGeoDataset, IGeoDataset> tPair = computeWatershed(locationpoint, null); tWatershedPolyGDS = tPair.Value; tWatershedRasterGDS = tPair.Key; } } #endregion #region Modify the default fields in polygon catchment // raster-to-poly conversion adds some fields we don't want - remove them // also we will return the search id, and the corresponding outlet coordinates as // attributes on the catchment try { IFeatureClass tPolygonAsFC = (IFeatureClass)tWatershedPolyGDS; // these get made by raster-poly conversion and they're boring TryDeleteAField(tPolygonAsFC, "GRIDCODE"); TryDeleteAField(tPolygonAsFC, "ID"); // Now then now then. After an irritating Thursday afternoon i've discovered that we can't use // tPolygonAsFC.GetFeature(1). Because 1 doesn't mean the first one in the FC, but the one with // OID = 1. If there were multiple polygons that got deleted and replaced by a single unioned one, then // the unioned one won't have OID = 1, as OIDs aren't reused. So we have to use a cursor to get the // feature instead. Add all the fields first, to save having to redo the feature retrieval from the // cursor, then set them if they added ok. bool addedSearchId = AddAField(tPolygonAsFC, "search_id", esriFieldType.esriFieldTypeString, search_id.Length); bool addedOutletX = AddAField(tPolygonAsFC, "outlet_x", esriFieldType.esriFieldTypeDouble); bool addedOutletY = AddAField(tPolygonAsFC, "outlet_y", esriFieldType.esriFieldTypeDouble); IFeature tCatchmentFeature; IFeatureCursor tFeatureCursor = tPolygonAsFC.Search(null, false); tCatchmentFeature = tFeatureCursor.NextFeature(); // there will only be one, not bothering with loop if (addedSearchId) { try { tCatchmentFeature.set_Value(tCatchmentFeature.Fields.FindField("search_id"), search_id); tCatchmentFeature.Store(); } catch (Exception ex) { logger.LogMessage(ServerLogger.msgType.debug, "create watershed handler", 99, "error setting search id field with value " + search_id + ". Detail: " + ex.StackTrace + " " + ex.Message); } } if (addedOutletX) { try { tCatchmentFeature.set_Value(tCatchmentFeature.Fields.FindField("outlet_x"), locationpoint.X); tCatchmentFeature.Store(); } catch (Exception ex) { logger.LogMessage(ServerLogger.msgType.debug, "create watershed handler", 99, "error setting outlet x field with value " + locationpoint.X + ". Detail: " + ex.StackTrace + " " + ex.Message); } } if (addedOutletY) { try { tCatchmentFeature.set_Value(tCatchmentFeature.Fields.FindField("outlet_y"), locationpoint.Y); tCatchmentFeature.Store(); } catch (Exception ex) { logger.LogMessage(ServerLogger.msgType.debug, "create watershed handler", 99, "error setting outlet y field with value " + locationpoint.Y + ". Detail: " + ex.StackTrace + " " + ex.Message); } } } catch (Exception ex) { logger.LogMessage(ServerLogger.msgType.debug, "create watershed handler", 99, "some weird problem setting fields in output polygon" + ex.Message + ex.TargetSite.Name + ex.StackTrace + ex.InnerException.Message); } #endregion bool tPolygonIsMultipart = false; { IFeatureClass tPolygonAsFC = (IFeatureClass)tWatershedPolyGDS; IFeatureCursor tFeatureCursor = tPolygonAsFC.Search(null, false); IFeature tCatchmentFeature = tFeatureCursor.NextFeature(); IPolygon tCatchmentPolygon = (IPolygon)tCatchmentFeature.ShapeCopy; tPolygonIsMultipart = tCatchmentPolygon.ExteriorRingCount > 1; } logger.LogMessage(ServerLogger.msgType.debug, "create watershed handler", 99, "created watershed polygon, proceeding with extractions"); #region Do the catchment characteristic extractions, if any // Use the catchment feature (both vector and original raster versions) as input into the generic // extraction method // will return one with nothing in if there are no extraction requests ExtractionResultCollection tExtractionResults = ProcessExtractions(search_id, tWatershedPolyGDS, tWatershedRasterGDS, extractionRequests); //IGeoDataset tFinalPolygonGDS = ProcessExtractions(tWatershedPolyGDS, tWatershedRasterGDS, extractionRequests); #endregion // The catchment feature now exists and we also have all the attributes requested. Ready to go. // Return either as attributes on the feature itself or as a structured JSON object if (returnAsPolygonAttributes) { IRecordSetInit returnRecSet = new RecordSetClass(); IGeoDataset tFinalPolygonGDS = tExtractionResults.ResultsAsAttributedGeodataset; returnRecSet.SetSourceTable(tFinalPolygonGDS as ITable, null); IRecordSet recset = returnRecSet as IRecordSet; byte[] jsonFeatures = Conversion.ToJson(recset); return jsonFeatures; } else { JsonObject tResultsAsJson = tExtractionResults.ResultsAsJson; byte[] jsonFeatures = System.Text.Encoding.UTF8.GetBytes(tResultsAsJson.ToJson()); return jsonFeatures; } }
private byte[] ExtractByPolygonHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { string search_id; bool found = operationInput.TryGetString("search_id", out search_id); if (!found || string.IsNullOrEmpty(search_id)) { throw new ArgumentNullException("search_id"); } // input polygon - REQUIRED - the polygon to summarise data within JsonObject jsonPolygon; found = operationInput.TryGetJsonObject("polygon", out jsonPolygon); if (!found) { throw new ArgumentNullException("polygon"); } IPolygon extractionPolygon = Conversion.ToGeometry(jsonPolygon, esriGeometryType.esriGeometryPolygon) as IPolygon; long? jsonWkid; found = operationInput.TryGetAsLong("input_wkid", out jsonWkid); if (!found) { throw new ArgumentNullException("input_wkid", "WKID numeric value for spatial reference of input point must be provided"); } if (jsonWkid.HasValue) { int wkid = (int)jsonWkid.Value; ISpatialReferenceFactory2 tInSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2; ISpatialReference tInSR = tInSRFac.CreateSpatialReference(wkid); extractionPolygon.SpatialReference = tInSR; } else { // we won't get here extractionPolygon.SpatialReference = new UnknownCoordinateSystemClass(); } bool? reqReturnAsAttributes; bool returnAsAttributes = false; found = operationInput.TryGetAsBoolean("extractToPolygonAttributes", out reqReturnAsAttributes); if (found && reqReturnAsAttributes.HasValue) { returnAsAttributes = (bool)reqReturnAsAttributes; } List<ExtractionLayerConfig> extractionRequests = new List<ExtractionLayerConfig>(); foreach (ExtractionLayerConfig tExtLayerInfo in m_ExtractableParams) { string jsonParam = tExtLayerInfo.ParamName; bool? wasRequested; found = operationInput.TryGetAsBoolean(jsonParam, out wasRequested); if (found && wasRequested.HasValue && (bool)wasRequested) { extractionRequests.Add(tExtLayerInfo); } } logger.LogMessage(ServerLogger.msgType.debug, "ExtractByPolygonHandler", 99, "Processed inputs, attempting " + extractionRequests.Count.ToString() + " extractions"); // now need to convert the IPolygon to a geodataset, (a polygon one) for feature // extractions. IWorkspace inMemWksp = CreateInMemoryWorkspace() as IWorkspace; IFeatureWorkspace inMemFeatWksp = inMemWksp as IFeatureWorkspace; IFeatureClass tPolyAsFC = CreateFeatureClassFromGeometry(extractionPolygon, inMemFeatWksp, extractionPolygon.SpatialReference.FactoryCode); IArea tArea = extractionPolygon as IArea; if (AddAField(tPolyAsFC,"Total_Area",esriFieldType.esriFieldTypeDouble)) { IFeatureCursor tFCursor = tPolyAsFC.Search(null,false); IFeature tPolyAsFeature = tFCursor.NextFeature(); tPolyAsFeature.set_Value(tPolyAsFC.FindField("Total_Area"),tArea.Area); tPolyAsFeature.Store(); } IGeoDataset tPolygonGDS = tPolyAsFC as IGeoDataset; // now do the extractions from it ExtractionResultCollection tExtractionResults = ProcessExtractions(search_id,tPolygonGDS, null, extractionRequests); // Warning! Don't go assuming that the suggestively-named responseProperties can be set to anything // helpful to describe, say, response properties. Try setting it to anything other than null // (that I have tried) and you get "500 Unexpected Error" message and lose the best part of an // afternoon working out why! //responseProperties = "Extractions processed successfully"; responseProperties = null; logger.LogMessage(ServerLogger.msgType.debug, "ExtractByPolygonHandler", 99, "Extractions complete, returning feature"); if (returnAsAttributes) { IRecordSetInit returnRecSet = new RecordSetClass(); IGeoDataset tFinalGDS = tExtractionResults.ResultsAsAttributedGeodataset; returnRecSet.SetSourceTable(tFinalGDS as ITable, null); IRecordSet recset = returnRecSet as IRecordSet; byte[] jsonFeature = Conversion.ToJson(recset); return jsonFeature; } else { JsonObject tResultsAsJson = tExtractionResults.ResultsAsJson; byte[] jsonFeatures = System.Text.Encoding.UTF8.GetBytes(tResultsAsJson.ToJson()); return jsonFeatures; } }
private void button1_Click(object sender, EventArgs e) { label2.Text = "正在生成shp文件..."; OleDbConnection conn_access = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + database_path + ";" + "Persist Security Info=False;"); conn_access.Open(); //获取表名 string sql_sheet = "select * from[" + comboBox1.Text + "]"; OleDbDataAdapter ada = new OleDbDataAdapter(sql_sheet, conn_access); DataTable dt = new DataTable(); ada.Fill(dt); string strShapeFolder = "E:\\毕业设计\\txttoshp"; string strShapeFile = "myshp.shp"; string shapeFileName = strShapeFolder + strShapeFile; IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(strShapeFolder, 0); IFeatureClass pFeatureClass; IPoint pPoint; IFields pFields = new Fields(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; IField pField = new Field(); IFieldEdit pFieldEdit = (IFieldEdit)pField; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); IGeographicCoordinateSystem pGCS; pGCS = spatialReferenceFactory.CreateGeographicCoordinateSystem ((int)esriSRGeoCS2Type.esriSRGeoCS_AuthalicSphere_GRS1980); pFieldEdit.Name_2 = "SHAPE"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDefEdit pGeoDef = new GeometryDef() as IGeometryDefEdit; IGeometryDefEdit pGeoDefEdit = (IGeometryDefEdit)pGeoDef; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; pGeoDefEdit.SpatialReference_2 = pGCS; pFieldsEdit.AddField(pField); pFieldEdit.GeometryDef_2 = pGeoDef; //添加字段 #region pField = new Field(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "X坐标值"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.AddField(pField); pField = new Field(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "Y坐标值"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.AddField(pField); pField = new Field(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "高程"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; pFieldsEdit.AddField(pField); #endregion //创建shp #region try { pFeatureClass = pFeatureWorkspace.CreateFeatureClass(strShapeFile, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", ""); } catch { pFeatureClass = pFeatureWorkspace.CreateFeatureClass(strShapeFile, pFields, null, null, esriFeatureType.esriFTSimple, "SHAPE", ""); } progressBar1.Value = 0; progressBar1.Maximum = dt.Rows.Count; for (int i = 0; i < dt.Rows.Count; i++) { pPoint = new ESRI.ArcGIS.Geometry.Point(); pPoint.X = Convert.ToDouble(dt.Rows[i][1]); pPoint.Y = Convert.ToDouble(dt.Rows[i][2]); pPoint.Z = Convert.ToDouble(dt.Rows[i][3]); IFeature pFeature = pFeatureClass.CreateFeature(); pFeature.Shape = pPoint; pFeature.set_Value(pFeature.Fields.FindField("X坐标值"), dt.Rows[i][1]); pFeature.set_Value(pFeature.Fields.FindField("Y坐标值"), dt.Rows[i][2]); pFeature.set_Value(pFeature.Fields.FindField("高程"), dt.Rows[i][3]); pFeature.Store(); progressBar1.Value++; } IFeatureLayer pFeaturelayer = new FeatureLayer(); pFeaturelayer.FeatureClass = pFeatureClass; pFeaturelayer.Name = "layer"; axMapControl1.Map.AddLayer(pFeaturelayer); #endregion }
protected ISpatialReference GetSpatialReferenceParam(JsonObject input, string name) { object outSRParam = null; if (input.TryGetObject(name, out outSRParam)) { ISpatialReferenceFactory factory = new SpatialReferenceEnvironment(); if (outSRParam is int) { return (factory as ISpatialReferenceFactory2).CreateSpatialReference((int)outSRParam); } else if (outSRParam is JsonObject) { JsonObject jsonParam = outSRParam as JsonObject; long? wkid; string wkt; if (jsonParam.TryGetAsLong("wkid", out wkid)) { return (factory as ISpatialReferenceFactory2).CreateSpatialReference((int)wkid.Value); } else if (jsonParam.TryGetString("wkt", out wkt)) { ISpatialReference result; int bytesRead; (factory as ISpatialReferenceFactory3).CreateESRISpatialReference(wkt, out result, out bytesRead); return result; } } } return null; }
/// <summary> /// 从Prj文件创建空间参考 /// </summary> /// <param name="strFile"></param> /// <returns></returns> public static ISpatialReference CreateSpatialReference(string strFile) { ISpatialReferenceFactory spatialRefFactory = new SpatialReferenceEnvironment(); return spatialRefFactory.CreateESRISpatialReferenceFromPRJFile(strFile); }
public static IGeometry ProjectGeometry(IGeometry pGeo) { //如果是地理坐标系,则投影到投影坐标系 if (pGeo.SpatialReference is IGeographicCoordinateSystem) { ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); IProjectedCoordinateSystem pcs = srFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_World_Mercator); //投影到 Mercator 坐标系 pGeo.Project(pcs); } return pGeo; }
private void processPointLayer(LayerProperties layerProps, geFolder folder) { //I have a point layer, and a kml folder :) IFeatureClass clasa = (layerProps.Layeru as IFeatureLayer).FeatureClass; //get acces to features IFeatureCursor featurele = clasa.Search(null, true); //if I have any features Point punct; IFeature currentFeature; //create coord system WGS 84 (Google earth) IGeographicCoordinateSystem gcs; SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); gcs = sre.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //create spatial reference ISpatialReference pointToSpatialReference; pointToSpatialReference = gcs; #region add points while ((currentFeature = featurele.NextFeature()) != null) { punct = currentFeature.Shape as Point; //coordinates and vertices double coordLat; double coordLong; //create a placemark for the point gePlacemark pmPoint = new gePlacemark(); pmPoint.StyleUrl = "#Shape2KMLGeneratedStyle"; //project point and get coordinates punct.Project(pointToSpatialReference); punct.QueryCoords(out coordLong, out coordLat); //add point geCoordinates coords; gePoint point; switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: if (layerProps.Field == "") { //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude); } else { int altitude; //if altitude is integer, this should work altitude = (int)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude); } point = new gePoint(coords); point.AltitudeMode = geAltitudeModeEnum.absolute; break; case AltitudeMode.clampToGround: coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong)); point = new gePoint(coords); point.AltitudeMode = geAltitudeModeEnum.clampToGround; break; case AltitudeMode.relativeToGround: if (layerProps.Field == "") { //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude); } else { int altitude; //if altitude is integer, this should work altitude = (int)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude); } point = new gePoint(coords); point.AltitudeMode = geAltitudeModeEnum.relativeToGround; break; default: point = null; break; } if (layerProps.DescField != "") { pmPoint.Description = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.DescField)).ToString(); } if (layerProps.NameField != "") { pmPoint.Name = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.NameField)).ToString(); } pmPoint.Geometry = point; folder.Features.Add(pmPoint); #endregion } }
private void processPolygonLayer(LayerProperties layerProps, geFolder folder) { //I have a polygon layer, and a kml folder :) IFeatureClass clasa = (layerProps.Layeru as IFeatureLayer).FeatureClass; //get acces to features IFeatureCursor featurele = clasa.Search(null, true); int nrFeature = clasa.FeatureCount(null); //if I have any features Polygon poligon; IFeature currentFeature; while ((currentFeature = featurele.NextFeature()) != null) { poligon = currentFeature.Shape as Polygon; //coordinates and vertices double coordLat; double coordLong; IEnumVertex colection = poligon.EnumVertices; IPoint polyVertex; //create coord system WGS 84 (Google earth) IGeographicCoordinateSystem gcs; SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); gcs = sre.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //create spatial reference ISpatialReference pointToSpatialReference; pointToSpatialReference = gcs; #region add points to polygon //create a placemark for the line gePlacemark pmPolygon = new gePlacemark(); pmPolygon.StyleUrl = "#Shape2KMLGeneratedStyle"; List <geCoordinates> polyCoords = new List <geCoordinates>(); int index1, index2; //iterate points... while (!colection.IsLastInPart()) { //create polygon from vertices colection.Next(out polyVertex, out index1, out index2); //project point and get coordinates polyVertex.Project(pointToSpatialReference); polyVertex.QueryCoords(out coordLong, out coordLat); //add point to line try { //create points for polygon based on altitude mode. switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: if (layerProps.Field == "") { //add point to line polyCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude)); } else { int altitude; //if altitude is integer, this should work altitude = (int)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point to line polyCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude)); } break; case AltitudeMode.clampToGround: //add point to line polyCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong))); break; case AltitudeMode.relativeToGround: if (layerProps.Field == "") { //add point to line polyCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude)); } else { float altitude; //if altitude is integer, this should work altitude = (float)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point to line polyCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude)); } break; default: break; } } catch (Exception) { MessageBox.Show("Altitude field is not a number value"); break; } } //create line from list of coords geOuterBoundaryIs outer = new geOuterBoundaryIs(new geLinearRing(polyCoords)); gePolygon poly = new gePolygon(outer); //and add it to document switch (layerProps.AltitudeMode) { //set altitude mode... case AltitudeMode.absolute: poly.AltitudeMode = geAltitudeModeEnum.absolute; break; case AltitudeMode.clampToGround: poly.AltitudeMode = geAltitudeModeEnum.clampToGround; break; case AltitudeMode.relativeToGround: poly.AltitudeMode = geAltitudeModeEnum.relativeToGround; break; default: break; } if (layerProps.DescField != "") { pmPolygon.Description = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.DescField)).ToString(); } if (layerProps.NameField != "") { pmPolygon.Name = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.NameField)).ToString(); } pmPolygon.Geometry = poly; folder.Features.Add(pmPolygon); #endregion } }
/// <summary> /// 绘制点缓冲 /// </summary> private void DrawBufferByPoint(ESRI.ArcGIS.ADF.Web.Geometry.Point adfPt) { //1.连接服务器 AGSServerConnection connection = new AGSServerConnection(); connection.Host = "localhost"; connection.Connect(); //2.获得服务器 IServerObjectManager pSom = connection.ServerObjectManager; IServerContext pSc = pSom.CreateServerContext("china", "MapServer");//服务名和类型 IMapServer mapServer = pSc.ServerObject as IMapServer; //3.使用服务器对象 几何对象转换 IMapServerObjects pMso = mapServer as IMapServerObjects; //ESRI.ArcGIS.Geometry.IGeometry comPt = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.ValueObjectToComObject(adfPt, pSc) // as ESRI.ArcGIS.Geometry.IGeometry;////ValueObjectToComObject(pnt, pSC); IPoint pt = new ESRI.ArcGIS.Geometry.PointClass(); pt.X = adfPt.X; pt.Y = adfPt.Y; ESRI.ArcGIS.Geometry.IGeometry comPt = pt; ESRI.ArcGIS.Geometry.SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); ISpatialReference pSR = sre.CreateGeographicCoordinateSystem(4326); comPt.SpatialReference = pSR; //绘制buffer ITopologicalOperator pTOPO = comPt as ITopologicalOperator; pTOPO.Simplify();//?? double bufDis = Map1.Extent.Width / 2; IPolygon bufPoly = pTOPO.Buffer(10) as IPolygon; bufPoly.Densify(0, 0); ESRI.ArcGIS.ADF.ArcGISServer.PolygonN valuePolyN = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.ComObjectToValueObject(bufPoly, pSc, typeof(ESRI.ArcGIS.ADF.ArcGISServer.PolygonN)) as ESRI.ArcGIS.ADF.ArcGISServer.PolygonN; ESRI.ArcGIS.ADF.Web.Geometry.Polygon adfPoly = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.ToAdfPolygon(valuePolyN) as ESRI.ArcGIS.ADF.Web.Geometry.Polygon; #region Densify ////***Densify // ESRI.ArcGIS.Geometry.IPointCollection com_pointcollection = (ESRI.ArcGIS.Geometry.IPointCollection)bufPoly; // ESRI.ArcGIS.ADF.Web.Geometry.PointCollection new_adf_pointcollection = ESRI.ArcGIS.ADF.Web.DataSources.ArcGISServer.Converter.ComObjectToValueObject(com_pointcollection, pSc, typeof(ESRI.ArcGIS.ADF.ArcGISServer.poly)); //ESRI.ArcGIS.ADF.Web.Geometry.PointCollection new_adf_pointcollection = new ESRI.ArcGIS.ADF.Web.Geometry.PointCollection(); //for (int i = 0; i < com_pointcollection.PointCount - 1; i++) //{ // ESRI.ArcGIS.ADF.Web.Geometry.Point new_adf_pt = new ESRI.ArcGIS.ADF.Web.Geometry.Point(); // new_adf_pt.X = com_pointcollection.get_Point(i).X; // new_adf_pt.Y = com_pointcollection.get_Point(i).Y; // new_adf_pointcollection.Add(new_adf_pt); //} //ESRI.ArcGIS.ADF.Web.Geometry.Ring new_adf_ring = new ESRI.ArcGIS.ADF.Web.Geometry.Ring(); //new_adf_ring.Points = new_adf_pointcollection; //ESRI.ArcGIS.ADF.Web.Geometry.RingCollection new_adf_ringcollection = new ESRI.ArcGIS.ADF.Web.Geometry.RingCollection(); //new_adf_ringcollection.Add(new_adf_ring); //ESRI.ArcGIS.ADF.Web.Geometry.Polygon new_adf_polygon = new ESRI.ArcGIS.ADF.Web.Geometry.Polygon(); //new_adf_polygon.Rings = new_adf_ringcollection; //ESRI.ArcGIS.ADF.Web.Geometry.Geometry geom = new_adf_polygon as ESRI.ArcGIS.ADF.Web.Geometry.Geometry; ////*******Densify #endregion ESRI.ArcGIS.ADF.Web.Geometry.Geometry geom = adfPoly as ESRI.ArcGIS.ADF.Web.Geometry.Geometry; GraphicElement geoEle = new GraphicElement(geom, System.Drawing.Color.Red); try { Map1.Zoom(adfPoly); } catch (Exception ex) { Console.WriteLine(ex); } geoEle.Symbol.Transparency = 50; IEnumerable gfc = Map1.GetFunctionalities(); MapResource gMap = null; foreach (IGISFunctionality gfunc in gfc) { if (gfunc.Resource.Name == "graph") { gMap = (MapResource)gfunc.Resource; break; } } if (gMap == null) { return; } ElementGraphicsLayer glayer = null; foreach (DataTable dt in gMap.Graphics.Tables) { if (dt is ElementGraphicsLayer) { glayer = dt as ElementGraphicsLayer; break; } } if (glayer == null) { glayer = new ElementGraphicsLayer(); gMap.Graphics.Tables.Add(glayer); } glayer.Clear();//清除数据 glayer.Add(geoEle); //4.释放服务器对象 pSc.ReleaseContext(); if (Map1.ImageBlendingMode == ImageBlendingMode.WebTier) { Map1.Refresh(); } else if (Map1.ImageBlendingMode == ImageBlendingMode.Browser) { Map1.RefreshResource(gMap.Name); } return; }
private ISpatialReference GetSpatialReference(ESRI.ArcGIS.Geometry.esriSRGeoCSType FactoryCode) { ISpatialReferenceFactory oSpatialReferenceFactory; IGeographicCoordinateSystem oGCS; try { oSpatialReferenceFactory = new SpatialReferenceEnvironment(); oGCS = oSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)FactoryCode); return oGCS; } catch { return null; } }
/// <summary> /// The add XY event layer. /// </summary> /// <param name="table"> /// The table. /// </param> /// <param name="query"> /// The query. /// </param> /// <param name="tweetShow"> /// The tweet show. /// </param> public static void AddXyEventLayer(ITable table, string query, bool tweetShow = true) { var mxdoc = ArcMap.Application.Document as IMxDocument; if (mxdoc != null) { var map = mxdoc.FocusMap; // Get the table named XYSample.txt var stTableCollection = map as IStandaloneTableCollection; // Get the table name object var dataset = table as IDataset; var tableName = dataset.FullName; // Specify the X and Y fields var xyEvent2FieldsProperties = new XYEvent2FieldsProperties() as IXYEvent2FieldsProperties; if (xyEvent2FieldsProperties != null) { xyEvent2FieldsProperties.XFieldName = "x"; xyEvent2FieldsProperties.YFieldName = "y"; xyEvent2FieldsProperties.ZFieldName = string.Empty; // Specify the projection var spatialReferenceFactory = new SpatialReferenceEnvironment() as ISpatialReferenceFactory; var projectedCoordinateSystem = spatialReferenceFactory.CreateGeographicCoordinateSystem( (int) esriSRGeoCSType.esriSRGeoCS_WGS1984); // Create the XY name object as set it's properties var xyEventSourceName = new XYEventSourceName() as IXYEventSourceName; xyEventSourceName.EventProperties = xyEvent2FieldsProperties; xyEventSourceName.SpatialReference = projectedCoordinateSystem; xyEventSourceName.EventTableName = tableName; IName xyName = xyEventSourceName as IName; IXYEventSource xyEventSource = xyName.Open() as IXYEventSource; // Create a new Map Layer IFeatureLayer featureLayer = new FeatureLayer() as IFeatureLayer; featureLayer.FeatureClass = xyEventSource as IFeatureClass; featureLayer.Name = query; // Add the layer extension (this is done so that when you edit // the layer's Source properties and click the Set Data Source // button, the Add XY Events Dialog appears) ILayerExtensions layerExtensions = featureLayer as ILayerExtensions; XYDataSourcePageExtension resPageExtension = new XYDataSourcePageExtension(); layerExtensions.AddExtension(resPageExtension); IGeoFeatureLayer geoLayer = (IGeoFeatureLayer) featureLayer; ISimpleRenderer simpleRenderer = (ISimpleRenderer) geoLayer.Renderer; var randomNumber = NumberRandom.Next(0, Colors.Count - 1); var color = Colors[randomNumber]; IRgbColor rgbColor = new RgbColorClass(); rgbColor.Blue = color.B; rgbColor.Red = color.R; rgbColor.Green = color.G; IMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass(); markerSymbol.Color = rgbColor; markerSymbol.Size = 5; simpleRenderer.Symbol = (ISymbol) markerSymbol; try { map.AddLayer(featureLayer); } catch (Exception error) { Console.WriteLine(error.Message); } } } }
private ESRI.ArcGIS.Geometry.ISpatialReference getWGS84() { ISpatialReferenceFactory oSpatialReferenceFactory; try { oSpatialReferenceFactory = new SpatialReferenceEnvironment(); return oSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); } catch //(Exception ex) { return GetSpatialReference(esriSRGeoCSType.esriSRGeoCS_WGS1984); } }
public IFeatureLayer CreateShapefile(string sNewLayerName, IArray pOldFeatures, IArray pNewGeometries, esriGeometryType nNewGeometryType) //增加一个新图层(如用于缓冲区等) { if (m_axMapControl == null || pOldFeatures.Count == 0 || pNewGeometries.Count == 0) { return(null); } //public static string GetWorkspacePath() //{ string sPath = "\\WSData"; if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } //return sPath; //} string MapPath = sPath; //改 bool bFileExisted = System.IO.File.Exists(MapPath + "\\" + sNewLayerName + ".shp"); if (bFileExisted && MessageBox.Show("The file is already existed, and do you want to create new one?", "Select one", MessageBoxButtons.YesNo) == DialogResult.Yes) { System.IO.File.Delete(MapPath + "\\" + sNewLayerName + ".shp"); System.IO.File.Delete(MapPath + "\\" + sNewLayerName + ".dbf"); System.IO.File.Delete(MapPath + "\\" + sNewLayerName + ".shx"); RemoveLayer(sNewLayerName); } IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFWS = pWorkspaceFactory.OpenFromFile(MapPath, 0) as IFeatureWorkspace; IFeatureLayer pFeatureLayer = new FeatureLayerClass(); //If file existed, directly load if (System.IO.File.Exists(MapPath + "\\" + sNewLayerName + ".shp")) { pFeatureLayer.FeatureClass = pFWS.OpenFeatureClass(sNewLayerName); pFeatureLayer.Name = pFeatureLayer.FeatureClass.AliasName; if (!IsLayerExisted(sNewLayerName)) { m_axMapControl.AddLayer(pFeatureLayer); m_axMapControl.Refresh(); } return(pFeatureLayer); } //Find fields from old feature IFeature pTmpFt = pOldFeatures.get_Element(0) as IFeature; IFields pTmpFields = pTmpFt.Fields; try { IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = fields as IFieldsEdit; //Shape field IField fd1 = new FieldClass(); IFieldEdit fiEdit1 = fd1 as IFieldEdit; fiEdit1.Name_2 = "Shape"; fiEdit1.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeomDef = new GeometryDefClass(); IGeometryDefEdit pGeomDefEdit = pGeomDef as IGeometryDefEdit; ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment(); pGeomDefEdit.GeometryType_2 = nNewGeometryType; //pGeomDefEdit.SpatialReference_2 = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference; fiEdit1.GeometryDef_2 = pGeomDef; fieldsEdit.AddField(fd1); for (int index = 0; index < pTmpFields.FieldCount; index++) { IField pField = pTmpFields.get_Field(index); if (IsSysField(pField.Name)) { continue; } IField fd = new FieldClass(); IFieldEdit fiEdit2 = fd as IFieldEdit; fiEdit2.Name_2 = pField.Name; fiEdit2.Type_2 = pField.Type; fiEdit2.Length_2 = pField.Length; fiEdit2.AliasName_2 = pField.AliasName; fieldsEdit.AddField(fd); } //Create feature class pFeatureLayer.FeatureClass = pFWS.CreateFeatureClass(sNewLayerName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", ""); pFeatureLayer.Name = sNewLayerName; //start editing IFeatureClass fc = pFeatureLayer.FeatureClass; IWorkspaceEdit w = (fc as IDataset).Workspace as IWorkspaceEdit; //w.StartEditing(true); //w.StartEditOperation(); IFeatureBuffer f = fc.CreateFeatureBuffer(); IFeatureCursor cur = fc.Insert(true); pTmpFields = fc.Fields; for (int i = 0; i < pOldFeatures.Count; i++) { IFeature pOldFeature = pOldFeatures.get_Element(0) as IFeature; f.Shape = pNewGeometries.get_Element(i) as IGeometry; for (int index = 0; index < pTmpFields.FieldCount; index++) { IField pField = pTmpFields.get_Field(index); if (IsSysField(pField.Name)) { continue; } int nOldIdx = pOldFeature.Fields.FindField(pField.Name); if (nOldIdx != -1) { object obj = pOldFeature.get_Value(nOldIdx); f.set_Value(index, obj); } } cur.InsertFeature(f); //flush per 1000 loops if (i % 1000 == 0) { cur.Flush(); } } cur.Flush(); //w.StopEditOperation(); //w.StopEditing(true); m_axMapControl.AddShapeFile(MapPath, sNewLayerName + ".shp"); m_axMapControl.Refresh(); } catch (Exception exception) { MessageBox.Show("Create" + sNewLayerName + " shapefile error:" + exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } return(pFeatureLayer); }
private void processPointLayer(LayerProperties layerProps, geFolder folder) { //I have a point layer, and a kml folder :) IFeatureClass clasa = (layerProps.Layeru as IFeatureLayer).FeatureClass; //get acces to features IFeatureCursor featurele = clasa.Search(null, true); //if I have any features Point punct; IFeature currentFeature; //create coord system WGS 84 (Google earth) IGeographicCoordinateSystem gcs; SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); gcs = sre.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //create spatial reference ISpatialReference pointToSpatialReference; pointToSpatialReference = gcs; #region add points while ((currentFeature = featurele.NextFeature()) != null) { punct = currentFeature.Shape as Point; //coordinates and vertices double coordLat; double coordLong; //create a placemark for the point gePlacemark pmPoint = new gePlacemark(); pmPoint.StyleUrl = "#Shape2KMLGeneratedStyle"; //project point and get coordinates punct.Project(pointToSpatialReference); punct.QueryCoords(out coordLong, out coordLat); //add point geCoordinates coords; gePoint point; switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: if (layerProps.Field == "") { //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude); } else { int altitude; //if altitude is integer, this should work altitude = (int)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude); } point = new gePoint(coords); point.AltitudeMode = geAltitudeModeEnum.absolute; break; case AltitudeMode.clampToGround: coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong)); point = new gePoint(coords); point.AltitudeMode = geAltitudeModeEnum.clampToGround; break; case AltitudeMode.relativeToGround: if (layerProps.Field == "") { //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude); } else { int altitude; //if altitude is integer, this should work altitude = (int)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point coords = new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude); } point = new gePoint(coords); point.AltitudeMode = geAltitudeModeEnum.relativeToGround; break; default: point = null; break; } if (layerProps.DescField != "") pmPoint.Description = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.DescField)).ToString(); if (layerProps.NameField != "") pmPoint.Name = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.NameField)).ToString(); pmPoint.Geometry = point; folder.Features.Add(pmPoint); #endregion } }
private void processRasterLayer(LayerProperties layerProps, geFolder folder) { IRasterLayer currentLayer = layerProps.Layeru as IRasterLayer; //get coordinates for image :D geAngle90 north; geAngle90 south; geAngle180 east; geAngle180 west; Double coordlat, coordlong; IPoint refPoint; refPoint = currentLayer.AreaOfInterest.LowerLeft; //coordinate system. IGeographicCoordinateSystem gcs; SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); //create coordinate system for WGS 84 (Google earth) gcs = sre.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //spatial reference ISpatialReference pointToSpatialReference; pointToSpatialReference = gcs; //project point to google earth projection refPoint.Project(pointToSpatialReference); //and get coordinates refPoint.QueryCoords(out coordlong, out coordlat); //left = west point and lower = south west = new geAngle180(coordlong); south = new geAngle90(coordlat); //and upper right refPoint = currentLayer.AreaOfInterest.UpperRight; //project point to google earth projection refPoint.Project(pointToSpatialReference); //x.ToString("{0:0.00}"); //and get coordinates refPoint.QueryCoords(out coordlong, out coordlat); //north and east north = new geAngle90(coordlat); east = new geAngle180(coordlong); //so I have all coordinates, now I create the overlay. geGroundOverlay.geLatLonBox latlonbox = new geGroundOverlay.geLatLonBox(north, south, east, west); geGroundOverlay overlay = new geGroundOverlay(latlonbox); //copy image to current folder... string name = System.IO.Path.GetDirectoryName(Path); name = System.IO.Path.Combine(name, currentLayer.Name); File.Copy(currentLayer.FilePath, name, true); // overlay.Icon.Href = currentLayer.FilePath; overlay.Icon = new geIcon(System.IO.Path.GetFileName(name)); overlay.Name = currentLayer.Name; overlay.Description = currentLayer.FilePath; overlay.StyleUrl = "#Shape2KMLGeneratedStyle"; switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: overlay.AltitudeMode = geAltitudeModeEnum.absolute; overlay.Altitude = layerProps.Altitude; //use altitude from field , do that later... break; case AltitudeMode.clampToGround: overlay.AltitudeMode = geAltitudeModeEnum.clampToGround; break; case AltitudeMode.relativeToGround: overlay.AltitudeMode = geAltitudeModeEnum.relativeToGround; overlay.Altitude = layerProps.Altitude; //use altitude from field , do that later... break; default: break; } //and add overlay to folder. THAT "simple" folder.Features.Add(overlay); }
private void processPolyLineLayer(LayerProperties layerProps, geFolder folder) { //I have a polyline layer, and a kml folder :) IFeatureClass clasa = (layerProps.Layeru as IFeatureLayer).FeatureClass; //get acces to features IFeatureCursor featurele = clasa.Search(null, true); int nrFeature = clasa.FeatureCount(null); //if I have any features Polyline curba; IFeature currentFeature; while ((currentFeature = featurele.NextFeature()) != null) { curba = currentFeature.Shape as Polyline; //coordinates and vertices double coordLat; double coordLong; IEnumVertex colection = curba.EnumVertices; IPoint lineVertex; //create coord system WGS 84 (Google earth) IGeographicCoordinateSystem gcs; SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); gcs = sre.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //create spatial reference ISpatialReference pointToSpatialReference; pointToSpatialReference = gcs; #region add points to polyline //create a placemark for the line gePlacemark pmLine = new gePlacemark(); pmLine.StyleUrl = "#Shape2KMLGeneratedStyle"; List<geCoordinates> lineCoords = new List<geCoordinates>(); int index1, index2; //iterate points... geLineString line = null; while (!colection.IsLastInPart()) { colection.Next(out lineVertex, out index1, out index2); //project point and get coordinates lineVertex.Project(pointToSpatialReference); lineVertex.QueryCoords(out coordLong, out coordLat); try { switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: if (layerProps.Field == "") { //add point to line lineCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude)); } else { int altitude; //if altitude is integer, this should work altitude = (int)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point to line lineCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude)); } break; case AltitudeMode.clampToGround: //add point to line lineCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong))); break; case AltitudeMode.relativeToGround: if (layerProps.Field == "") { //add point to line lineCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Altitude)); } else { float altitude; //if altitude is integer, this should work altitude = (float)currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.Field)); //add point to line lineCoords.Add(new geCoordinates(new geAngle90(coordLat), new geAngle180(coordLong), layerProps.Multiplier * altitude)); } break; default: break; } } catch (Exception) { MessageBox.Show("Altitude field is not a number value"); break; } } //create line from list of coords line = new geLineString(lineCoords); switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: line.AltitudeMode = geAltitudeModeEnum.absolute; break; case AltitudeMode.clampToGround: line.AltitudeMode = geAltitudeModeEnum.clampToGround; break; case AltitudeMode.relativeToGround: line.AltitudeMode = geAltitudeModeEnum.relativeToGround; break; default: break; } if (layerProps.DescField != "") pmLine.Description = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.DescField)).ToString(); if (layerProps.NameField != "") pmLine.Name = currentFeature.get_Value(currentFeature.Fields.FindField(layerProps.NameField)).ToString(); //and add it to document pmLine.Geometry = line; folder.Features.Add(pmLine); #endregion } }
public static IFeatureClass createNewEmptyShapefilePoint(string sP, string sN, int sPj) { String strFolder; String strName; const string strShapeFieldName = "Shape"; try { strFolder = sP; strName = sN; // Open the folder to contain the shapefile as a workspace IFeatureWorkspace pFWS; IWorkspaceFactory pWorkspaceFactory; pWorkspaceFactory = new ShapefileWorkspaceFactory(); pFWS = (IFeatureWorkspace)pWorkspaceFactory.OpenFromFile(strFolder, 0); // Set up a simple fields collection IFields pFields; IFieldsEdit pFieldsEdit; pFields = new Fields(); pFieldsEdit = (IFieldsEdit)pFields; IField pField; IFieldEdit pFieldEdit; // Make the shape field // it will need a geometry definition, with a spatial reference pField = new Field(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = strShapeFieldName; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; IGeometryDef pGeomDef; IGeometryDefEdit pGeomDefEdit; pGeomDef = new GeometryDef(); pGeomDefEdit = (IGeometryDefEdit)pGeomDef; pGeomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //Creates point shapefile if (sPj == 0) { pGeomDefEdit.SpatialReference_2 = new UnknownCoordinateSystemClass(); } else { ISpatialReferenceFactory2 pSpatRefFact; pSpatRefFact = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2; IProjectedCoordinateSystem pGeoCoordSys; pGeoCoordSys = pSpatRefFact.CreateProjectedCoordinateSystem(sPj); pGeomDefEdit.SpatialReference_2 = pGeoCoordSys; } pFieldEdit.GeometryDef_2 = pGeomDef; pFieldsEdit.AddField(pField); // Add another miscellaneous text field pField = new Field(); pFieldEdit = (IFieldEdit)pField; pFieldEdit.Length_2 = 25; pFieldEdit.Name_2 = "TextField"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; pFieldsEdit.AddField(pField); // Create the shapefile return pFWS.CreateFeatureClass(strName, pFields, null, null, esriFeatureType.esriFTSimple, strShapeFieldName, ""); } catch { return null; } }
private void PointToLatLong(IPoint Point, out double Latitude, out double Longitude) { Latitude = 39.759444; Longitude = -84.191667; try { SpatialReferenceEnvironment SpRFc = new SpatialReferenceEnvironment(); IGeographicCoordinateSystem GCS = SpRFc.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); ISpatialReference SpRefOutput = GCS; SpRefOutput.SetFalseOriginAndUnits(-180, -90, 1000000); IGeometry2 Geometry2 = (IGeometry2)Point; ISpatialReference SpRefInput = _map.SpatialReference; if (SpRefInput == null) return; Geometry2.SpatialReference = SpRefInput; Geometry2.Project(SpRefOutput); IPoint newPoint = (Point)Geometry2; Latitude = newPoint.Y; Longitude = newPoint.X; return; } catch (Exception) { } return; }
/// <summary> /// Handles the incoming rest requests /// </summary> /// <param name="boundVariables"> The bound variables. </param> /// <param name="operationInput"> The operation input. </param> /// <param name="outputFormat"> The output format. </param> /// <param name="requestProperties"> The request properties. </param> /// <param name="responseProperties"> The response properties. </param> /// <returns> </returns> /// <exception cref="System.ArgumentNullException"></exception> public static byte[] Handler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; var errors = new ErrorContainer(400); var wkid = 26912; const string featureClass = "SGID10.TRANSPORTATION.UDOTRoutes_LRS"; //pull out all the variables var x = operationInput.GetNumberValue("x"); var y = operationInput.GetNumberValue("y"); var wkidInput = operationInput.GetNumberValue("wkid", nullable: true); var bufferInput = operationInput.GetNumberValue("buffer", nullable: true); var includeRamps = operationInput.GetNumberValue("includeRamps", nullable: true); ISpatialReference newSpatialRefefence = null; ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironment(); if (wkidInput > 0) { wkid = Convert.ToInt32(wkidInput); } if (bufferInput < 1 || bufferInput > 200) { bufferInput = 100; } //reproject to our data's spatial reference if (wkid != 26912) { var isProjected = true; try { newSpatialRefefence = srFactory.CreateProjectedCoordinateSystem(wkid); } catch (ArgumentException) { isProjected = false; } if (!isProjected) { newSpatialRefefence = srFactory.CreateGeographicCoordinateSystem(wkid); } } var utm = srFactory.CreateProjectedCoordinateSystem(26912); IPoint point = new Point { X = x, Y = y, SpatialReference = utm }; //input is in different projection - reproject it if (wkid != 26912) { point = new Point { X = x, Y = y, SpatialReference = newSpatialRefefence }; point.Project(utm); } var bufferGeometry = CommandExecutor.ExecuteCommand( new BufferGeometryCommand(new GeometryContainer { Geometry = point }, bufferInput)); var sdeConnector = SdeConnectorFactory.Create(featureClass); if (sdeConnector == null) { errors.Add("{0} was not found in our database. ".With(featureClass) + "A valid example would be SGID10.BOUNDARIES.Counties."); } if (errors.HasErrors) { return Json(errors); } // ReSharper disable PossibleNullReferenceException because of returning errors if null var workspace = sdeConnector.Connect(); // ReSharper restore PossibleNullReferenceException var featureWorkspace = workspace as IFeatureWorkspace; if (featureWorkspace == null) { errors.Add("Error connecting to SDE."); return Json(errors); } var whereClause = "(LABEL LIKE '0%') AND RT_DIR <> 'B'"; //gets rid of ramps, collectors, and federal aid routes if (includeRamps < 1) { whereClause = whereClause.Insert(0, "LEN(LABEL) = 5 AND "); } var spatFilter = new SpatialFilterClass { SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects, Geometry = bufferGeometry, WhereClause = whereClause }; var lrsFeatureClass = featureWorkspace.OpenFeatureClass(featureClass.Trim()); var fCursor = lrsFeatureClass.Search(spatFilter, true); var candidates = new TopAndEqualMilepostCandidates(new ClosestMilepostComparer()); IFeature row; while ((row = fCursor.NextFeature()) != null) { var shape = row.ShapeCopy as IPolyline; if (shape == null) { continue; } IPoint hitPoint = new Point(); var hitDistance = -1d; var hitPartIndex = -1; var hitSegmentIndex = -1; var increasingSide = false; var hitTest = shape as IHitTest; if (hitTest == null) { continue; } var isHit = hitTest.HitTest(point, bufferInput, esriGeometryHitPartType.esriGeometryPartBoundary, hitPoint, ref hitDistance, ref hitPartIndex, ref hitSegmentIndex, ref increasingSide); if (!isHit) { continue; } var milepost = hitPoint.M; var distance = GetDistanceBetween(point, hitPoint); var routeName = CommandExecutor.ExecuteCommand(new GetValueForFieldCommand("LABEL", row.Fields, row)); candidates.Add(new ClosestMilepost(milepost, routeName.ToString(), distance, increasingSide)); Marshal.ReleaseComObject(row); Marshal.ReleaseComObject(shape); Marshal.ReleaseComObject(hitPoint); } Marshal.ReleaseComObject(lrsFeatureClass); Marshal.ReleaseComObject(workspace); Marshal.ReleaseComObject(spatFilter); return Json(candidates); }
private IProjectedCoordinateSystem GetProjectedCoordinateSystem() { //以下结果均不加带号 //if(北京54and三度带)2397+带号 4 //if(北京54and六度带)21400+带号 //if(西安80and三度带)2345+带号 4 //if(西安80and六度带)2325+带号 4 //创建投影坐标系 try { SpatialReferenceEnvironment spatialReferenceEnvironment = new SpatialReferenceEnvironment(); IProjectedCoordinateSystem projectedCoordinateSystem = new UnknownCoordinateSystemClass() as IProjectedCoordinateSystem; if (cbbCoordinateSystem.Text == "北京54坐标系" && cbbfendai.Text == "三度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(2397 + Convert.ToInt32(cbbnumber.Text)); } else if (cbbCoordinateSystem.Text == "北京54坐标系" && cbbfendai.Text == "六度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(21400 + Convert.ToInt32(cbbnumber.Text)); } else if (cbbCoordinateSystem.Text == "西安80坐标系" && cbbfendai.Text == "三度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(2345 + Convert.ToInt32(cbbnumber.Text)); } else if (cbbCoordinateSystem.Text == "西安80坐标系" && cbbfendai.Text == "六度带") { projectedCoordinateSystem = spatialReferenceEnvironment.CreateProjectedCoordinateSystem(2325 + Convert.ToInt32(cbbnumber.Text)); } return projectedCoordinateSystem; } catch (Exception ex) { string exception = ex.Message; MessageBox.Show(exception); return null; } }
private IFeatureClass CreateFeatureClassFromGeometry(IGeometry pGeometry, IFeatureWorkspace pOutFeatWorkspace, int wkid) { // thanks to http://bcdcspatial.blogspot.co.uk/2011/12/some-random-arcobjects-that-make.html // which was the only place i could find an answer to the problem I was having - the last // argument to createfeatureclass is null NOT an empty string try { IFields tFields = new FieldsClass() as IFields; IFieldsEdit tFieldsEdit = (IFieldsEdit)tFields; IField tShpFld = new Field(); IFieldEdit tShpEd = (IFieldEdit)tShpFld; tShpEd.Type_2 = esriFieldType.esriFieldTypeGeometry; tShpEd.Name_2 = "Shape"; IGeometryDef tGeomDef = new GeometryDef(); IGeometryDefEdit tGdEdit = (IGeometryDefEdit)tGeomDef; tGdEdit.GeometryType_2 = pGeometry.GeometryType; ISpatialReferenceFactory2 tSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2; ISpatialReference tSpatRef = tSRFac.CreateSpatialReference(wkid); ISpatialReferenceResolution tSpatRefRes = (ISpatialReferenceResolution)tSpatRef; tSpatRefRes.ConstructFromHorizon(); tGdEdit.SpatialReference_2 = tSpatRef; tShpEd.GeometryDef_2 = tGeomDef; tFieldsEdit.AddField(tShpFld); IObjectClassDescription tOCDesc = new FeatureClassDescription(); for (int i = 0; i < tOCDesc.RequiredFields.FieldCount; i++) { IField tField = tOCDesc.RequiredFields.get_Field(i); if (tFieldsEdit.FindField(tField.Name) == -1) { tFieldsEdit.AddField(tField); } } string tFCName = "tmp" + Guid.NewGuid().ToString("N"); IFeatureClass tFC = pOutFeatWorkspace.CreateFeatureClass( tFCName, tFields, null, null, esriFeatureType.esriFTSimple, "Shape", null); IFeature tGeomAsFeature = tFC.CreateFeature(); tGeomAsFeature.Shape = pGeometry; tGeomAsFeature.Store(); return tFC; } catch (Exception e) { Console.WriteLine(e.Message); logger.LogMessage(ServerLogger.msgType.error, "CreateFeatureClassFromGeometry", 99, "Could not create feature class " + e.Message + e.Source + e.StackTrace); throw e; } }
private void processRasterLayer(LayerProperties layerProps, geFolder folder) { IRasterLayer currentLayer = layerProps.Layeru as IRasterLayer; //get coordinates for image :D geAngle90 north; geAngle90 south; geAngle180 east; geAngle180 west; Double coordlat, coordlong; IPoint refPoint; refPoint = currentLayer.AreaOfInterest.LowerLeft; //coordinate system. IGeographicCoordinateSystem gcs; SpatialReferenceEnvironment sre = new SpatialReferenceEnvironment(); //create coordinate system for WGS 84 (Google earth) gcs = sre.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); //spatial reference ISpatialReference pointToSpatialReference; pointToSpatialReference = gcs; //project point to google earth projection refPoint.Project(pointToSpatialReference); //and get coordinates refPoint.QueryCoords(out coordlong, out coordlat); //left = west point and lower = south west= new geAngle180(coordlong); south = new geAngle90(coordlat); //and upper right refPoint = currentLayer.AreaOfInterest.UpperRight; //project point to google earth projection refPoint.Project(pointToSpatialReference); //x.ToString("{0:0.00}"); //and get coordinates refPoint.QueryCoords(out coordlong, out coordlat); //north and east north = new geAngle90(coordlat); east = new geAngle180(coordlong); //so I have all coordinates, now I create the overlay. geGroundOverlay.geLatLonBox latlonbox = new geGroundOverlay.geLatLonBox(north,south,east,west); geGroundOverlay overlay = new geGroundOverlay(latlonbox); //copy image to current folder... string name = System.IO.Path.GetDirectoryName(Path); name = System.IO.Path.Combine(name, currentLayer.Name); File.Copy(currentLayer.FilePath, name,true); // overlay.Icon.Href = currentLayer.FilePath; overlay.Icon = new geIcon(System.IO.Path.GetFileName(name)); overlay.Name = currentLayer.Name; overlay.Description = currentLayer.FilePath; overlay.StyleUrl = "#Shape2KMLGeneratedStyle"; switch (layerProps.AltitudeMode) { case AltitudeMode.absolute: overlay.AltitudeMode = geAltitudeModeEnum.absolute; overlay.Altitude = layerProps.Altitude; //use altitude from field , do that later... break; case AltitudeMode.clampToGround: overlay.AltitudeMode = geAltitudeModeEnum.clampToGround; break; case AltitudeMode.relativeToGround: overlay.AltitudeMode = geAltitudeModeEnum.relativeToGround; overlay.Altitude = layerProps.Altitude; //use altitude from field , do that later... break; default: break; } //and add overlay to folder. THAT "simple" folder.Features.Add(overlay); }
private void OpenCADFile(string filePath, string outputFilePath) { try { Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString()); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; String nameOfPath = System.IO.Path.GetDirectoryName(filePath); String nameOfCADFile = System.IO.Path.GetFileName(filePath); #region Open CAD Workspace from File Path //Set the workspace. ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory(); //Open the workspace. ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0); //Get the CADDrawingWorkspace. ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace; pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace; //Open the CadDrawingDataset. ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset; pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile); //Set the feature workspace. ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace; //Open the Feature Class. #endregion #region Getting Polygon, polylines, and annotation from Cad file ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polygon")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polyline")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Annotation")); #endregion UID CLSID_def = new UIDClass(); CLSID_def.Value = "esriGeoDatabase.Feature"; #region Creating Layers from Feature Classes //Polygons ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer.FeatureClass = pFeatClass; pFeatLayer.Name = "Polygons"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer; //Annotation ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Anno.FeatureClass = pFeatClass_Anno; pFeatLayer_Anno.Name = "Annotation"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno; //Polylines ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline; pFeatLayer_Plyline.Name = "Polylines"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline; #endregion #region Creating In-Memory workspace IWorkspaceFactory WF = new InMemoryWorkspaceFactory(); ESRI.ArcGIS.esriSystem.IName name = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName; IWorkspace inMemWorkspace = (IWorkspace)name.Open(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace; #endregion #region Creating new Fields IObjectClassDescription objectClassDescription = new FeatureClassDescription(); // create the fields using the required fields method IFields exportFields = new Fields(); IFieldsEdit fieldsEdit = (IFieldsEdit)exportFields; //OID IField field = new Field(); IField oidField = new Field(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class IGeometryDef geometryDef = new GeometryDef(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); ISpatialReference spatialReference = dataSet.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new Field(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); #endregion #region Creating New Shapefile for Final output UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; //using the In-Memory Workspace created above IFeatureClass output = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass polylines_cleaned = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); #endregion #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace Geoprocessor GP = new Geoprocessor(); //Polylines ESRI.ArcGIS.DataManagementTools.Append append = new Append(); append.inputs = pFeatClass_Plyline; append.target = polylines_cleaned; GP.Execute(append, null); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline); GC.Collect(); //Annotation append = new Append(); append.inputs = pFeatClass_Anno; append.target = annotation_cleaned; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno); GC.Collect(); //Polygons to output append = new Append(); append.inputs = pFeatClass; append.target = output; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass); GC.Collect(); #endregion #region Query Filter to Filter Layers string queryString = ""; //using the checked box list and comma seperated list to create where clause string //Adding Items from Check Box List foreach (var checkedItem in checkedListBox1.CheckedItems) { queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND "; } //Adding Items from Comma separated string if (textBox_commaSeparated.Text.Length > 0) { foreach (var item in textBox_commaSeparated.Text.Split(',')) { queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND "; } } //Removing Last 'AND' FROM queryString if (queryString.Length > 0) //if Atleast one item added { queryString = queryString.Remove(queryString.Length - 4); } IQueryFilter queryFilter = new QueryFilter(); queryFilter.SubFields = ""; if (queryString.Length > 0) { queryFilter.WhereClause = queryString; } else { queryFilter.WhereClause = "1=1"; } #endregion #region Removing Null Geometries string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", ""); Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From Polylines_cleaned IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false); IFeature feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat); GC.Collect(); Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From output Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString()); updateCursor = output.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString()); //From Annotation Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); updateCursor = annotation_cleaned.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); #endregion #region Convert lines feature class to feature Cursor IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false); #endregion #region Deleting all columns of polygons to match with output IFields _fieldsP = output.Fields; IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP; for (int i = 0; i < output.Fields.FieldCount; i++) { IField _field = output.Fields.get_Field(i); if (_field.Name != "Shape" && _field.Name != "FID") { output.DeleteField(_field); if (i < output.Fields.FieldCount) { i--; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP); GC.Collect(); #endregion #region Setting Envelop information IEnvelope envelop = new Envelope() as IEnvelope; IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset; envelop.SpatialReference = dataSet.SpatialReference; envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax); #endregion #region Construct Polygons from Lines Cursor (usting Feature Construct) IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction; ISelectionSet selectionSet = null; //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null); featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet); #endregion System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct); System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor); GC.Collect(); Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString()); #region SPATIAL JOIN GP = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin(); spatialJoin.join_features = annotation_cleaned; spatialJoin.target_features = output; spatialJoin.join_operation = "JOIN_ONE_TO_MANY"; spatialJoin.join_type = "KEEP_ALL"; spatialJoin.match_option = "CONTAINS"; spatialJoin.out_feature_class = outputFilePath; GP.Execute(spatialJoin, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned); GC.Collect(); #endregion #region Remove All Fields of Annotation except Text ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IFeatureWorkspace work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0); IFeatureClass output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath)); IFields _fields = output_AfterJoin_FClasss.Fields; IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields; for (int i = 0; i < _fields.FieldCount; i++) { IField _field = output_AfterJoin_FClasss.Fields.get_Field(i); if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID") { output_AfterJoin_FClasss.DeleteField(_field); i--; } else { if (field.Name == "Text_" || _field.Name == "Text") { IFieldEdit fieldEdit = (IFieldEdit)_field; fieldEdit.Name_2 = "PlotNumber"; fieldEdit.AliasName_2 = "PlotNumber"; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit); GC.Collect(); #endregion System.Windows.Forms.Cursor.Current = Cursors.Default; Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString()); MessageBox.Show("Import Complete!"); } catch { MessageBox.Show("Error Importing. Something wrong with the CAD File"); } }