arcEngine开发之根据点坐标创建Shp图层

思路

根据点坐标创建Shapefile文件大致思路是这样的:
(1)创建表的工作空间,通过 IField、IFieldsEdit、IField 等接口创建属性字段,添加到要素集中。
(2)根据获取点的坐标信息为属性字段赋值,进而得到图层的要素集

必要元素

将创建 Shapefile 文件代码封装成方法如下,这里说明一下创建一 个 Shapefile 文件至少需要配置的元素:
(1)首先,当我们创建一个shp文件时,ArcMap会自动生成如下字段:
这里写图片描述
其中shp表示几何字段,我们需要设置 IFile.NameIField.Type 来定义这个字段
(2)其次,如果我们没有设置空间坐标时,会弹出如下对话框:
这里写图片描述
因此第二步我们需要设置shp文件的空间坐标。 这里是通过设置 IField.GeometryDef 实现的。这个属性其实是IGeometryDef接口,通过对这个接口的 GeometryTypeSpatialReference 属性进行设置即可完成对空间坐标的定义。

代码说明

封装的这段代码里,发现对于 IFeatureIFeatureClass 还是不怎么理解,通过查阅资料发现, IFeature 继承自 IRowIObject ,由于IFeature 可以通过 IFeatureClass 创建而成,因此可以知道的是IFeatureClass 是和ITable处于同一个级别,IFeature 相当于是属性表中的一行。

代码

private IFeatureLayer CreateShpFromPoints(List<CPoint> cPointList,string filePath)
{
	//其中,CPoint为存储点数据的结构体,包含name,x,y属性
	//利用IWorkspaceFactory打开工作空间
	int index = filePath.LastIndexOf('\\');
    string folder = filePath.Substring(0, index);
    string shapeName = filePath.Substring(index + 1);  
    IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass();
	IFeatureWorkspace pFWS = (IFeatureWorkspace)pWSF.OpenFromFile(folder, 0);

	//创建字段编辑所需要的接口
    IFields pFields = new FieldsClass();
    IFieldsEdit pFieldsEdit;
    pFieldsEdit = (IFieldsEdit)pFields;

	//给字段属性、类型赋值
    IField pField = new FieldClass();
    IFieldEdit pFieldEdit = (IFieldEdit)pField;
    pFieldEdit.Name_2 = "Shape";
    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
    IGeometryDef pGeometryDef = new GeometryDefClass();
    IGeometryDefEdit pGDefEdit = (IGeometryDefEdit)pGeometryDef;
    pGDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
    //定义坐标系
    ISpatialReferenceFactory pSRF = new SpatialReferenceEnvironmentClass();
    ISpatialReference pSpatialReference = pSRF.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954);
    pGDefEdit.SpatialReference_2 = pSpatialReference;

    pFieldEdit.GeometryDef_2 = pGeometryDef;
    pFieldsEdit.AddField(pField);
     
    IFeatureClass pFeatureClass;
    pFeatureClass = pFWS.CreateFeatureClass(shapeName, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

     IPoint pPoint = new PointClass();
     for (int j = 0; j < cPointList.Count; j++)
     {
         pPoint.X = cPointList[j].X;
         pPoint.Y = cPointList[j].Y;

         IFeature pFeature = pFeatureClass.CreateFeature();
         pFeature.Shape = pPoint;
         pFeature.Store();
     }
       
     IFeatureLayer pFeatureLayer = new FeatureLayerClass();
     pFeatureLayer.Name = shapeName;
     pFeatureLayer.FeatureClass = pFeatureClass;
     return pFeatureLayer;
}
posted @ 2018-03-05 09:42  firepation  阅读(710)  评论(0编辑  收藏  举报