esriJson和Geometry的相互转换
esriJson转Geometry
json字符串:“{“spatialReference”:{“wkid”:4490},“rings”:[[[122,37.1],[123,37.2],[123,37.3],[122,37.4],[122,37.5],[122,37.1]]]}”——瞎编的
常用的esriGeometryType:esriGeometryPolygon、esriGeometryPoint、esriGeometryPolyline
public static ESRI.ArcGIS.Geometry.IGeometry ConvertToGeometry(string strJson, esriGeometryType type,
bool bHasZ, bool bHasM)
{
bool bHasZ=false;
bool bHasM=false;
IJSONReader jsonReader = new JSONReaderClass();
jsonReader.ReadFromString(strJson);
JSONConverterGeometryClass jsonCon = new JSONConverterGeometryClass();
return jsonCon.ReadGeometry(jsonReader, type, bHasZ, bHasM);
}
问:假如json字符串不带spatialReference,并且数据本身是自定义的坐标系,如何给Geometry添加坐标信息?
答:json转Geometry的时候不提供spatialReference,转成Geometry后读取prj文件,根据prj文件获取spatialReference赋给Geometry
注意:如果上传的坐标串是逆时针的,那么上述方法转换得到的Geometry是空的(IsEmpty),需要对转换后的Geometry进行拓扑闭合
//json转Geometry
IGeometry geometry = ConvertToGeometry(json, esriGeometryType.esriGeometryPolygon);
//使Geometry拓扑闭合
ITopologicalOperator top = geometry as ITopologicalOperator;
top.Simplify();
Geometry转esriJson
public static string ConvertGeometryToJson(ESRI.ArcGIS.Geometry.IGeometry geometry,
bool isGeneralize = false)
{
string geomJsonStr = null;
try
{
ITopologicalOperator topoGeom = geometry as ITopologicalOperator;
topoGeom.Simplify();
if (isGeneralize)//是否泛化--什么时候需要泛化?
{
ISpatialReference spatialReference = geometry.SpatialReference;
enumSpatialRelType spatialRelType = SpatialRefOpt.GetSpatialRelType(spatialReference);
double offset = 0.001;
if (spatialRelType == enumSpatialRelType.GCS) offset = 0.001;
IPolycurve polycurve = geometry as IPolycurve;
polycurve.Generalize(offset);
}
ESRI.ArcGIS.esriSystem.IJSONWriter jsonWriter = new ESRI.ArcGIS.esriSystem.JSONWriterClass();
jsonWriter.WriteToString();
ESRI.ArcGIS.Geometry.JSONConverterGeometryClass jsonCon = new ESRI.ArcGIS.Geometry.JSONConverterGeometryClass();
jsonCon.WriteGeometry(jsonWriter, null, geometry, false);
geomJsonStr = Encoding.UTF8.GetString(jsonWriter.GetStringBuffer());
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine("\nConvertGeometryToJson::error::" + ex.Source + ".\n" + ex.ToString());
}
return geomJsonStr;
}