Construct a SpatialReference - from a well-known ID
// Use a builder convenience method or use a builder constructor.// SpatialReferenceBuilder convenience methods don't need to run on the MCT.SpatialReferencesr3857=SpatialReferenceBuilder.CreateSpatialReference(3857);// SpatialReferenceBuilder constructors need to run on the MCT.ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(SpatialReferenceBuildersrBuilder=newSpatialReferenceBuilder(3857)){// do something with the buildersr3857=srBuilder.ToSpatialReference();}});
Construct a SpatialReference - from a string
// Use a builder convenience method or use a builder constructor.stringwkt="GEOGCS[\"MyGCS84\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Radian\",1.0]]";// SpatialReferenceBuilder convenience methods don't need to run on the MCT.SpatialReferencesr=SpatialReferenceBuilder.CreateSpatialReference(wkt);// SpatialReferenceBuilder constructors need to run on the MCT.ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(SpatialReferenceBuilderbuilder=newSpatialReferenceBuilder(wkt)){// do something with the builderSpatialReferenceanotherSR=builder.ToSpatialReference();}});
Construct a SpatialReference with a vertical coordinate system - from well-known IDs
// Use a builder convenience method or use a builder constructor.// see a list of vertical coordinate systems at http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Vertical_coordinate_systems/02r3000000rn000000/// Builder convenience methods don't need to run on the MCT.// 4326 = GCS_WGS_1984// 115700 = vertical WGS_1984SpatialReferencesr4326_115700=SpatialReferenceBuilder.CreateSpatialReference(4326,115700);// SpatialReferenceBuilder constructors need to run on the MCT.ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(SpatialReferenceBuildersb=newSpatialReferenceBuilder(4326,115700)){// SpatialReferenceBuilder properties// sb.wkid == 4326// sb.Wkt == "GEOGCS["MyGCS84",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT[\"Radian\",1.0]]"// sb.name == GCS_WGS_1984// sb.vcsWkid == 115700// sb.VcsWkt == "VERTCS["WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PARAMETER["Vertical_Shift",0.0],PARAMETER["Direction",1.0],UNIT["Meter",1.0]]// do something with the buildersr4326_115700=sb.ToSpatialReference();}});
Construct a SpatialReference with a vertical coordinate system - from a string
// Use a builder convenience method or use a builder constructor.// custom VCS - use vertical shift of -1.23 instead of 0stringcustom_vWkt=@"VERTCS[""SHD_height"",VDATUM[""Singapore_Height_Datum""],PARAMETER[""Vertical_Shift"",-1.23],PARAMETER[""Direction"",-1.0],UNIT[""Meter"",1.0]]";// Builder convenience methods don't need to run on the MCT.SpatialReferencesr4326_customVertical=SpatialReferenceBuilder.CreateSpatialReference(4326,custom_vWkt);// SpatialReferenceBuilder properties// sr4326_customVertical.wkid == 4326// sr4326_customVertical.vert_wkid == 0// sr4326_customVertical.vert_wkt == custom_vWkt// sr4326_customVertical.hasVcs == true// SpatialReferenceBuilder constructors need to run on the MCT.ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(SpatialReferenceBuildersb=newSpatialReferenceBuilder(4326,custom_vWkt)){// do something with the buildersr4326_customVertical=sb.ToSpatialReference();}});
Construct a SpatialReference with a custom PCS - from a string
// Use a builder convenience method or use a builder constructor.// Custom PCS, Predefined GCSstringcustomWkt="PROJCS[\"WebMercatorMile\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Mile\",1609.344000614692]]";// Builder convenience methods don't need to run on the MCT.SpatialReferencespatialReference=SpatialReferenceBuilder.CreateSpatialReference(customWkt);// SpatialReferenceBuilder properties// spatialReference.Wkt == customWkt// spatialReference.Wkid == 0// spatialReference.VcsWkid == 0// spatialReference.GcsWkid == 4326SpatialReferencegcs=spatialReference.Gcs;// gcs.Wkid == 4326// gcs.IsGeographic == true// spatialReference.GcsWkt == gcs.Wkt// SpatialReferenceBuilder constructors need to run on the MCT.ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{using(SpatialReferenceBuildersb=newSpatialReferenceBuilder(customWkt)){// do something with the builderspatialReference=sb.ToSpatialReference();}});
SpatialReference Properties
// SpatialReferenceBuilder constructors need to run on the MCT.ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// use the builder constructorusing(SpatialReferenceBuildersrBuilder=newSpatialReferenceBuilder(3857)){// spatial reference builder propertiesintbuilderWkid=srBuilder.Wkid;stringbuilderWkt=srBuilder.Wkt;stringbuilderName=srBuilder.Name;doublexyScale=srBuilder.XYScale;doublexyTolerance=srBuilder.XYTolerance;doublexyResolution=srBuilder.XYResolution;Unitunit=srBuilder.Unit;doublezScale=srBuilder.ZScale;doublezTolerance=srBuilder.ZTolerance;UnitzUnit=srBuilder.ZUnit;doublemScale=srBuilder.MScale;doublemTolerance=srBuilder.MTolerance;doublefalseX=srBuilder.FalseX;doublefalseY=srBuilder.FalseY;doublefalseZ=srBuilder.FalseZ;doublefalseM=srBuilder.FalseM;// get the spatial referenceSpatialReferencesr3857=srBuilder.ToSpatialReference();// spatial reference propertiesintsrWkid=sr3857.Wkid;stringsrWkt=sr3857.Wkt;stringsrName=sr3857.Name;xyScale=sr3857.XYScale;xyTolerance=sr3857.XYTolerance;xyResolution=sr3857.XYResolution;unit=sr3857.Unit;zScale=sr3857.ZScale;zTolerance=sr3857.ZTolerance;zUnit=sr3857.ZUnit;mScale=sr3857.MScale;mTolerance=sr3857.MTolerance;falseX=sr3857.FalseX;falseY=sr3857.FalseY;falseZ=sr3857.FalseZ;falseM=sr3857.FalseM;boolhasVcs=sr3857.HasVcs;}});
SpatialReference WKT2
SpatialReferencesr=SpatialReferences.WebMercator;// Get Esri WKTstringwkt=sr.Wkt;/* PROJCS["WGS_1984_Web_Mercator_Auxiliary_Sphere", GEOGCS["GCS_WGS_1984", DATUM["D_WGS_1984", SPHEROID["WGS_1984", 6378137.0, 298.257223563]], PRIMEM["Greenwich", 0.0], UNIT["Degree", 0.0174532925199433]], PROJECTION["Mercator_Auxiliary_Sphere"], PARAMETER["False_Easting", 0.0], PARAMETER["False_Northing", 0.0], PARAMETER["Central_Meridian", 0.0], PARAMETER["Standard_Parallel_1", 0.0], PARAMETER["Auxiliary_Sphere_Type", 0.0], UNIT["Meter", 1.0]]*/// Get OGC WKT2stringwkt2=sr.GetWkt2(WktFormatMode.None);/* PROJCRS["WGS_1984_Web_Mercator_Auxiliary_Sphere", BASEGEOGCRS["GCS_WGS_1984", DYNAMIC[FRAMEEPOCH[1990.5], MODEL["AM0-2"]], DATUM["D_WGS_1984", ELLIPSOID["WGS_1984", 6378137.0, 298.257223563, LENGTHUNIT["Meter", 1.0]]], PRIMEM["Greenwich", 0.0, ANGLEUNIT["Degree", 0.0174532925199433]], CS[ellipsoidal, 2], AXIS["Latitude (lat)", north, ORDER[1]], AXIS["Longitude (lon)", east, ORDER[2]], ANGLEUNIT["Degree", 0.0174532925199433]], CONVERSION["Mercator_Auxiliary_Sphere", METHOD["Mercator_Auxiliary_Sphere"], PARAMETER["False_Easting", 0.0, LENGTHUNIT["Meter", 1.0]], PARAMETER["False_Northing", 0.0, LENGTHUNIT["Meter", 1.0]], PARAMETER["Central_Meridian", 0.0, ANGLEUNIT["Degree", 0.0174532925199433]], PARAMETER["Standard_Parallel_1", 0.0, ANGLEUNIT["Degree", 0.0174532925199433]], PARAMETER["Auxiliary_Sphere_Type", 0.0]], CS[Cartesian, 2], AXIS["Easting (X)", east, ORDER[1]], AXIS["Northing (Y)", north, ORDER[2]], LENGTHUNIT["Meter", 1.0]]*/// You can create a spatial reference with the Esri WKT string or the OCG WKT2 stringsr=SpatialReferenceBuilder.CreateSpatialReference(wkt2);// Get OGC WKT2 including authority in top-level objects// In this case the authority is written as ID["EPSG",3857]wkt2=sr.GetWkt2(WktFormatMode.AuthorityTop);/* PROJCRS["WGS_1984_Web_Mercator_Auxiliary_Sphere", BASEGEOGCRS["GCS_WGS_1984", DYNAMIC[FRAMEEPOCH[1990.5],MODEL["AM0-2"]], DATUM["D_WGS_1984", ELLIPSOID["WGS_1984",6378137.0,298.257223563,LENGTHUNIT["Meter",1.0]]], PRIMEM["Greenwich",0.0,ANGLEUNIT["Degree",0.017453292519943295]], CS[ellipsoidal,2], AXIS["Latitude (lat)",north,ORDER[1]], AXIS["Longitude(lon)",east,ORDER[2]], ANGLEUNIT["Degree",0.017453292519943295]], CONVERSION["Mercator_Auxiliary_Sphere", METHOD["Mercator_Auxiliary_Sphere"], PARAMETER["False_Easting",0.0,LENGTHUNIT["Meter",1.0]], PARAMETER["False_Northing",0.0,LENGTHUNIT["Meter",1.0]], PARAMETER["Central_Meridian",0.0,ANGLEUNIT["Degree",0.017453292519943295]], PARAMETER["Standard_Parallel_1",0.0,ANGLEUNIT["Degree",0.017453292519943295]], PARAMETER["Auxiliary_Sphere_Type",0.0]], CS[Cartesian,2], AXIS["Easting (X)",east,ORDER[1]], AXIS["Northing (Y)",north,ORDER[2]], LENGTHUNIT["Meter",1.0], ID["EPSG",3857]]*/// Get OGC WKT2 including authority in all objects// Authority is written as ID["ESPG",<id>] or ID["Esri",<id>]wkt2=sr.GetWkt2(WktFormatMode.AuthorityAll);/* PROJCRS["WGS_1984_Web_Mercator_Auxiliary_Sphere", BASEGEOGCRS["GCS_WGS_1984", DYNAMIC[FRAMEEPOCH[1990.5],MODEL["AM0-2"]], DATUM["D_WGS_1984", ELLIPSOID["WGS_1984",6378137.0,298.257223563,LENGTHUNIT["Meter",1.0,ID["EPSG",9001]],ID["EPSG",7030]], ID["EPSG",6326]], PRIMEM["Greenwich",0.0,ANGLEUNIT["Degree",0.017453292519943295,ID["EPSG",9102]],ID["EPSG",8901]], CS[ellipsoidal,2], AXIS["Latitude (lat)",north,ORDER[1]], AXIS["Longitude(lon)",east,ORDER[2]], ANGLEUNIT["Degree",0.017453292519943295,ID["EPSG",9102]],ID["EPSG",4326]], CONVERSION["Mercator_Auxiliary_Sphere", METHOD["Mercator_Auxiliary_Sphere",ID["Esri",43104]], PARAMETER["False_Easting",0.0,LENGTHUNIT["Meter",1.0,ID["EPSG",9001]],ID["Esri",100001]], PARAMETER["False_Northing",0.0,LENGTHUNIT["Meter",1.0,ID["EPSG",9001]],ID["Esri",100002]], PARAMETER["Central_Meridian",0.0,ANGLEUNIT["Degree",0.017453292519943295,ID["EPSG",9102]],ID["Esri",100010]], PARAMETER["Standard_Parallel_1",0.0,ANGLEUNIT["Degree",0.017453292519943295,ID["EPSG",9102]],ID["Esri",100025]], PARAMETER["Auxiliary_Sphere_Type",0.0,ID["Esri",100035]]], CS[Cartesian,2], AXIS["Easting(X)",east,ORDER[1]], AXIS["Northing (Y)",north,ORDER[2]], LENGTHUNIT["Meter",1.0,ID["EPSG",9001]], ID["EPSG",3857]]*/
Determine grid convergence for a SpatialReference at a given point
Coordinate2Dcoordinate=newCoordinate2D(10,30);doubleangle=SpatialReferences.WGS84.GetConvergenceAngle(coordinate);// angle = 0SpatialReferencesrUTM30N=SpatialReferenceBuilder.CreateSpatialReference(32630);coordinate.X=500000;coordinate.Y=550000;angle=srUTM30N.GetConvergenceAngle(coordinate);// angle = 0MapPointpointWGS84=MapPointBuilderEx.CreateMapPoint(10,50,SpatialReferences.WGS84);MapPointpointUTM30N=GeometryEngine.Instance.Project(pointWGS84,srUTM30N)asMapPoint;coordinate=(Coordinate2D)pointUTM30N;// get convergence angle and convert to degreesangle=srUTM30N.GetConvergenceAngle(coordinate)*180/Math.PI;// angle = 10.03
Datum
varcimMapDefinition=MapView.Active.Map.GetDefinition();// use if map's sr does not have a vertical coordinate systemvardatumTransformations=cimMapDefinition.DatumTransforms;// use if map's sr has a vertical coordinate systemvarhvDatumTransformations=cimMapDefinition.HVDatumTransforms;
Coordinate2Dv=newCoordinate2D(0,1);// v.Magnitude = 1Coordinate2Dother=newCoordinate2D(-1,0);doubledotProduct=v.DotProduct(other);// dotProduct = 0Coordinate2Dw=v+other;// w = (-1, 1)w+=other;// w = (-2, 1)w-=other;// w = (-1, 1)w=v;w.Rotate(Math.PI,other);// w = (-2, -1)w=other;w.Scale(-4);// w = (4, 0)// w.Magnitude = 4w.Move(-1,4);// w = (3, 4)// w.Magnitude = 5w.Move(-6,-1);Tuple<double,double>components=w.QueryComponents();// components = (-3, 3)// w.Magnitude = 3 * Math.Sqrt(2)Coordinate2DunitVector=w.GetUnitVector();// w = (-Math.Sqrt(2) / 2, Math.Sqrt(2) / 2)// w.Magnitude = 1w.SetComponents(3,4);
Builder Properties
Builder Properties
// list of pointsList<MapPoint>points=newList<MapPoint>{MapPointBuilderEx.CreateMapPoint(0,0,2,3,1),MapPointBuilderEx.CreateMapPoint(1,1,5,6),MapPointBuilderEx.CreateMapPoint(2,1,6),MapPointBuilderEx.CreateMapPoint(0,0)};// will have attributes because it is created with convenience methodPolylinepolylineWithAttrs=PolylineBuilderEx.CreatePolyline(points);boolhasZ=polylineWithAttrs.HasZ;// hasZ = trueboolhasM=polylineWithAttrs.HasM;// hasM = trueboolhasID=polylineWithAttrs.HasID;// hasID = true// will not have attributes because it is specified as a parameterPolylinepolylineWithoutAttrs=PolylineBuilderEx.CreatePolyline(points,AttributeFlags.None);hasZ=polylineWithoutAttrs.HasZ;// hasZ = falsehasM=polylineWithoutAttrs.HasM;// hasM = falsehasID=polylineWithoutAttrs.HasID;// hasID = false// will have attributes because it is created with convenience methodPolygonpolygonWithAttrs=PolygonBuilderEx.CreatePolygon(points);hasZ=polygonWithAttrs.HasZ;// hasZ = truehasM=polygonWithAttrs.HasM;// hasM = truehasID=polygonWithAttrs.HasID;// hasID = true// will not have attributes because it is specified as a parameterPolygonpolygonWithoutAttrs=PolygonBuilderEx.CreatePolygon(points,AttributeFlags.None);hasZ=polygonWithoutAttrs.HasZ;// hasZ = falsehasM=polygonWithoutAttrs.HasM;// hasM = falsehasID=polygonWithoutAttrs.HasID;// hasID = false// will not have attributes because it is specified as a parameterPolylineBuilderExpolylineB=newPolylineBuilderEx(points,AttributeFlags.None);hasZ=polylineB.HasZ;// hasZ = falsehasM=polylineB.HasM;// hasM = falsehasID=polylineB.HasID;// hasID = false// will have attributes because it is passed an attributed polylinepolylineB=newPolylineBuilderEx(polylineWithAttrs);hasZ=polylineB.HasZ;// hasZ = truehasM=polylineB.HasM;// hasM = truehasID=polylineB.HasID;// hasID = true// will not have attributes because it is passed a non-attributed polylinepolylineB=newPolylineBuilderEx(polylineWithoutAttrs);hasZ=polylineB.HasZ;// hasZ = falsehasM=polylineB.HasM;// hasM = falsehasID=polylineB.HasID;// hasID = false// will not have attributes because it is specified as a parameterPolygonBuilderExpolygonB=newPolygonBuilderEx(points,AttributeFlags.None);hasZ=polygonB.HasZ;// hasZ = falsehasM=polygonB.HasM;// hasM = falsehasID=polygonB.HasID;// hasID = false// will have attributes because it is passed an attributed polygonpolygonB=newPolygonBuilderEx(polygonWithAttrs);hasZ=polygonB.HasZ;// hasZ = truehasM=polygonB.HasM;// hasM = truehasID=polygonB.HasID;// hasID = true// will not have attributes because it is passed a non-attributed polygonpolygonB=newPolygonBuilderEx(polygonWithoutAttrs);hasZ=polygonB.HasZ;// hasZ = truehasM=polygonB.HasM;// hasM = truehasID=polygonB.HasID;// hasID = true
MapPoint
Construct a MapPoint
// Use a builder convenience method or use a builder constructor.// Create a 2D point without a spatial referenceMapPointpoint2D=MapPointBuilderEx.CreateMapPoint(1,2);SpatialReferencesr=point2D.SpatialReference;// sr = nullboolhasZ=point2D.HasZ;// hasZ = falseboolhasM=point2D.HasM;// hasM = falseboolhasID=point2D.HasID;// hasID = falsedoublex=point2D.X;// x = 1doubley=point2D.Y;// y = 2doublez=point2D.Z;// z = 0 default valuedoublem=point2D.M;// m is NaN default valuedoubleid=point2D.ID;// id = 0 default value// Or use a builderEx which doesn't need to run on the MCT. MapPointBuilderExbuilderEx=newMapPointBuilderEx(1,2);// do something with the builderbuilderEx.Y=3;point2D=builderEx.ToGeometry();sr=point2D.SpatialReference;// sr = nullhasZ=point2D.HasZ;// hasZ = falsehasM=point2D.HasM;// hasM = falsehasID=point2D.HasID;// hasID = falsex=point2D.X;// x = 1y=point2D.Y;// y = 3z=point2D.Z;// z = 0 default valuem=point2D.M;// m is NaN default valueid=point2D.ID;// id = 0 default value// Create a 2D point with a spatial referenceSpatialReferencespatialReference=SpatialReferenceBuilder.CreateSpatialReference(4269);point2D=MapPointBuilderEx.CreateMapPoint(1,2,spatialReference);sr=point2D.SpatialReference;// sr != nullintwkid=sr.Wkid;// wkid = 4269// Or use a builderbuilderEx=newMapPointBuilderEx(1,2,spatialReference);// Do something with the builderbuilderEx.SetValues(3,5);point2D=builderEx.ToGeometry();sr=point2D.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 4269x=point2D.X;// x = 3y=point2D.Y;// y = 5// Change the spatial reference of the builderbuilderEx.SpatialReference=SpatialReferences.WGS84;point2D=builderEx.ToGeometry();sr=point2D.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 4326x=point2D.X;// x = 3y=point2D.Y;// y = 5// Create a 3D point with MMapPointpointZM=MapPointBuilderEx.CreateMapPoint(1,2,3,4);sr=pointZM.SpatialReference;// sr = nullhasZ=pointZM.HasZ;// hasZ = truehasM=pointZM.HasM;// hasM = truehasID=pointZM.HasID;// hasID = falsex=pointZM.X;// x = 1y=pointZM.Y;// y = 2z=pointZM.Z;// z = 3m=pointZM.M;// m = 4id=pointZM.ID;// id = 0 default value// Create a 3D point with M and a spatial referencepointZM=MapPointBuilderEx.CreateMapPoint(1,2,3,4,spatialReference);sr=pointZM.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 4269// Create a point from another point in three waysMapPointclone=pointZM.Clone()asMapPoint;// Has the same values including the spatial reference as pointZMMapPointanotherZM=MapPointBuilderEx.CreateMapPoint(pointZM);// Has the same values including the spatial reference as pointZMbuilderEx=newMapPointBuilderEx(pointZM);// Has the same values including the spatial reference as pointZM// Do something with the builderbuilderEx.HasM=false;builderEx.ID=7;// Setting the id also sets HasID = trueMapPointpointZId=builderEx.ToGeometry();sr=pointZId.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 4269hasZ=pointZId.HasZ;// hasZ = truehasM=pointZId.HasM;// hasM = falsehasID=pointZId.HasID;// hasID = truex=pointZId.X;// x = 1y=pointZId.Y;// y = 2z=pointZId.Z;// z = 3m=pointZId.M;// m is NaN, default valueid=pointZId.ID;// id = 7// Create a point with Z, M, and ID-valuesMapPointpointZMId=MapPointBuilderEx.CreateMapPoint(1,2,3,4,5,spatialReference);sr=pointZMId.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 4269hasZ=pointZMId.HasZ;// hasZ = truehasM=pointZMId.HasM;// hasM = truehasID=pointZMId.HasID;// hasID = truex=pointZMId.X;// x = 1y=pointZMId.Y;// y = 2z=pointZMId.Z;// z = 3m=pointZMId.M;// m = 4id=pointZMId.ID;// id = 5// Pick and choose which attributes to includeMapPointpoint=MapPointBuilderEx.CreateMapPoint(1,2,false,3,true,4,true,5);sr=point.SpatialReference;// sr = nullhasZ=point.HasZ;// hasZ = falsehasM=point.HasM;// hasM = truehasID=point.HasID;// hasID = truex=point.X;// x = 1y=point.Y;// y = 2z=point.Z;// z = 0, default valuem=point.M;// m = 4id=point.ID;// id = 5// Or use a builderbuilderEx=new(1,2,true,3,false,4,true,5);// Do something with the builderbuilderEx.ID=7;builderEx.SpatialReference=SpatialReferences.WGS84;point=builderEx.ToGeometry();sr=point.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 4326hasZ=point.HasZ;// hasZ = truehasM=point.HasM;// hasM = falsehasID=point.HasID;// hasID = truex=point.X;// x = 1y=point.Y;// y = 2z=point.Z;// z = 0, default valuem=point.M;// m is NaN, default valueid=point.ID;// id = 7
MapPoint Builder Properties
// MapPointBuilderEx constructors can run on any thread.MapPointpoint1=null;MapPointpoint2=null;SpatialReferencespatialReference=SpatialReferenceBuilder.CreateSpatialReference(54004);MapPointBuilderExmapPointBuilder=newMapPointBuilderEx(100,200,spatialReference);SpatialReferencesr=mapPointBuilder.SpatialReference;// sr != nullintwkid=sr.Wkid;// wkid = 54004boolhasZ=mapPointBuilder.HasZ;// hasZ = falseboolhasM=mapPointBuilder.HasM;// hasM = falseboolhasID=mapPointBuilder.HasID;// hasID = falseboolisEmpty=mapPointBuilder.IsEmpty;// isEmpty = falsedoublex=mapPointBuilder.X;// x = 100doubley=mapPointBuilder.Y;// y = 200doublez=mapPointBuilder.Z;// z = 0, default valuedoublem=mapPointBuilder.M;// m is NaN, default valuedoubleid=mapPointBuilder.ID;// id = 0, default value// Do something with the buildermapPointBuilder.Z=12;// Setting the z-value automatically sets HasZ property to truepoint1=mapPointBuilder.ToGeometry();sr=point1.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 54004hasZ=point1.HasZ;// hasZ = truehasM=point1.HasM;// hasM = falsehasID=point1.HasID;// hasID = falsex=point1.X;// x = 100y=point1.Y;// y = 200z=point1.Z;// z = 12m=point1.M;// m is NaN, default valueid=point1.ID;// id = 0, default value// Change some of the builder propertiesmapPointBuilder.SetValues(11,22);mapPointBuilder.HasZ=false;mapPointBuilder.HasM=true;mapPointBuilder.M=44;// Create another pointpoint2=mapPointBuilder.ToGeometry();boolisEqual=point1.IsEqual(point2);// isEqual = false// Set the builder to empty// Sets X and Y to NaN. Sets other attributes to the default values.// Does not change the attribute awareness.mapPointBuilder.SetEmpty();MapPointpoint3=mapPointBuilder.ToGeometry();sr=point3.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 54004hasZ=point3.HasZ;// hasZ = falsehasM=point3.HasM;// hasM = truehasID=point3.HasID;// hasID = falseisEmpty=point3.IsEmpty;// isEmpty = truex=point3.X;// x is NaNy=point3.Y;// y is NaNz=point3.Z;// z = 0, default valuem=point3.M;// m is NaN, default valueid=point3.ID;// ID = 0, default value// Create a builder from a pointmapPointBuilder=newMapPointBuilderEx(point2);// point1 = (11, 22, 0, 44, 0)sr=mapPointBuilder.SpatialReference;// sr != nullwkid=sr.Wkid;// wkid = 54004hasZ=mapPointBuilder.HasZ;// hasZ = falsehasM=mapPointBuilder.HasM;// hasM = truehasID=mapPointBuilder.HasID;// hasID = falseisEmpty=mapPointBuilder.IsEmpty;// isEmpty = falsex=mapPointBuilder.X;// x = 11y=mapPointBuilder.Y;// y = 22z=mapPointBuilder.Z;// z = 0, default valuem=mapPointBuilder.M;// m = 44id=mapPointBuilder.ID;// ID = 0, default value// Setting attribute values automatically sets the corresponding flag to truemapPointBuilder.Z=150;mapPointBuilder.ID=2;// Remove the spatial referencemapPointBuilder.SpatialReference=null;MapPointpoint4=mapPointBuilder.ToGeometry()asMapPoint;sr=point3.SpatialReference;// sr = nullhasZ=point3.HasZ;// hasZ = truehasM=point3.HasM;// hasM = truehasID=point3.HasID;// hasID = trueisEmpty=point3.IsEmpty;// isEmpty = falsex=point3.X;// x = 11y=point3.Y;// y = 22z=point3.Z;// z = 150m=point3.M;// m = 44id=point3.ID;// ID = 2
MapPoint IsEqual
MapPointpt1=MapPointBuilderEx.CreateMapPoint(1,2,3,4,5);intID=pt1.ID;// ID = 5boolhasID=pt1.HasID;// hasID = trueMapPointpt2=MapPointBuilderEx.CreateMapPoint(1,2,3,4,0);ID=pt2.ID;// ID = 0hasID=pt2.HasID;// hasID = trueMapPointpt3=MapPointBuilderEx.CreateMapPoint(1,2,3,4);ID=pt3.ID;// ID = 0hasID=pt3.HasID;// hasID = falseMapPointpt4=MapPointBuilderEx.CreateMapPoint(1,2,3,44);ID=pt4.ID;// ID = 0hasID=pt4.HasID;// hasID = falseboolhasM=pt4.HasM;// hasM = trueMapPointpt5=MapPointBuilderEx.CreateMapPoint(1,2,3);ID=pt5.ID;// ID = 0hasID=pt5.HasID;// hasID = falsehasM=pt5.HasM;// hasM = falseboolisEqual=pt1.IsEqual(pt2);// isEqual = false, different IDsisEqual=pt2.IsEqual(pt3);// isEqual = false, HasId is differentisEqual=pt4.IsEqual(pt3);// isEqual = false, different MsisEqual=pt1.IsEqual(pt5);// isEqual = false, pt has M, id but pt5 does not.
Zoom to a specified point
//Create a pointvarpt=MapPointBuilderEx.CreateMapPoint(x,y,SpatialReferenceBuilder.CreateSpatialReference(4326));//Buffer it - for purpose of zoomvarpoly=GeometryEngine.Instance.Buffer(pt,buffer_size);//do we need to project the buffer polygon?if(!MapView.Active.Map.SpatialReference.IsEqual(poly.SpatialReference)){//project the polygonpoly=GeometryEngine.Instance.Project(poly,MapView.Active.Map.SpatialReference);}// Must run on MCT.QueuedTask.Run(()=>{//Zoom - add in a delay for animation effectMapView.Active.ZoomTo(poly,newTimeSpan(0,0,0,3));});
Polyline
Construct a Polyline - from an enumeration of MapPoints
// Use a builderEx convenience method or a builderEx constructor.// neither need to run on the MCTMapPointstartPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0);MapPointendPt=MapPointBuilderEx.CreateMapPoint(2.0,1.0);List<MapPoint>list=newList<MapPoint>(){startPt,endPt};Polylinepolyline=PolylineBuilderEx.CreatePolyline(list,SpatialReferences.WGS84);// use AttributeFlags.None since we only have 2D points in the listPolylineBuilderExpb=newPolylineBuilderEx(list,AttributeFlags.None);pb.SpatialReference=SpatialReferences.WGS84;Polylinepolyline2=pb.ToGeometry();// Use AttributeFlags.NoAttributes because we only have 2d points in the listPolylinepolyline4=PolylineBuilderEx.CreatePolyline(list,AttributeFlags.None);
Get the points of a Polyline
// get the points as a readonly CollectionReadOnlyPointCollectionpts=polyline.Points;intnumPts=polyline.PointCount;// OR get an enumeration of the pointsIEnumerator<MapPoint>enumPts=polyline.Points.GetEnumerator();// OR get the point coordinates as a readonly list of Coordinate2DIReadOnlyList<Coordinate2D>coordinates=polyline.Copy2DCoordinatesToList();// OR get the point coordinates as a readonly list of Coordinate3DIReadOnlyList<Coordinate3D>coordinates3D=polyline.Copy3DCoordinatesToList();// OR get a subset of the collection as Coordinate2D using preallocated memoryIList<Coordinate2D>coordinate2Ds=newList<Coordinate2D>(10);// allocate some spaceICollection<Coordinate2D>subsetCoordinates2D=coordinate2Ds;// assignpts.Copy2DCoordinatesToList(1,2,refsubsetCoordinates2D);// copy 2 elements from index 1 into the allocated list// coordinate2Ds.Count = 2// do something with the coordinate2Ds// without allocating more space, obtain a different set of coordinatespts.Copy2DCoordinatesToList(5,9,refsubsetCoordinates2D);// copy 9 elements from index 5 into the allocated list// coordinate2Ds.Count = 9// OR get a subset of the collection as Coordinate3D using preallocated memoryIList<Coordinate3D>coordinate3Ds=newList<Coordinate3D>(15);// allocate some spaceICollection<Coordinate3D>subsetCoordinates3D=coordinate3Ds;// assignpts.Copy3DCoordinatesToList(3,5,refsubsetCoordinates3D);// copy 5 elements from index 3 into the allocated list// coordinate3Ds.Count = 5// OR get a subset of the collection as MapPoint using preallocated memoryIList<MapPoint>mapPoints=newList<MapPoint>(7);// allocate some spaceICollection<MapPoint>subsetMapPoint=mapPoints;// assignpts.CopyPointsToList(1,4,refsubsetMapPoint);// copy 4 elements from index 1 into the allocated list// mapPoints.Count = 4
Get the parts of a Polyline
intnumParts=polyline.PartCount;// get the parts as a readonly collectionReadOnlyPartCollectionparts=polyline.Parts;
Enumerate the parts of a Polyline
ReadOnlyPartCollectionpolylineParts=polyline.Parts;// enumerate the segments to get the lengthdoublelen=0;IEnumerator<ReadOnlySegmentCollection>segments=polylineParts.GetEnumerator();while(segments.MoveNext()){ReadOnlySegmentCollectionseg=segments.Current;foreach(Segmentsinseg){len+=s.Length;// perhaps do something specific per segment typeswitch(s.SegmentType){caseSegmentType.Line:break;caseSegmentType.Bezier:break;caseSegmentType.EllipticArc:break;}}}// or use foreach patternforeach(varpartinpolyline.Parts){foreach(varsegmentinpart){len+=segment.Length;// perhaps do something specific per segment typeswitch(segment.SegmentType){caseSegmentType.Line:break;caseSegmentType.Bezier:break;caseSegmentType.EllipticArc:break;}}}
ICollection<Segment>collection=newList<Segment>();polyline.GetAllSegments(refcollection);intnumSegments=collection.Count;// = 10IList<Segment>iList=collectionasIList<Segment>;for(inti=0;i<numSegments;i++){// do something with iList[i]}// use the segments to build another polylinePolylinepolylineFromSegments=PolylineBuilderEx.CreatePolyline(collection);
Build a multi-part Polyline
List<MapPoint>firstPoints=newList<MapPoint>();firstPoints.Add(MapPointBuilderEx.CreateMapPoint(1.0,1.0));firstPoints.Add(MapPointBuilderEx.CreateMapPoint(1.0,2.0));firstPoints.Add(MapPointBuilderEx.CreateMapPoint(2.0,2.0));firstPoints.Add(MapPointBuilderEx.CreateMapPoint(2.0,1.0));List<MapPoint>nextPoints=newList<MapPoint>();nextPoints.Add(MapPointBuilderEx.CreateMapPoint(11.0,1.0));nextPoints.Add(MapPointBuilderEx.CreateMapPoint(11.0,2.0));nextPoints.Add(MapPointBuilderEx.CreateMapPoint(12.0,2.0));nextPoints.Add(MapPointBuilderEx.CreateMapPoint(12.0,1.0));// use AttributeFlags.None since we have 2D points in the listPolylineBuilderExpBuilder=newPolylineBuilderEx(firstPoints,AttributeFlags.None);pBuilder.AddPart(nextPoints);Polylinepolyline=pBuilder.ToGeometry();// polyline has 2 partspBuilder.RemovePart(0);polyline=pBuilder.ToGeometry();// polyline has 1 part
StartPoint of a Polyline
// Method 1: Get the start point of the polyline by converting the polyline // into a collection of points and getting the first point// sketchGeometry is a Polyline// get the sketch as a point collectionvarpointCol=((Multipart)sketchGeometry).Points;// Get the start point of the linevarfirstPoint=pointCol[0];// Method 2: Convert polyline into a collection of line segments // and get the "StartPoint" of the first line segment.varpolylineGeom=sketchGeometryasArcGIS.Core.Geometry.Polyline;varpolyLineParts=polylineGeom.Parts;ReadOnlySegmentCollectionpolylineSegments=polyLineParts.First();//get the first segment as a LineSegmentvarfirsLineSegment=polylineSegments.First()asLineSegment;//Now get the start PointvarstartPoint=firsLineSegment.StartPoint;
// create list of pointsMapPointstartPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0);MapPointendPt=MapPointBuilderEx.CreateMapPoint(2.0,1.0);List<MapPoint>list=newList<MapPoint>(){startPt,endPt};// BuilderEx constructors don't need to run on the MCT.// use the PolylineBuilder as we wish to manipulate the geometry// use AttributeFlags.None as we have 2D pointsPolylineBuilderExpolylineBuilder=newPolylineBuilderEx(list,AttributeFlags.None);// split at a distance 0.75polylineBuilder.SplitAtDistance(0.75,false);// get the polylinePolylinepolyline=polylineBuilder.ToGeometry();// polyline should have 3 points (1,1), (1.75, 1), (2,1)// add another pathMapPointp1=MapPointBuilderEx.CreateMapPoint(4.0,1.0);MapPointp2=MapPointBuilderEx.CreateMapPoint(6.0,1.0);MapPointp3=MapPointBuilderEx.CreateMapPoint(7.0,1.0);List<MapPoint>pts=newList<MapPoint>(){p1,p2,p3};polylineBuilder.AddPart(pts);polyline=polylineBuilder.ToGeometry();// polyline has 2 parts. Each part has 3 points// split the 2nd path half way - don't create a new pathpolylineBuilder.SplitPartAtDistance(1,0.5,true,false);polyline=polylineBuilder.ToGeometry();// polyline still has 2 parts; but now has 7 points
Create 3D Polyline and set Z-values while preserving curve segments
PolylineBuilderExpolylineBuilder=newPolylineBuilderEx(polyline);polylineBuilder.HasZ=true;// The HasZ property is set to true for all the points in// polyline3D when you call ToGeometry().Polylinepolyline3D=polylineBuilder.ToGeometry();// For this example, create Z-values. // You may want to pass them in as a parameter.intnumPoints=polyline3D.PointCount;double[]zValues=newdouble[numPoints];for(inti=0;i<numPoints;i++){zValues[i]=i%2==0?2:1;}// We need to know at which point index each part startsintpartPointIndex=0;intnumParts=polyline3D.PartCount;for(inti=0;i<numParts;i++){varpart=polyline3D.Parts[i];intnumSegments=part.Count;for(intj=0;j<numSegments;j++){Segmentsegment=part[j];MapPointBuilderExpointBuilder=newMapPointBuilderEx(segment.StartPoint);pointBuilder.Z=zValues[partPointIndex++];MapPointstartPoint=pointBuilder.ToGeometry();// Make sure that the end point of this segment is the same as the start point of the next segmentpointBuilder=newMapPointBuilderEx(segment.EndPoint);pointBuilder.Z=zValues[partPointIndex];MapPointendPoint=pointBuilder.ToGeometry();SegmentTypesegmentType=segment.SegmentType;SegmentBuilderExsegmentBuilder=null;switch(segmentType){caseSegmentType.Line:segmentBuilder=newLineBuilderEx((LineSegment)segment);break;caseSegmentType.Bezier:segmentBuilder=newCubicBezierBuilderEx((CubicBezierSegment)segment);break;caseSegmentType.EllipticArc:segmentBuilder=newEllipticArcBuilderEx((EllipticArcSegment)segment);break;}// Only change the start and end point which now have Z-values set. // This will preserve the curve if the segment is an EllipticArcSegment or CubicBezierSegment.segmentBuilder.StartPoint=startPoint;segmentBuilder.EndPoint=endPoint;segment=segmentBuilder.ToSegment();polylineBuilder.ReplaceSegment(i,j,segment);}// Move point index for the next partpartPointIndex++;}polyline3D=polylineBuilder.ToGeometry();returnpolyline3D;
Polygon
Construct a Polygon - from an enumeration of MapPoints
// Use a builderEx convenience method or use a builderEx constructor.MapPointpt1=MapPointBuilderEx.CreateMapPoint(1.0,1.0);MapPointpt2=MapPointBuilderEx.CreateMapPoint(1.0,2.0);MapPointpt3=MapPointBuilderEx.CreateMapPoint(2.0,2.0);MapPointpt4=MapPointBuilderEx.CreateMapPoint(2.0,1.0);List<MapPoint>list=newList<MapPoint>(){pt1,pt2,pt3,pt4};Polygonpolygon=PolygonBuilderEx.CreatePolygon(list,SpatialReferences.WGS84);// polygon.HasZ will be false - it is determined by the HasZ flag of the points in the list// or specifically use AttributeFlags.NoAttributespolygon=PolygonBuilderEx.CreatePolygon(list,AttributeFlags.None);// use AttributeFlags.None as we have 2D pointsPolygonBuilderExpolygonBuilder=newPolygonBuilderEx(list,AttributeFlags.None);polygonBuilder.SpatialReference=SpatialReferences.WGS84;polygon=polygonBuilder.ToGeometry();
Construct a Polygon - from an Envelope
// Use a builderEx convenience method or use a builderEx constructor.MapPointminPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0);MapPointmaxPt=MapPointBuilderEx.CreateMapPoint(2.0,2.0);// Create an envelopeEnvelopeenv=EnvelopeBuilderEx.CreateEnvelope(minPt,maxPt);PolygonpolygonFromEnv=PolygonBuilderEx.CreatePolygon(env);PolygonBuilderExpolygonBuilderEx=newPolygonBuilderEx(env);polygonBuilderEx.SpatialReference=SpatialReferences.WGS84;polygonFromEnv=polygonBuilderEx.ToGeometry()asPolygon;
Get the points of a Polygon
// get the points as a readonly CollectionReadOnlyPointCollectionpts=polygon.Points;// get an enumeration of the pointsIEnumerator<MapPoint>enumPts=polygon.Points.GetEnumerator();// get the point coordinates as a readonly list of Coordinate2DIReadOnlyList<Coordinate2D>coordinates=polygon.Copy2DCoordinatesToList();// get the point coordinates as a readonly list of Coordinate3DIReadOnlyList<Coordinate3D>coordinates3D=polygon.Copy3DCoordinatesToList();
Get the parts of a Polygon
// get the parts as a readonly collectionReadOnlyPartCollectionparts=polygon.Parts;
Enumerate the parts of a Polygon
intnumSegments=0;IEnumerator<ReadOnlySegmentCollection>segments=polygon.Parts.GetEnumerator();while(segments.MoveNext()){ReadOnlySegmentCollectionseg=segments.Current;numSegments+=seg.Count;foreach(Segmentsinseg){// do something with the segment}}
Get the segments of a Polygon
List<Segment>segmentList=newList<Segment>(30);ICollection<Segment>collection=segmentList;polygon.GetAllSegments(refcollection);// segmentList.Count = 4// segmentList.Capacity = 30// use the segments to build another polygonPolygonpolygonFromSegments=PolygonBuilderEx.CreatePolygon(collection);
Build a donut polygon
List<Coordinate2D>outerCoordinates=newList<Coordinate2D>();outerCoordinates.Add(newCoordinate2D(10.0,10.0));outerCoordinates.Add(newCoordinate2D(10.0,20.0));outerCoordinates.Add(newCoordinate2D(20.0,20.0));outerCoordinates.Add(newCoordinate2D(20.0,10.0));// define the inner polygon as anti-clockwiseList<Coordinate2D>innerCoordinates=newList<Coordinate2D>();innerCoordinates.Add(newCoordinate2D(13.0,13.0));innerCoordinates.Add(newCoordinate2D(17.0,13.0));innerCoordinates.Add(newCoordinate2D(17.0,17.0));innerCoordinates.Add(newCoordinate2D(13.0,17.0));PolygonBuilderExpbEx=newPolygonBuilderEx(outerCoordinates);PolygondonutEx=pbEx.ToGeometry()asPolygon;doubleareaEx=donutEx.Area;// area = 100pbEx.AddPart(innerCoordinates);donutEx=pbEx.ToGeometry()asPolygon;areaEx=donutEx.Area;// area = 84.0areaEx=GeometryEngine.Instance.Area(donutEx);// area = 84.0
Create an N-sided regular polygon
// <summary>// Create an N-sided regular polygon. A regular sided polygon is a polygon that is equiangular (all angles are equal in measure) // and equilateral (all sides are equal in length). See https://en.wikipedia.org/wiki/Regular_polygon// </summary>// <param name="numSides">The number of sides in the polygon.</param>// <param name="center">The center of the polygon.</param>// <param name="radius">The distance from the center of the polygon to a vertex.</param>// <param name="rotation">The rotation angle in radians of the start point of the polygon. The start point will be// rotated counterclockwise from the positive x-axis.</param>// <returns>N-sided regular polygon.</returns>// <exception cref="ArgumentException">Number of sides is less than 3.</exception>publicPolygonCreateRegularPolygon(intnumSides,Coordinate2Dcenter,doubleradius,doublerotation){if(numSides<3)thrownewArgumentException();Coordinate2D[]coords=newCoordinate2D[numSides+1];doublecenterX=center.X;doublecenterY=center.Y;doublex=radius*Math.Cos(rotation)+centerX;doubley=radius*Math.Sin(rotation)+centerY;Coordinate2Dstart=newCoordinate2D(x,y);coords[0]=start;doubleda=2*Math.PI/numSides;for(inti=1;i<numSides;i++){x=radius*Math.Cos(i*da+rotation)+centerX;y=radius*Math.Sin(i*da+rotation)+centerY;coords[i]=newCoordinate2D(x,y);}coords[numSides]=start;returnPolygonBuilderEx.CreatePolygon(coords);}
Get the exterior rings of a polygon - polygon.GetExteriorRing
publicvoidGetExteriorRings(PolygoninputPolygon){if(inputPolygon==null||inputPolygon.IsEmpty)return;// polygon part countintpartCount=inputPolygon.PartCount;// polygon exterior ring countintnumExtRings=inputPolygon.ExteriorRingCount;// get set of exterior rings for the polygonIList<Polygon>extRings=inputPolygon.GetExteriorRings();// test each part for "exterior ring"for(intidx=0;idx<partCount;idx++){boolisExteriorRing=inputPolygon.IsExteriorRing(idx);varring=inputPolygon.GetExteriorRing(idx);}}
Envelope
Construct an Envelope
// Use a builderEx convenience method or use a builderEx constructor.MapPointminPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0);MapPointmaxPt=MapPointBuilderEx.CreateMapPoint(2.0,2.0);Envelopeenvelope=EnvelopeBuilderEx.CreateEnvelope(minPt,maxPt);EnvelopeBuilderExbuilderEx=newEnvelopeBuilderEx(minPt,maxPt);envelope=builderEx.ToGeometry()asEnvelope;
// use the convenience buildersEnvelopeenv1=EnvelopeBuilderEx.CreateEnvelope(0,0,1,1,SpatialReferences.WGS84);Envelopeenv2=EnvelopeBuilderEx.CreateEnvelope(0.5,0.5,1.5,1.5,SpatialReferences.WGS84);Envelopeenv3=env1.Union(env2);doublearea=env3.Area;doubledepth=env3.Depth;doubleheight=env3.Height;doublewidth=env3.Width;doublelen=env3.Length;MapPointcenterPt=env3.Center;Coordinate2Dcoord=env3.CenterCoordinate;boolisEmpty=env3.IsEmpty;intpointCount=env3.PointCount;// coordinates//env3.XMin, env3.XMax, env3.YMin, env3.YMax//env3.ZMin, env3.ZMax, env3.MMin, env3.MMaxboolisEqual=env1.IsEqual(env2);// false// or use the builderEx constructors which don't need to run on the MCT.EnvelopeBuilderExbuilderEx=newEnvelopeBuilderEx(0,0,1,1,SpatialReferences.WGS84);builderEx.Union(env2);// builder is updated to the resultdepth=builderEx.Depth;height=builderEx.Height;width=builderEx.Width;centerPt=builderEx.Center;coord=builderEx.CenterCoordinate;isEmpty=builderEx.IsEmpty;env3=builderEx.ToGeometry()asEnvelope;
Intersect two Envelopes
// use the convenience buildersEnvelopeenv1=EnvelopeBuilderEx.CreateEnvelope(0,0,1,1,SpatialReferences.WGS84);Envelopeenv2=EnvelopeBuilderEx.CreateEnvelope(0.5,0.5,1.5,1.5,SpatialReferences.WGS84);boolintersects=env1.Intersects(env2);// trueEnvelopeenv3=env1.Intersection(env2);// or use the builderEx constructors which don't need to run on the MCT.EnvelopeBuilderExbuilderEx=newEnvelopeBuilderEx(0,0,1,1,SpatialReferences.WGS84);intersects=builderEx.Intersects(env2);builderEx.Intersection(env2);// note this sets the builder to the intersectionenv3=builderEx.ToGeometry()asEnvelope;
Expand an Envelope
// Use a builderEx convenience method or use a builderEx constructor.// convenience methods don't need to run on the MCT.Envelopeenvelope=EnvelopeBuilderEx.CreateEnvelope(100.0,100.0,500.0,500.0);// shrink the envelope by 50%Enveloperesult=envelope.Expand(0.5,0.5,true);// builderEx constructors don't need to run on the MCT.EnvelopeBuilderExbuilderEx=newEnvelopeBuilderEx(100.0,100.0,500.0,500.0);builderEx.Expand(0.5,0.5,true);envelope=builderEx.ToGeometry()asEnvelope;
Update Coordinates of an Envelope
Coordinate2DminCoord=newCoordinate2D(1,3);Coordinate2DmaxCoord=newCoordinate2D(2,4);Coordinate2Dc1=newCoordinate2D(0,5);Coordinate2Dc2=newCoordinate2D(1,3);// use the EnvelopeBuilderEx. This constructor doesn't need to run on the MCT.EnvelopeBuilderExbuilderEx=newEnvelopeBuilderEx(minCoord,maxCoord);// builderEx.XMin, YMin, Zmin, MMin = 1, 3, 0, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 2, 4, 0, double.Nan// set XMin. if XMin > XMax; both XMin and XMax changebuilderEx.XMin=6;// builderEx.XMin, YMin, ZMin, MMin = 6, 3, 0, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 6, 4, 0, double.Nan// set XMaxbuilderEx.XMax=8;// builderEx.XMin, YMin, ZMin, MMin = 6, 3, 0, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 8, 4, 0, double.Nan// set XMax. if XMax < XMin, both XMin and XMax changebuilderEx.XMax=3;// builderEx.XMin, YMin, ZMin, MMin = 3, 3, 0, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 3, 4, 0, double.Nan// set YMinbuilderEx.YMin=2;// builderEx.XMin, YMin, ZMin, MMin = 3, 2, 0, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 3, 4, 0, double.Nan// set ZMin. if ZMin > ZMax, both ZMin and ZMax changebuilderEx.ZMin=3;// builderEx.XMin, YMin, ZMin, MMin = 3, 2, 3, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 3, 4, 3, double.Nan// set ZMax. if ZMax < ZMin. both ZMin and ZMax changebuilderEx.ZMax=-1;// builderEx.XMin, YMin, ZMin, MMin = 3, 2, -1, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 3, 4, -1, double.NanbuilderEx.SetZCoords(8,-5);// builderEx.XMin, YMin, ZMin, MMin = 3, 2, -5, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 3, 4, 8, double.NanbuilderEx.SetXYCoords(c1,c2);// builderEx.XMin, YMin, ZMin, MMin = 0, 3, -5, double.Nan// builderEx.XMax, YMax, ZMax, MMax = 1, 5, 8, double.NanbuilderEx.HasM=true;builderEx.SetMCoords(2,5);vargeomEx=builderEx.ToGeometry();
Multipoint
Construct a Multipoint - from an enumeration of MapPoints
// Use a builderEx convenience method or use a builderEx constructor.List<MapPoint>list=newList<MapPoint>();list.Add(MapPointBuilderEx.CreateMapPoint(1.0,1.0));list.Add(MapPointBuilderEx.CreateMapPoint(1.0,2.0));list.Add(MapPointBuilderEx.CreateMapPoint(2.0,2.0));list.Add(MapPointBuilderEx.CreateMapPoint(2.0,1.0));// use the builderEx constructors which don't need to run on the MCT.// use AttributeFlags.NoAttributes since we have 2d points in the listMultipointBuilderExbuilderEx=newMultipointBuilderEx(list,AttributeFlags.None);MultipointmultiPoint=builderEx.ToGeometry()asMultipoint;intptCount=builderEx.PointCount;// builderEx convenience methods don't need to run on the MCTmultiPoint=MultipointBuilderEx.CreateMultipoint(list);// multiPoint.HasZ, HasM, HasID will be false - the attributes are determined // based on the attribute state of the points in the list// or specifically set the statemultiPoint=MultipointBuilderEx.CreateMultipoint(list,AttributeFlags.None);// multiPoint.HasM = falsemultiPoint=MultipointBuilderEx.CreateMultipoint(list,AttributeFlags.HasM);// multiPoint.HasM = trueptCount=multiPoint.PointCount;
Construct a Multipoint - using MultipointBuilderEx
Coordinate2D[]coordinate2Ds=newCoordinate2D[]{newCoordinate2D(1,2),newCoordinate2D(-1,-2)};SpatialReferencesr=SpatialReferences.WGS84;MultipointBuilderExbuilder=newMultipointBuilderEx(coordinate2Ds,sr);// builder.PointCount = 2builder.HasZ=true;// builder.Zs.Count = 2// builder.Zs[0] = 0// builder.Zs[1] = 0builder.HasM=true;// builder.Ms.Count = 2// builder.Ms[0] = NaN// builder.Ms[1] = NaNbuilder.HasID=true;// builder.IDs.Count = 2// builder.IDs[0] = 0// builder.IDs[1] = 0// set it emptybuilder.SetEmpty();// builder.Coords.Count = 0// builder.Zs.Count = 0// builder.Ms.Count = 0// builder.IDs.Count = 0// reset coordinatesList<Coordinate2D>inCoords=newList<Coordinate2D>(){newCoordinate2D(1,2),newCoordinate2D(3,4),newCoordinate2D(5,6)};builder.Coordinate2Ds=inCoords;// builder.Coords.Count = 3// builder.HasZ = true// builder.HasM = true// builder.HasID = truedouble[]zs=newdouble[]{1,2,1,2,1,2};builder.Zs=zs;// builder.Zs.Count = 6double[]ms=newdouble[]{0,1};builder.Ms=ms;// builder.Ms.Count = 2// coordinates are now (x, y, z, m, id)// (1, 2, 1, 0, 0), (3, 4, 2, 1, 0) (5, 6, 1, NaN, 0)MapPointmapPoint=builder.GetPoint(2);// mapPoint.HasZ = true// mapPoint.HasM = true// mapPoint.HasID = true// mapPoint.Z = 1// mapPoint.M = NaN// mapPoint.ID = 0// add an M to the listbuilder.Ms.Add(2);// builder.Ms.count = 3// coordinates are now (x, y, z, m, id)// (1, 2, 1, 0, 0), (3, 4, 2, 1, 0) (5, 6, 1, 2, 0)// now get the 2nd point again; it will now have an M valuemapPoint=builder.GetPoint(2);// mapPoint.M = 2int[]ids=newint[]{-1,-2,-3};// assign ID valuesbuilder.IDs=ids;// coordinates are now (x, y, z, m, id)// (1, 2, 1, 0, -1), (3, 4, 2, 1, -2) (5, 6, 1, 2, -3)// create a new pointMapPointpoint=MapPointBuilderEx.CreateMapPoint(-300,400,4);builder.SetPoint(2,point);// coordinates are now (x, y, z, m, id)// (1, 2, 1, 0, -1), (3, 4, 2, 1, -2) (-300, 400, 4, NaN, 0)builder.RemovePoints(1,3);// builder.PointCount = 1
Modify the points of a Multipoint
// assume a multiPoint has been built from 4 points// the modified multiPoint will have the first point removed and the last point moved// use the builderEx constructors which don't need to run on the MCT.MultipointBuilderExbuilderEx=newMultipointBuilderEx(multipoint);// remove the first pointbuilderEx.RemovePoint(0);// modify the coordinates of the last pointvarptEx=builderEx.GetPoint(builderEx.PointCount-1);builderEx.RemovePoint(builderEx.PointCount-1);varnewPtEx=MapPointBuilderEx.CreateMapPoint(ptEx.X+1.0,ptEx.Y+2.0);builderEx.AddPoint(newPtEx);MultipointmodifiedMultiPointEx=builderEx.ToGeometry()asMultipoint;
Retrieve Points, 2D Coordinates, 3D Coordinates from a multipoint
// Use a builderEx convenience method or use a builderEx constructor.MapPointstartPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0);MapPointendPt=MapPointBuilderEx.CreateMapPoint(2.0,1.0);// BuilderEx convenience methods don't need to run on the MCT.LineSegmentlineFromMapPoint=LineBuilderEx.CreateLineSegment(startPt,endPt);// coordinate2DCoordinate2Dstart2d=(Coordinate2D)startPt;Coordinate2Dend2d=(Coordinate2D)endPt;LineSegmentlineFromCoordinate2D=LineBuilderEx.CreateLineSegment(start2d,end2d);// coordinate3DCoordinate3Dstart3d=(Coordinate3D)startPt;Coordinate3Dend3d=(Coordinate3D)endPt;LineSegmentlineFromCoordinate3D=LineBuilderEx.CreateLineSegment(start3d,end3d);// lineSegmentLineSegmentanotherLineFromLineSegment=LineBuilderEx.CreateLineSegment(lineFromCoordinate3D);// builderEx constructors don't need to run on the MCTLineBuilderExlbEx=newLineBuilderEx(startPt,endPt);lineFromMapPoint=lbEx.ToSegment()asLineSegment;lbEx=newLineBuilderEx(start2d,end2d);lineFromCoordinate2D=lbEx.ToSegment()asLineSegment;lbEx=newLineBuilderEx(start3d,end3d);lineFromCoordinate3D=lbEx.ToSegment()asLineSegment;lbEx=newLineBuilderEx(startPt,endPt);lineFromMapPoint=lbEx.ToSegment()asLineSegment;lbEx=newLineBuilderEx(lineFromCoordinate3D);anotherLineFromLineSegment=lbEx.ToSegment()asLineSegment;
Alter LineSegment Coordinates
// builderEx constructors don't need to run on the MCTLineBuilderExlbuilderEx=newLineBuilderEx(lineSegment);// find the existing coordinateslbuilderEx.QueryCoords(outstartPt,outendPt);// or use //startPt = lbuilderEx.StartPoint;//endPt = lbuilderEx.EndPoint;// update the coordinateslbuilderEx.SetCoords(GeometryEngine.Instance.Move(startPt,10,10)asMapPoint,GeometryEngine.Instance.Move(endPt,-10,-10)asMapPoint);// or use //lbuilderEx.StartPoint = GeometryEngine.Instance.Move(startPt, 10, 10) as MapPoint;//lbuilderEx.EndPoint = GeometryEngine.Instance.Move(endPt, -10, -10) as MapPoint;LineSegmentsegment2=lbuilderEx.ToSegment()asLineSegment;
Cubic Bezier
Construct a Cubic Bezier - from Coordinates
// Use a builderEx convenience method or a builderEx constructor.MapPointstartPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0,3.0);MapPointendPt=MapPointBuilderEx.CreateMapPoint(2.0,2.0,3.0);Coordinate2Dctrl1Pt=newCoordinate2D(1.0,2.0);Coordinate2Dctrl2Pt=newCoordinate2D(2.0,1.0);// BuilderEx convenience methods don't need to run on the MCTCubicBezierSegmentbezier=CubicBezierBuilderEx.CreateCubicBezierSegment(startPt,ctrl1Pt,ctrl2Pt,endPt,SpatialReferences.WGS84);// without a SRbezier=CubicBezierBuilderEx.CreateCubicBezierSegment(startPt,ctrl1Pt,ctrl2Pt,endPt);// builderEx constructors don't need to run on the MCTCubicBezierBuilderExcbbEx=newCubicBezierBuilderEx(startPt,ctrl1Pt,ctrl2Pt,endPt);bezier=cbbEx.ToSegment()asCubicBezierSegment;// another alternativecbbEx=newCubicBezierBuilderEx(startPt,ctrl1Pt.ToMapPoint(),ctrl2Pt.ToMapPoint(),endPt);bezier=cbbEx.ToSegment()asCubicBezierSegment;
Construct a Cubic Bezier - from MapPoints
// Use a builderEx convenience method or a builderEx constructor.MapPointstartPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0,SpatialReferences.WGS84);MapPointendPt=MapPointBuilderEx.CreateMapPoint(2.0,2.0,SpatialReferences.WGS84);MapPointctrl1Pt=MapPointBuilderEx.CreateMapPoint(1.0,2.0,SpatialReferences.WGS84);MapPointctrl2Pt=MapPointBuilderEx.CreateMapPoint(2.0,1.0,SpatialReferences.WGS84);// BuilderEx convenience methods don't need to run on the MCTCubicBezierSegmentbezier=CubicBezierBuilderEx.CreateCubicBezierSegment(startPt,ctrl1Pt,ctrl2Pt,endPt);// builderEx constructors don't need to run on the MCTCubicBezierBuilderExcbbEx=newCubicBezierBuilderEx(startPt,ctrl1Pt,ctrl2Pt,endPt);bezier=cbbEx.ToSegment()asCubicBezierSegment;
Construct a Cubic Bezier - from an enumeration of MapPoints
// Use a buildeExr convenience method or use a builderEx constructor.MapPointstartPt=MapPointBuilderEx.CreateMapPoint(1.0,1.0,SpatialReferences.WGS84);MapPointendPt=MapPointBuilderEx.CreateMapPoint(2.0,2.0,SpatialReferences.WGS84);MapPointctrl1Pt=MapPointBuilderEx.CreateMapPoint(1.0,2.0,SpatialReferences.WGS84);MapPointctrl2Pt=MapPointBuilderEx.CreateMapPoint(2.0,1.0,SpatialReferences.WGS84);List<MapPoint>listMapPoints=newList<MapPoint>();listMapPoints.Add(startPt);listMapPoints.Add(ctrl1Pt);listMapPoints.Add(ctrl2Pt);listMapPoints.Add(endPt);// BuilderEx convenience methods don't need to run on the MCTCubicBezierSegmentbezier=CubicBezierBuilderEx.CreateCubicBezierSegment(listMapPoints);// builderEx constructors don't need to run on the MCTCubicBezierBuilderExcbbEx=newCubicBezierBuilderEx(listMapPoints);bezier=cbbEx.ToSegment()asCubicBezierSegment;
Cubic Bezier Builder Properties
// retrieve the bezier curve's control pointsCubicBezierBuilderExcbbEx=newCubicBezierBuilderEx(bezierSegment);MapPointstartPtEx=cbbEx.StartPoint;Coordinate2DctrlPt1Ex=cbbEx.ControlPoint1;Coordinate2DctrlPt2Ex=cbbEx.ControlPoint2;MapPointendPtEx=cbbEx.EndPoint;// or use the QueryCoords methodcbbEx.QueryCoords(outstartPtEx,outctrlPt1Ex,outctrlPt2Ex,outendPtEx);
Cubic Bezier Properties
// retrieve the bezier curve's control pointsCubicBezierSegmentcb=CubicBezierBuilderEx.CreateCubicBezierSegment(bezierSegment);MapPointstartPt=cb.StartPoint;Coordinate2DctrlPt1=cb.ControlPoint1;Coordinate2DctrlPt2=cb.ControlPoint2;MapPointendPt=cb.EndPoint;boolisCurve=cb.IsCurve;doublelen=cb.Length;
Construct a Circular Arc - using an interior point
// Construct a circular arc from (2, 1) to (1, 2) with interior pt (1 + sqrt(2)/2, 1 + sqrt(2)/2).// Use a builderEx convenience method or use a builderEx constructor.MapPointfromPt=MapPointBuilderEx.CreateMapPoint(2,1);MapPointtoPt=MapPointBuilderEx.CreateMapPoint(1,2);Coordinate2DinteriorPt=newCoordinate2D(1+Math.Sqrt(2)/2,1+Math.Sqrt(2)/2);// BuilderEx convenience methods don't need to run on the MCT.EllipticArcSegmentcircularArc=EllipticArcBuilderEx.CreateCircularArc(fromPt,toPt,interiorPt);// BuilderEx constructors don't need to run on the MCT.EllipticArcBuilderExeab=newEllipticArcBuilderEx(fromPt,toPt,interiorPt);// do something with the builderEllipticArcSegmentanotherCircularArc=eab.ToSegment();
Construct a Circular Arc - using a chord length and bearing
// Construct a circular arc counterclockwise from (2, 1) to (1, 2) such that the embedded // circle has center point at (1, 1) and radius = 1.// Use a builderEx convenience method or use a builderEx constructor.MapPointfromPt=MapPointBuilderEx.CreateMapPoint(2,1,SpatialReferences.WGS84);doublechordLength=Math.Sqrt(2);doublechordBearing=3*Math.PI/4;doubleradius=1;ArcOrientationorientation=ArcOrientation.ArcCounterClockwise;MinorOrMajorminorOrMajor=MinorOrMajor.Minor;// BuildeEx convenience methods don't need to run on the MCT.EllipticArcSegmentcircularArc=EllipticArcBuilderEx.CreateCircularArc(fromPt,chordLength,chordBearing,radius,orientation,minorOrMajor);// BuilderEx constructors don't need to run on the MCT either.EllipticArcBuilderExcab=newEllipticArcBuilderEx(fromPt,chordLength,chordBearing,radius,orientation,minorOrMajor);// do something with the builderEllipticArcSegmentanotherCircularArc=cab.ToSegment();
Construct a Circular Arc - using a center point, angle and radius
// Construct a circular arc with center point at (0, 0), from angle = 0, // central angle = pi/2, radius = 1.// Use a builderEx convenience method or use a builderEx constructor.SpatialReferencesr4326=SpatialReferences.WGS84;Coordinate2DcenterPt=newCoordinate2D(0,0);doublefromAngle=0;doublecentralAngle=Math.PI/2;doubleradius=1;// BuilderEx convenience methods don't need to run on the MCT.EllipticArcSegmentcircularArc=EllipticArcBuilderEx.CreateCircularArc(fromAngle,centralAngle,centerPt,radius,sr4326);// BuilderEx constructors don't need to run on the MCT.EllipticArcBuilderExcab=newEllipticArcBuilderEx(fromAngle,centralAngle,centerPt,radius,sr4326);EllipticArcSegmentotherCircularArc=cab.ToSegment();
Construct an Elliptic Arc - using a center point and rotation angle
// Construct an elliptic arc centered at (1,1), startAngle = 0, centralAngle = PI/2, // rotationAngle = 0, semiMajorAxis = 1, minorMajorRatio = 0.5.// Use a builderEx convenience method or use a builderEx constructor.Coordinate2DcenterPt=newCoordinate2D(1,1);// BuilderEx convenience methods don't need to run on the MCT.EllipticArcSegmentcircularArc=EllipticArcBuilderEx.CreateEllipticArcSegment(centerPt,0,Math.PI/2,0,1,0.5);doublesemiMajor;doublesemiMinor;circularArc.GetAxes(outsemiMajor,outsemiMinor);// semiMajor = 1, semiMinor = 0.5// BuilderEx constructors don't need to run on the MCT.EllipticArcBuilderExcab=newEllipticArcBuilderEx(centerPt,0,Math.PI/2,0,1,0.5);cab.GetAxes(outsemiMajor,outsemiMinor);EllipticArcSegmentotherCircularArc=cab.ToSegment();
Construct a Circular Arc - using a center point and orientation
// Construct a circular arc from (2, 1) to (1, 2) // with center point at (1, 1) and orientation counterclockwise.// Use a builderEx convenience method or use a builderEx constructor.MapPointtoPt=MapPointBuilderEx.CreateMapPoint(1,2);MapPointfromPt=MapPointBuilderEx.CreateMapPoint(2,1);Coordinate2DcenterPtCoord=newCoordinate2D(1,1);// BuilderEx convenience methods don't need to run on the MCT.EllipticArcSegmentcircularArc=EllipticArcBuilderEx.CreateCircularArc(fromPt,toPt,centerPtCoord,ArcOrientation.ArcCounterClockwise);// BuilderEx constructors need to run on the MCT.EllipticArcBuilderExcab=newEllipticArcBuilderEx(fromPt,toPt,centerPtCoord,ArcOrientation.ArcCounterClockwise);EllipticArcSegmentotherCircularArc=cab.ToSegment();
Construct a Circular Arc - using two segments and radius
// Construct a segment from (100, 100) to (50, 50) and another segment from (100, 100) to (150, 50).// Use a builderEx convenience method or use a builderEx constructor.LineSegmentsegment1=LineBuilderEx.CreateLineSegment(newCoordinate2D(100,100),newCoordinate2D(50,50));LineSegmentsegment2=LineBuilderEx.CreateLineSegment(newCoordinate2D(100,100),newCoordinate2D(150,50));// Construct the hint point to determine where the arc will be constructed.Coordinate2DhintPoint=newCoordinate2D(100,75);// Call QueryFilletRadius to get the minimum and maximum radii that can be used with these segments.varminMaxRadii=EllipticArcBuilderEx.QueryFilletRadiusRange(segment1,segment2,hintPoint);// Use the maximum radius to create the arc.doublemaxRadius=minMaxRadii.Item2;// BuilderEx convenience methods don't need to run on the MCT.//At 2.x - EllipticArcSegment circularArc = EllipticArcBuilderEx.CreateEllipticArcSegment(segment1, segment2, maxRadius, hintPoint);EllipticArcSegmentcircularArc=EllipticArcBuilderEx.CreateCircularArc(segment1,segment2,maxRadius,hintPoint);// This EllipticArcBuilderEx constructor needs to run on the MCT either.EllipticArcBuilderExcab=newEllipticArcBuilderEx(segment1,segment2,maxRadius,hintPoint);EllipticArcSegmentotherCircularArc=cab.ToSegment();
Construct a Circle
// Construct a circle with center at (-1,-1), radius = 2, and oriented clockwise.// Use a builderEx convenience method or use a builderEx constructor.Coordinate2DcenterPtCoord=newCoordinate2D(-1,-1);// Builder convenience methods don't need to run on the MCT.EllipticArcSegmentcircle=EllipticArcBuilderEx.CreateCircle(centerPtCoord,2,ArcOrientation.ArcClockwise);// circle.IsCircular = true// circle.IsCounterClockwise = false// circle.IsMinor = falsedoublestartAngle,rotationAngle,centralAngle,semiMajor,semiMinor;Coordinate2DactualCenterPt;circle.QueryCoords(outactualCenterPt,outstartAngle,outcentralAngle,outrotationAngle,outsemiMajor,outsemiMinor);// semiMajor = 2.0// semiMinor = 2.0// startAngle = PI/2// centralAngle = -2*PI// rotationAngle = 0// endAngle = PI/2// This EllipticArcBuilderEx constructor doesn't need to run on the MCT.EllipticArcBuilderExbuilder=newEllipticArcBuilderEx(centerPtCoord,2,ArcOrientation.ArcClockwise);EllipticArcSegmentotherCircle=builder.ToSegment();
Construct an Ellipse
// Construct an ellipse centered at (1, 2) with rotationAngle = -pi/6, // semiMajorAxis = 5, minorMajorRatio = 0.2, oriented clockwise.// Use a builderEx convenience method or use a builderEx constructor.Coordinate2DcenterPt=newCoordinate2D(1,2);// BuilderEx convenience methods don't need to run on the MCT.EllipticArcSegmentellipse=EllipticArcBuilderEx.CreateEllipse(centerPt,-1*Math.PI/6,5,0.2,ArcOrientation.ArcClockwise);// This EllipticArcBuilderEx constructor doesn't need to run on the MCT.EllipticArcBuilderExbuilder=newEllipticArcBuilderEx(centerPt,-1*Math.PI/6,5,0.2,ArcOrientation.ArcClockwise);EllipticArcSegmentanotherEllipse=builder.ToSegment();
Elliptic Arc Builder Properties
// retrieve the curve's propertiesEllipticArcBuilderExbuilder=newEllipticArcBuilderEx(arcSegment);MapPointstartPt=builder.StartPoint;MapPointendPt=builder.EndPoint;Coordinate2DcenterPt=builder.CenterPoint;boolisCircular=builder.IsCircular;boolisMinor=builder.IsMinor;doublestartAngle=builder.StartAngle;doubleendAngle=builder.EndAngle;doublecentralAngle=builder.CentralAngle;doublerotationAngle=builder.RotationAngle;ArcOrientationorientation=builder.Orientation;
Elliptic Arc Properties
// retrieve the curve's control pointsEllipticArcSegmentarc=EllipticArcBuilderEx.CreateEllipticArcSegment(arcSegment);MapPointstartPt=arc.StartPoint;MapPointendPt=arc.EndPoint;Coordinate2DcenterPt=arc.CenterPoint;boolisCircular=arc.IsCircular;boolisMinor=arc.IsMinor;boolisCounterClockwise=arc.IsCounterClockwise;boolisCurve=arc.IsCurve;doublelen=arc.Length;doubleratio=arc.MinorMajorRatio;doublesemiMajorAxis,semiMinorAxis;// get the axesarc.GetAxes(outsemiMajorAxis,outsemiMinorAxis);// or use the properties// semiMajorAxis = arc.SemiMajorAxis;// semiMinorAxis = arc.SemiMinorAxis;doublestartAngle,centralAngle,rotationAngle;// or use QueryCoords to get complete informationarc.QueryCoords(outcenterPt,outstartAngle,outcentralAngle,outrotationAngle,outsemiMajorAxis,outsemiMinorAxis);// use properties to get angle information//double endAngle = arc.EndAngle;//centralAngle = arc.CentralAngle;//rotationAngle = arc.RotationAngle;//startAngle = arc.StartAngle;
GeometryBag
Construct GeometryBag
MapPointpoint=MapPointBuilderEx.CreateMapPoint(1,2,SpatialReferences.WebMercator);List<Coordinate2D>coords2D=newList<Coordinate2D>(){newCoordinate2D(0,0),newCoordinate2D(0,1),newCoordinate2D(1,1),newCoordinate2D(1,0)};Multipointmultipoint=MultipointBuilderEx.CreateMultipoint(coords2D,SpatialReferences.WGS84);Polylinepolyline=PolylineBuilderEx.CreatePolyline(coords2D,SpatialReferences.WebMercator);GeometryBagBuilderExbuilder=newGeometryBagBuilderEx(SpatialReferences.WGS84);GeometryBagemptyBag=builder.ToGeometry();// emptyBag.IsEmpty = truebuilder.AddGeometry(point);// builder.GeometryCount = 1GeometryBaggeometryBag=builder.ToGeometry();// geometryBag.PartCount = 1// geometryBag.PointCount = 1// geometryBag.IsEmpty = falseIReadOnlyList<Geometry>geometries=geometryBag.Geometries;// geometries.Count = 1// geometries[0] is MapPoint with a sr of WGS84boolisEqual=geometryBag.IsEqual(emptyBag);// isEqual = falsebuilder.InsertGeometry(0,multipoint);geometryBag=builder.ToGeometry();// geometryBag.PartCount = 2geometries=geometryBag.Geometries;// geometries.Count = 2// geometries[0] is Multipoint// geometries[1] is MapPointbuilder.AddGeometry(polyline);builder.RemoveGeometry(1);geometryBag=builder.ToGeometry();// geometryBag.PartCount = 2geometries=geometryBag.Geometries;// geometries.Count = 2// geometries[0] is Multipoint// geometries[1] is Polyline
Construct GeometryBag - from an enumeration of geometries
// Use a builder convenience method or use a builder constructor.MapPointpoint=MapPointBuilderEx.CreateMapPoint(10,20);List<Coordinate2D>coords=newList<Coordinate2D>(){newCoordinate2D(50,60),newCoordinate2D(-120,-70),newCoordinate2D(40,60)};Multipointmultipoint=MultipointBuilderEx.CreateMultipoint(coords,SpatialReferences.WebMercator);Polylinepolyline=PolylineBuilderEx.CreatePolyline(coords);stringjson="{\"rings\":[[[0,0],[0,1],[1,1],[1,0],[0,0]],[[3,0],[3,1],[4,1],[4,0],[3,0]]]}";Polygonpolygon=PolygonBuilderEx.FromJson(json);vargeometries=newList<Geometry>(){point,multipoint,polyline,polygon};// Builder convenience methods don't need to run on the MCT.//At 2.x - GeometryBag bag = GeometryBagBuilder.CreateGeometryBag(geometries, SpatialReferences.WGS84);varbag=GeometryBagBuilderEx.CreateGeometryBag(geometries,SpatialReferences.WGS84);//At 2.x - using (var builder = new GeometryBagBuilder(geometries, SpatialReferences.WGS84)) varbuilder=newGeometryBagBuilderEx(geometries,SpatialReferences.WGS84);// do something with the builderbag=builder.ToGeometry();
Construct GeometryBag - adding or inserting an enumeration of geometries
MapPointpoint=MapPointBuilderEx.CreateMapPoint(10,20);List<Coordinate2D>coords=newList<Coordinate2D>(){newCoordinate2D(50,60),newCoordinate2D(-120,-70),newCoordinate2D(40,60)};Multipointmultipoint=MultipointBuilderEx.CreateMultipoint(coords,SpatialReferences.WebMercator);Polylinepolyline=PolylineBuilderEx.CreatePolyline(coords);stringjson="{\"rings\":[[[0,0],[0,1],[1,1],[1,0],[0,0]],[[3,0],[3,1],[4,1],[4,0],[3,0]]]}";Polygonpolygon=PolygonBuilderEx.FromJson(json);vargeometries=newList<Geometry>(){point,multipoint,polyline,polygon};//At 2.x - using (var builder = new GeometryBagBuilder(SpatialReferences.WGS84))varbuilder=newGeometryBagBuilderEx(SpatialReferences.WGS84);builder.AddGeometries(geometries);GeometryBaggeomBag=builder.ToGeometry();// geomBag.PartCount == 4 (point, multipoint, polyline, polygon)geometries=newList<Geometry>(){point,polyline};builder.InsertGeometries(1,geometries);// builder.GeometryCount == 6geomBag=builder.ToGeometry();// geomBag.PartCount == 6 (point, point, polyline, multipoint, polyline, polygon)
Multipatch
Construct Multipatch via Extrusion of Polygon or Polyline
// build a polygonstringjson="{\"hasZ\":true,\"rings\":[[[0,0,0],[0,1,0],[1,1,0],[1,0,0],[0,0,0]]],\"spatialReference\":{\"wkid\":4326}}";Polygonpolygon=PolygonBuilderEx.FromJson(json);// extrude the polygon by an offset to create a multipatchMultipatchmultipatch=GeometryEngine.Instance.ConstructMultipatchExtrude(polygon,2);// a different polygonjson="{\"hasZ\":true,\"rings\":[[[0,0,1],[0,1,2],[1,1,3],[1,0,4],[0,0,1]]],\"spatialReference\":{\"wkid\":4326}}";polygon=PolygonBuilderEx.FromJson(json);// extrude between z values to create a multipatchmultipatch=GeometryEngine.Instance.ConstructMultipatchExtrudeFromToZ(polygon,-10,20);// extrude along the axis defined by the coordinate to create a multipatchCoordinate3Dcoord=newCoordinate3D(10,18,-10);multipatch=GeometryEngine.Instance.ConstructMultipatchExtrudeAlongVector3D(polygon,coord);// build a polylinejson="{\"hasZ\":true,\"paths\":[[[400,800,1000],[800,1400,1500],[1200,800,2000],[1800,1800,2500],[2200,800,3000]]],\"spatialReference\":{\"wkid\":3857}}";Polylinepolyline=PolylineBuilderEx.FromJson(json);// extrude to a specific z value to create a multipatchmultipatch=GeometryEngine.Instance.ConstructMultipatchExtrudeToZ(polyline,500);Coordinate3DfromCoord=newCoordinate3D(50,50,-500);Coordinate3DtoCoord=newCoordinate3D(200,50,1000);// extrude between two coordinates to create a multipatchmultipatch=GeometryEngine.Instance.ConstructMultipatchExtrudeAlongLine(polyline,fromCoord,toCoord);
Multipatch Properties
// standard geometry propertiesboolhasZ=multipatch.HasZ;boolhasM=multipatch.HasM;boolhasID=multipatch.HasID;boolisEmpty=multipatch.IsEmpty;varsr=multipatch.SpatialReference;// number of patches (parts)intpatchCount=multiPatch.PartCount;// number of pointsintpointCount=multiPatch.PointCount;// retrieve the points as MapPointsReadOnlyPointCollectionpoints=multipatch.Points;// or as 3D CoordinatesIReadOnlyList<Coordinate3D>coordinates=multipatch.Copy3DCoordinatesToList();// multipatch materialsboolhasMaterials=multiPatch.HasMaterials;intmaterialCount=multiPatch.MaterialCount;// multipatch texturesboolhasTextures=multiPatch.HasTextures;inttextureVertexCount=multiPatch.TextureVertexCount;// normalsboolhasNormals=multiPatch.HasNormals;// properties for an individual patch (if multipatch.PartCount > 0)intpatchPriority=multiPatch.GetPatchPriority(patchIndex);PatchTypepatchType=multiPatch.GetPatchType(patchIndex);// patch pointsintpatchPointCount=multiPatch.GetPatchPointCount(patchIndex);intpointStartIndex=multiPatch.GetPatchStartPointIndex(patchIndex);// the patch Points are then the points in multipatch.Points from pointStartIndex to pointStartIndex + patchPointCount // if the multipatch has materials if(hasMaterials){// does the patch have a material? // materialIndex = -1 if the patch does not have a material; // 0 <= materialIndex < materialCount if the patch does have materialsintmaterialIndex=multipatch.GetPatchMaterialIndex(patchIndex);// properties for an individual material (if multipatch.MaterialCount > 0)varcolor=multipatch.GetMaterialColor(materialIndex);varedgeColor=multipatch.GetMaterialEdgeColor(materialIndex);varedgeWidth=multipatch.GetMaterialEdgeWidth(materialIndex);varshiness=multipatch.GetMaterialShininess(materialIndex);varpercent=multipatch.GetMaterialTransparencyPercent(materialIndex);varcullBackFace=multipatch.IsMaterialCullBackFace(materialIndex);// texture propertiesboolisTextured=multipatch.IsMaterialTextured(materialIndex);if(isTextured){intcolumnCount=multipatch.GetMaterialTextureColumnCount(materialIndex);introwCount=multipatch.GetMaterialTextureRowCount(materialIndex);intbpp=multipatch.GetMaterialTextureBytesPerPixel(materialIndex);TextureCompressionTypecompressionType=multipatch.GetMaterialTextureCompressionType(materialIndex);vartexture=multipatch.GetMaterialTexture(materialIndex);}}// texture coordinates (if multipatch.HasTextures = true)if(hasTextures){intnumPatchTexturePoints=multiPatch.GetPatchTextureVertexCount(patchIndex);varcoordinate2D=multiPatch.GetPatchTextureCoordinate(patchIndex,0);ICollection<Coordinate2D>textureCoordinates=newList<Coordinate2D>(numPatchTexturePoints);multiPatch.GetPatchTextureCoordinates(patchIndex,reftextureCoordinates);}// patch normals (if multipatch.HasNormals = true)if(hasNormals){// number of normal coordinates = multipatch.GetPatchPointCount(patchIndex)Coordinate3DpatchNormal=multipatch.GetPatchNormal(patchIndex,0);ICollection<Coordinate3D>normalCoordinates=newList<Coordinate3D>(patchPointCount);multipatch.GetPatchNormals(patchIndex,refnormalCoordinates);}
Construct Multipatch
// export to binary xmlstringbinaryXml=multiPatch.ToBinaryXml();// import from binaryXML - methods need to run on the MCTMultipatchbinaryMultipatch=MultipatchBuilderEx.FromBinaryXml(binaryXml);// xml export / importstringxml=multiPatch.ToXml();MultipatchxmlMultipatch=MultipatchBuilderEx.FromXml(xml);// esriShape export/importbyte[]buffer=multiPatch.ToEsriShape();MultipatchesriPatch=MultipatchBuilderEx.FromEsriShape(buffer);// or use GeometryEngineMultipatchpatchImport=GeometryEngine.Instance.ImportFromEsriShape(EsriShapeImportFlags.EsriShapeImportDefaults,buffer,multiPatch.SpatialReference)asMultipatch;
Construct Multipatch via MultipatchBuilderEx
varcoords_face1=newList<Coordinate3D>(){newCoordinate3D(12.495461061000071,41.902603910000039,62.552700000000186),newCoordinate3D(12.495461061000071,41.902603910000039,59.504700000004959),newCoordinate3D(12.495461061000071,41.902576344000067,59.504700000004959),newCoordinate3D(12.495461061000071,41.902603910000039,62.552700000000186),newCoordinate3D(12.495461061000071,41.902576344000067,59.504700000004959),newCoordinate3D(12.495461061000071,41.902576344000067,62.552700000000186),};varcoords_face2=newList<Coordinate3D>(){newCoordinate3D(12.495461061000071,41.902576344000067,62.552700000000186),newCoordinate3D(12.495461061000071,41.902576344000067,59.504700000004959),newCoordinate3D(12.495488442000067,41.902576344000067,59.504700000004959),newCoordinate3D(12.495461061000071,41.902576344000067,62.552700000000186),newCoordinate3D(12.495488442000067,41.902576344000067,59.504700000004959),newCoordinate3D(12.495488442000067,41.902576344000067,62.552700000000186),};varcoords_face3=newList<Coordinate3D>(){newCoordinate3D(12.495488442000067,41.902576344000067,62.552700000000186),newCoordinate3D(12.495488442000067,41.902576344000067,59.504700000004959),newCoordinate3D(12.495488442000067,41.902603910000039,59.504700000004959),newCoordinate3D(12.495488442000067,41.902576344000067,62.552700000000186),newCoordinate3D(12.495488442000067,41.902603910000039,59.504700000004959),newCoordinate3D(12.495488442000067,41.902603910000039,62.552700000000186),};varcoords_face4=newList<Coordinate3D>(){newCoordinate3D(12.495488442000067,41.902576344000067,59.504700000004959),newCoordinate3D(12.495461061000071,41.902576344000067,59.504700000004959),newCoordinate3D(12.495461061000071,41.902603910000039,59.504700000004959),newCoordinate3D(12.495488442000067,41.902576344000067,59.504700000004959),newCoordinate3D(12.495461061000071,41.902603910000039,59.504700000004959),newCoordinate3D(12.495488442000067,41.902603910000039,59.504700000004959),};varcoords_face5=newList<Coordinate3D>(){newCoordinate3D(12.495488442000067,41.902603910000039,59.504700000004959),newCoordinate3D(12.495461061000071,41.902603910000039,59.504700000004959),newCoordinate3D(12.495461061000071,41.902603910000039,62.552700000000186),newCoordinate3D(12.495488442000067,41.902603910000039,59.504700000004959),newCoordinate3D(12.495461061000071,41.902603910000039,62.552700000000186),newCoordinate3D(12.495488442000067,41.902603910000039,62.552700000000186),};varcoords_face6=newList<Coordinate3D>(){newCoordinate3D(12.495488442000067,41.902603910000039,62.552700000000186),newCoordinate3D(12.495461061000071,41.902603910000039,62.552700000000186),newCoordinate3D(12.495461061000071,41.902576344000067,62.552700000000186),newCoordinate3D(12.495488442000067,41.902603910000039,62.552700000000186),newCoordinate3D(12.495461061000071,41.902576344000067,62.552700000000186),newCoordinate3D(12.495488442000067,41.902576344000067,62.552700000000186),};// materialsvarmaterialRed=newBasicMaterial();materialRed.Color=System.Windows.Media.Colors.Red;varmaterialTransparent=newBasicMaterial();materialTransparent.Color=System.Windows.Media.Colors.White;materialTransparent.TransparencyPercent=80;varblueTransparent=newBasicMaterial(materialTransparent);blueTransparent.Color=System.Windows.Media.Colors.SkyBlue;// create a list of patch objectsvarpatches=newList<Patch>();// create the multipatchBuilderEx objectvarmpb=newArcGIS.Core.Geometry.MultipatchBuilderEx();// make each patch using the appropriate coordinates and add to the patch listvarpatch=mpb.MakePatch(PatchType.Triangles);patch.Coords=coords_face1;patches.Add(patch);patch=mpb.MakePatch(PatchType.Triangles);patch.Coords=coords_face2;patches.Add(patch);patch=mpb.MakePatch(PatchType.Triangles);patch.Coords=coords_face3;patches.Add(patch);patch=mpb.MakePatch(PatchType.Triangles);patch.Coords=coords_face4;patches.Add(patch);patch=mpb.MakePatch(PatchType.Triangles);patch.Coords=coords_face5;patches.Add(patch);patch=mpb.MakePatch(PatchType.Triangles);patch.Coords=coords_face6;patches.Add(patch);patches[0].Material=materialRed;patches[1].Material=materialTransparent;patches[2].Material=materialRed;patches[3].Material=materialRed;patches[4].Material=materialRed;patches[5].Material=blueTransparent;// assign the patches to the multipatchBuildermpb.Patches=patches;// check which patches currently contain the materialvarred=mpb.QueryPatchIndicesWithMaterial(materialRed);// red should be [0, 2, 3, 4]// call ToGeometry to get the multipatchmultipatch=mpb.ToGeometry()asMultipatch;
Construct Multipatch from another Multipatch
// create the multipatchBuilderEx objectvarbuilder=newArcGIS.Core.Geometry.MultipatchBuilderEx(multipatch);// check some propertiesboolhasM=builder.HasM;boolhasZ=builder.HasZ;boolhasID=builder.HasID;boolisEmpty=builder.IsEmpty;boolhasNormals=builder.HasNormals;varpatches=builder.Patches;intpatchCount=patches.Count;// if there's some patchesif(patchCount>0){intpointCount=builder.GetPatchPointCount(0);// replace the first point in the first patchif(pointCount>0){// get the first pointvarpt=builder.GetPoint(0,0);builder.SetPoint(0,0,newPoint);}// check which patches currently contain the texturevartexture=builder.QueryPatchIndicesWithTexture(brickTextureResource);// assign a texture materialpatches[0].Material=brickMaterialTexture;}// update the builder for M awarenessbuilder.HasM=true;// synchronize the patch attributes to match the builder attributes// in this instance because we just set HasM to true on the builder, each patch will now get a default M value for it's set of coordinatesbuilder.SynchronizeAttributeAwareness();// call ToGeometry to get the multipatchmultipatch=builder.ToGeometry()asMultipatch;// multipatch.HasM will be true
Construct Multipatch from a 3D model file
try{varmodel=ArcGIS.Core.Geometry.MultipatchBuilderEx.From3DModelFile(@"c:\Temp\My3dModelFile.dae");boolmodelIsEmpty=model.IsEmpty;}catch(FileNotFoundException){// file not found}catch(ArgumentException){// File extension is unsupported or cannot read the file}
Construct 3D special Multipatch shapes
varsr=MapView.Active.Map.SpatialReference;varextent=MapView.Active.Extent;varcenter=extent.Center;varcenterZ=MapPointBuilderEx.CreateMapPoint(center.X,center.Y,500,sr);// cubemultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Cube,centerZ,200,sr);// tetrahedronmultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Tetrahedron,centerZ,200,sr);// diamondmultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Diamond,centerZ,200,sr);// hexagonmultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Hexagon,centerZ,200,sr);// sphere framemultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.SphereFrame,centerZ,200,0.8,sr);// spheremultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Sphere,centerZ,200,0.8,sr);// cylindermultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Cylinder,centerZ,200,0.8,sr);// conemultipatch=ArcGIS.Core.Geometry.MultipatchBuilderEx.CreateMultipatch(MultipatchConstructType.Cone,centerZ,200,0.8,sr);// use the builder to add materials or textures// - create a cone with a materialbuilder=newMultipatchBuilderEx(MultipatchConstructType.Cone,centerZ,200,0.8,sr);BasicMaterialfaceMaterial=newBasicMaterial();faceMaterial.Color=System.Windows.Media.Color.FromRgb(255,0,0);faceMaterial.Shininess=150;faceMaterial.TransparencyPercent=50;faceMaterial.EdgeWidth=20;foreach(varpatchinbuilder.Patches)patch.Material=faceMaterial;multipatch=builder.ToGeometry()asMultipatch;
Create BasicMaterial
// Create BasicMaterial with default valuesBasicMaterialmaterial=newBasicMaterial();System.Windows.Media.Colorcolor=material.Color;// color = Colors.BlackSystem.Windows.Media.ColoredgeColor=material.EdgeColor;// edgeColor = Colors.BlackintedgeWidth=material.EdgeWidth;// edgeWidth = 0inttransparency=material.TransparencyPercent;// transparency = 0intshininess=material.Shininess;// shininess = 0boolcullBackFace=material.IsCullBackFace;// cullBackFace = false// Modify the propertiesmaterial.Color=System.Windows.Media.Colors.Red;material.EdgeColor=System.Windows.Media.Colors.Blue;material.EdgeWidth=10;material.TransparencyPercent=50;material.Shininess=25;material.IsCullBackFace=true;
Create BasicMaterial with JPEG texture
// read the jpeg into a buffer//At 3.0 you need https://www.nuget.org/packages/Microsoft.Windows.Compatibility//System.DrawingSystem.Drawing.Imageimage=System.Drawing.Image.FromFile(@"C:\temp\myImageFile.jpg");MemoryStreammemoryStream=newMemoryStream();System.Drawing.Imaging.ImageFormatformat=System.Drawing.Imaging.ImageFormat.Jpeg;image.Save(memoryStream,format);byte[]imageBuffer=memoryStream.ToArray();varjpgTexture=newJPEGTexture(imageBuffer);// texture propertiesintbpp=jpgTexture.BytesPerPixel;intcolumnCount=jpgTexture.ColumnCount;introwCount=jpgTexture.RowCount;// build the textureResource and the materialBasicMaterialmaterial=newBasicMaterial();material.TextureResource=newTextureResource(jpgTexture);
Create BasicMaterial with Uncompressed texture
UncompressedTextureuncompressedTexture1=newUncompressedTexture(newbyte[10*12*3],10,12,3);// texture propertiesintbpp=uncompressedTexture1.BytesPerPixel;intcolumnCount=uncompressedTexture1.ColumnCount;introwCount=uncompressedTexture1.RowCount;// build the textureResource and the materialTextureResourcetr=newTextureResource(uncompressedTexture1);BasicMaterialmaterial=newBasicMaterial();material.TextureResource=tr;
Get the texture image of a multipatch
// <summary>// This method gets the material texture image of a multipatch.// </summary>// <param name="multipatch">The input multipatch.</param>// <param name="patchIndex">The index of the patch (part) for which to get the material texture.</param>publicvoidGetMultipatchTextureImage(Multipatchmultipatch,intpatchIndex){intmaterialIndex=multipatch.GetPatchMaterialIndex(patchIndex);if(!multipatch.IsMaterialTextured(materialIndex))return;TextureCompressionTypecompressionType=multipatch.GetMaterialTextureCompressionType(materialIndex);stringext=compressionType==TextureCompressionType.CompressionJPEG?".jpg":".dat";byte[]textureBuffer=multipatch.GetMaterialTexture(materialIndex);StreamimageStream=newMemoryStream(textureBuffer);System.Drawing.Imageimage=System.Drawing.Image.FromStream(imageStream);image.Save(@"C:\temp\myImage"+ext);}
Get the normal coordinate of a multipatch
// <summary>// This method gets the normal coordinate of a multipatch and does something with it.// </summary>// <param name="multipatch">The input multipatch.</param>// <param name="patchIndex">The index of the patch (part) for which to get the normal.</param>publicvoidDoSomethingWithNormalCoordinate(Multipatchmultipatch,intpatchIndex){if(multipatch.HasNormals){// If the multipatch has normals, then the number of normals is equal to the number of points.intnumNormals=multipatch.GetPatchPointCount(patchIndex);for(intpointIndex=0;pointIndex<numNormals;pointIndex++){Coordinate3Dnormal=multipatch.GetPatchNormal(patchIndex,pointIndex);// Do something with the normal coordinate.}}}
Get the normals of a multipatch
// <summary>// This method gets the normal coordinate of a multipatch and does something with it.// </summary>// <param name="multipatch">The input multipatch.</param>publicvoidDoSomethingWithNormalCoordinates(Multipatchmultipatch){if(multipatch.HasNormals){// Allocate the list only onceintnumPoints=multipatch.PointCount;ICollection<Coordinate3D>normals=newList<Coordinate3D>(numPoints);// The parts of a multipatch are also called patchesintnumPatches=multipatch.PartCount;for(intpatchIndex=0;patchIndex<numPatches;patchIndex++){multipatch.GetPatchNormals(patchIndex,refnormals);// Do something with the normals for this patch.}}}
Get the material properties of a multipatch
publicvoidGetMaterialProperties(Multipatchmultipatch,intpatchIndex){if(multipatch.HasMaterials){// Get the material index for the specified patch.intmaterialIndex=multipatch.GetPatchMaterialIndex(patchIndex);System.Windows.Media.Colorcolor=multipatch.GetMaterialColor(materialIndex);inttranparencyPercent=multipatch.GetMaterialTransparencyPercent(materialIndex);boolisBackCulled=multipatch.IsMaterialCullBackFace(materialIndex);if(multipatch.IsMaterialTextured(materialIndex)){intbpp=multipatch.GetMaterialTextureBytesPerPixel(materialIndex);intcolumnCount=multipatch.GetMaterialTextureColumnCount(materialIndex);introwCount=multipatch.GetMaterialTextureRowCount(materialIndex);}}}
Multiparts
Get the individual parts of a multipart feature
publicIEnumerable<Geometry>MultipartToSinglePart(GeometryinputGeometry){// list holding the part(s) of the input geometryList<Geometry>singleParts=newList<Geometry>();// check if the input is a null pointer or if the geometry is emptyif(inputGeometry==null||inputGeometry.IsEmpty)returnsingleParts;// based on the type of geometry, take the parts/points and add them individually into a listswitch(inputGeometry.GeometryType){caseGeometryType.Envelope:singleParts.Add(inputGeometry.Clone()asEnvelope);break;caseGeometryType.Multipatch:singleParts.Add(inputGeometry.Clone()asMultipatch);break;caseGeometryType.Multipoint:varmultiPoint=inputGeometryasMultipoint;foreach(varpointinmultiPoint.Points){// add each point of collection as a standalone point into the listsingleParts.Add(point);}break;caseGeometryType.Point:singleParts.Add(inputGeometry.Clone()asMapPoint);break;caseGeometryType.Polygon:varpolygon=inputGeometryasPolygon;foreach(varpolygonPartinpolygon.Parts){// use the PolygonBuilderEx turning the segments into a standalone // polygon instancesingleParts.Add(PolygonBuilderEx.CreatePolygon(polygonPart));}break;caseGeometryType.Polyline:varpolyline=inputGeometryasPolyline;foreach(varpolylinePartinpolyline.Parts){// use the PolylineBuilderEx turning the segments into a standalone// polyline instancesingleParts.Add(PolylineBuilderEx.CreatePolyline(polylinePart));}break;caseGeometryType.Unknown:break;default:break;}returnsingleParts;}
Get the outermost rings of a polygon
publicPolygonGetOutermostRings(PolygoninputPolygon){if(inputPolygon==null||inputPolygon.IsEmpty)returnnull;List<Polygon>internalRings=newList<Polygon>();// explode the parts of the polygon into a list of individual geometries// see the "Get the individual parts of a multipart feature"// snippet for MultipartToSinglePartvarparts=MultipartToSinglePart(inputPolygon);// get an enumeration of clockwise geometries (area > 0) ordered by the areavarclockwiseParts=parts.Where(geom =>((Polygon)geom).Area>0).OrderByDescending(geom =>((Polygon)geom).Area);// for each of the exterior ringsforeach(varpartinclockwiseParts){// add the first (the largest) ring into the internal collectionif(internalRings.Count==0)internalRings.Add(partasPolygon);// use flag to indicate if current part is within the already selection polygonsboolisWithin=false;foreach(varitemininternalRings){if(GeometryEngine.Instance.Within(part,item))isWithin=true;}// if the current polygon is not within any polygon of the internal collection// then it is disjoint and needs to be added to if(isWithin==false)internalRings.Add(partasPolygon);}PolygonBuilderExouterRings=newPolygonBuilderEx();// now assemble a new polygon geometry based on the internal polygon collectionforeach(varringininternalRings){outerRings.AddParts(ring.Parts);}// return the final geometry of the outer ringsreturnouterRings.ToGeometry();}
Retrieve Geometry from Geodatabase
Retrieve Geometry from Geodatabase
// methods need to run on the MCTArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{try{// open a gdbusing(ArcGIS.Core.Data.Geodatabasegdb=newArcGIS.Core.Data.Geodatabase(newFileGeodatabaseConnectionPath(newUri(@"c:\Temp\MyDatabase.gdb")))){//Open a featureClass using(ArcGIS.Core.Data.FeatureClassfeatureClass=gdb.OpenDataset<ArcGIS.Core.Data.FeatureClass>("Polygon")){ArcGIS.Core.Data.QueryFilterfilter=newArcGIS.Core.Data.QueryFilter(){WhereClause="OBJECTID = 6"};// get the rowusing(ArcGIS.Core.Data.RowCursorrowCursor=featureClass.Search(filter,false)){while(rowCursor.MoveNext()){using(varrow=rowCursor.Current){longoid=row.GetObjectID();// get the shape from the rowArcGIS.Core.Data.Featurefeature=rowasArcGIS.Core.Data.Feature;Polygonpolygon=feature.GetShape()asPolygon;// do something here}}}}}}catch(Exceptionex){// error - handle appropriately}});
Import, Export Geometries
Import and Export Geometries to well-known Text
// create a point with z, mMapPointpoint=MapPointBuilderEx.CreateMapPoint(100,200,300,400,SpatialReferences.WebMercator);// set the flagsWktExportFlagswktExportFlags=WktExportFlags.WktExportDefaults;WktImportFlagswktImportFlags=WktImportFlags.WktImportDefaults;// export and importstringwktString=GeometryEngine.Instance.ExportToWKT(wktExportFlags,point);MapPointimportPoint=GeometryEngine.Instance.ImportFromWKT(wktImportFlags,wktString,SpatialReferences.WebMercator)asMapPoint;doublex=importPoint.X;// x = 100doubley=importPoint.Y;// y = 200boolhasZ=importPoint.HasZ;// hasZ = truedoublez=importPoint.Z;// z = 300boolhasM=importPoint.HasM;// hasM = truedoublem=importPoint.M;// m = 400// export without zWktExportFlagsexportFlagsNoZ=WktExportFlags.WktExportStripZs;wktString=GeometryEngine.Instance.ExportToWKT(exportFlagsNoZ,point);importPoint=GeometryEngine.Instance.ImportFromWKT(wktImportFlags,wktString,SpatialReferences.WebMercator)asMapPoint;x=importPoint.X;// x = 100y=importPoint.Y;// y = 200hasZ=importPoint.HasZ;// hasZ = falsez=importPoint.Z;// z = 0hasM=importPoint.HasM;// hasM = truem=importPoint.M;// m = 400// export without mWktExportFlagsexportFlagsNoM=WktExportFlags.WktExportStripMs;wktString=GeometryEngine.Instance.ExportToWKT(exportFlagsNoM,point);importPoint=GeometryEngine.Instance.ImportFromWKT(wktImportFlags,wktString,SpatialReferences.WebMercator)asMapPoint;x=importPoint.X;// x = 100y=importPoint.Y;// y = 200hasZ=importPoint.HasZ;// hasZ = truez=importPoint.Z;// z = 300hasM=importPoint.HasM;// hasM = falsem=importPoint.M;// m = Nan// export without z, mwktString=GeometryEngine.Instance.ExportToWKT(exportFlagsNoZ|exportFlagsNoM,point);importPoint=GeometryEngine.Instance.ImportFromWKT(wktImportFlags,wktString,SpatialReferences.WebMercator)asMapPoint;x=importPoint.X;// x = 100y=importPoint.Y;// y = 200hasZ=importPoint.HasZ;// hasZ = falsez=importPoint.Z;// z = 0hasM=importPoint.HasM;// hasM = falsem=importPoint.M;// m = Nan
Import and Export Geometries to well-known Binary
// create a polylineList<Coordinate2D>coords=newList<Coordinate2D>{newCoordinate2D(0,0),newCoordinate2D(0,1),newCoordinate2D(1,1),newCoordinate2D(1,0)};Polylinepolyline=PolylineBuilderEx.CreatePolyline(coords,SpatialReferences.WGS84);WkbExportFlagswkbExportFlags=WkbExportFlags.WkbExportDefaults;WkbImportFlagswkbImportFlags=WkbImportFlags.WkbImportDefaults;// export and importbyte[]buffer=GeometryEngine.Instance.ExportToWKB(wkbExportFlags,polyline);Geometrygeometry=GeometryEngine.Instance.ImportFromWKB(wkbImportFlags,buffer,SpatialReferences.WGS84);PolylineimportPolyline=geometryasPolyline;// alternatively, determine the size for the bufferintbufferSize=GeometryEngine.Instance.GetWKBSize(wkbExportFlags,polyline);buffer=newbyte[bufferSize];// exportbufferSize=GeometryEngine.Instance.ExportToWKB(wkbExportFlags,polyline,refbuffer);// importimportPolyline=GeometryEngine.Instance.ImportFromWKB(wkbImportFlags,buffer,SpatialReferences.WGS84)asPolyline;
Import and Export Geometries to EsriShape
// create an envelopeList<MapPoint>coordsZM=newList<MapPoint>{MapPointBuilderEx.CreateMapPoint(1001,1002,1003,1004),MapPointBuilderEx.CreateMapPoint(2001,2002,Double.NaN,2004),MapPointBuilderEx.CreateMapPoint(3001,-3002,3003,3004),MapPointBuilderEx.CreateMapPoint(1001,-4002,4003,4004)};Envelopeenvelope=EnvelopeBuilderEx.CreateEnvelope(coordsZM[0],coordsZM[2],SpatialReferences.WGS84);// export and importEsriShapeExportFlagsexportFlags=EsriShapeExportFlags.EsriShapeExportDefaults;EsriShapeImportFlagsimportFlags=EsriShapeImportFlags.EsriShapeImportDefaults;byte[]buffer=GeometryEngine.Instance.ExportToEsriShape(exportFlags,envelope);PolygonimportedPolygon=GeometryEngine.Instance.ImportFromEsriShape(importFlags,buffer,envelope.SpatialReference)asPolygon;EnvelopeimportedEnvelope=importedPolygon.Extent;// export without z,mbuffer=GeometryEngine.Instance.ExportToEsriShape(EsriShapeExportFlags.EsriShapeExportStripZs|EsriShapeExportFlags.EsriShapeExportStripMs,envelope);importedPolygon=GeometryEngine.Instance.ImportFromEsriShape(importFlags,buffer,SpatialReferences.WGS84)asPolygon;importedEnvelope=importedPolygon.Extent;boolhasZ=importedEnvelope.HasZ;// hasZ = falseboolhasM=importedEnvelope.HasM;// hasM = false// export with shapeSizeintbufferSize=GeometryEngine.Instance.GetEsriShapeSize(exportFlags,envelope);buffer=newbyte[bufferSize];bufferSize=GeometryEngine.Instance.ExportToEsriShape(exportFlags,envelope,refbuffer);importedPolygon=GeometryEngine.Instance.ImportFromEsriShape(importFlags,buffer,envelope.SpatialReference)asPolygon;importedEnvelope=importedPolygon.Extent;// or use the envelope and envelopeBuilderEx classesbuffer=envelope.ToEsriShape();// buffer represents a polygon as there is not an envelope Esri shape buffer// EnvelopeBuilderEx.FromEsriShape takes a polygon Esri shape buffer and returns the extent of the polygon.importedEnvelope=EnvelopeBuilderEx.FromEsriShape(buffer);
Import and Export Geometries to JSON
// MapPointstringinputString="{\"x\":1,\"y\":2,\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326}}";Geometrygeometry=GeometryEngine.Instance.ImportFromJson(JsonImportFlags.JsonImportDefaults,inputString);MapPointimportPoint=geometryasMapPoint;// importPoint = 1, 2// importPoint.SpatialReference.WKid = 4326// use the MapPointBuilderEx convenience methodMapPointimportPoint2=MapPointBuilderEx.FromJson(inputString);// importPoint2 = 1, 2// impointPoint2.SpatialReference.Wkid = 4326stringoutputString=GeometryEngine.Instance.ExportToJson(JsonExportFlags.JsonExportDefaults,importPoint);// outputString =// "{\"x\":1,\"y\":2,\"spatialReference\":{\"wkid\":4326,\"latestWkid\":4326}}"stringoutputString2=importPoint.ToJson();inputString="{\"spatialReference\":{\"wkid\":4326},\"z\":3,\"m\":4,\"x\":1,\"y\":2}";importPoint=GeometryEngine.Instance.ImportFromJson(JsonImportFlags.JsonImportDefaults,inputString)asMapPoint;// importPoint.HasM = true// importPoint.HasZ = true// importPoint.X = 1// importPoint.Y = 2// importPoint.M = 4// importPoint.Z = 3importPoint2=MapPointBuilderEx.FromJson(inputString);// export to json - skip spatial referenceoutputString=GeometryEngine.Instance.ExportToJson(JsonExportFlags.JsonExportSkipCRS,importPoint);// outputString = "{\"x\":1,\"y\":2,\"z\":3,\"m\":4}"// export from mappoint, skipping the sr - same as GeometryEngine.Instance.ExportToJson w JsonExportFlags.JsonExportSkipCRSoutputString2=importPoint.ToJson(true);//// Multipoint//List<Coordinate2D>coords=newList<Coordinate2D>(){newCoordinate2D(100,200),newCoordinate2D(201,300),newCoordinate2D(301,400),newCoordinate2D(401,500)};Multipointmultipoint=MultipointBuilderEx.CreateMultipoint(coords,SpatialReferences.WebMercator);inputString="{\"points\":[[100,200],[201,300],[301,400],[401,500]],\"spatialReference\":{\"wkid\":3857}}";MultipointimportMultipoint=GeometryEngine.Instance.ImportFromJson(JsonImportFlags.JsonImportDefaults,inputString)asMultipoint;// importMultipoint.IsEqual(multipoint) = trueReadOnlyPointCollectionpoints=importMultipoint.Points;// points.Count = 4// points[0] = 100, 200// points[1] = 201, 300// points[2] = 301, 400// points[3] = 401, 500// use the MultipointbuilderEx convenience methodMultipointimportMultipoint2=MultipointBuilderEx.FromJson(inputString);// importMultipoint2.IsEqual(multipoint) = true// export to jsonoutputString=GeometryEngine.Instance.ExportToJson(JsonExportFlags.JsonExportDefaults,multipoint);// outputString = inputString// or use the multipoint itselfoutputString2=multipoint.ToJson();//// Polyline//Polylinepolyline=PolylineBuilderEx.CreatePolyline(coords,SpatialReferences.WebMercator);// export without the spatial referenceoutputString=GeometryEngine.Instance.ExportToJson(JsonExportFlags.JsonExportSkipCRS,polyline);// importgeometry=GeometryEngine.Instance.ImportFromJson(JsonImportFlags.JsonImportDefaults,outputString);PolylineimportPolyline=geometryasPolyline;// importPolyline.SpatialReference = nullpoints=importPolyline.Points;// points.Count = 4// points[0] = 100, 200// points[1] = 201, 300// points[2] = 301, 400// points[3] = 401, 500// use the polylineBuilderEx convenience method PolylineimportPolyline2=PolylineBuilderEx.FromJson(outputString);// importPolyline2 = importPolylineoutputString2=importPolyline2.ToJson();// outputString2 = outputString//// Polygon//Polygonpolygon=PolygonBuilderEx.CreatePolygon(coords,SpatialReferences.WebMercator);// export without the spatial referenceoutputString=GeometryEngine.Instance.ExportToJson(JsonExportFlags.JsonExportSkipCRS,polygon);// importgeometry=GeometryEngine.Instance.ImportFromJson(JsonImportFlags.JsonImportDefaults,outputString);PolygonimportPolygon=geometryasPolygon;// importPolygon.SpatialReference = nullpoints=importPolygon.Points;// points.Count = 5// polygonBuilderEx convenience methodPolygonimportPolyon2=PolygonBuilderEx.FromJson(outputString);// importPolygon2 = importPolygon// export from the polygonoutputString2=importPolyon2.ToJson(true);// Empty polygonpolygon=PolygonBuilderEx.CreatePolygon(SpatialReferences.WebMercator);outputString=GeometryEngine.Instance.ExportToJson(JsonExportFlags.JsonExportDefaults,polygon);importPolygon=GeometryEngine.Instance.ImportFromJson(JsonImportFlags.JsonImportDefaults,outputString)asPolygon;// importPolygon.IsEmpty = true// importPolygon.SpatialReference.Wkid = 3857
// create from wkidGeographicTransformationgt1478=ArcGIS.Core.Geometry.GeographicTransformation.Create(1478);stringname=gt1478.Name;stringwkt=gt1478.Wkt;intwkid=gt1478.Wkid;// create from wktGeographicTransformationanother_gt1478=ArcGIS.Core.Geometry.GeographicTransformation.Create(wkt);// inverseGeographicTransformationinverse_gt148=another_gt1478.GetInverse()asGeographicTransformation;boolisForward=inverse_gt148.IsForward;
Create Composite Geographic Transformation
// Create singleton from wkidCompositeGeographicTransformationcgt=ArcGIS.Core.Geometry.CompositeGeographicTransformation.Create(108272);intcount=cgt.Count;// count = 1IList<GeographicTransformation>gts=cgt.TransformationsasIList<GeographicTransformation>;gts.Add(ArcGIS.Core.Geometry.GeographicTransformation.Create(1437,false));count=cgt.Count;// count = 2// create from an enumerationCompositeGeographicTransformationanother_cgt=ArcGIS.Core.Geometry.CompositeGeographicTransformation.Create(gts);GeographicTransformationgt0=another_cgt[0];GeographicTransformationgt1=another_cgt[1];// get the inverseCompositeGeographicTransformationinversed_cgt=another_cgt.GetInverse()asCompositeGeographicTransformation;// inversed_cgt[0] is same as gt1// inversed_cgt[1] is same as gt0varwkt=gt0.Wkt;// create from string CompositeGeographicTransformationthird_cgt=ArcGIS.Core.Geometry.CompositeGeographicTransformation.Create(wkt,gt0.IsForward);count=third_cgt.Count;// count = 1// create from josnstringjson=cgt.ToJson();CompositeGeographicTransformationjoson_cgt=DatumTransformation.CreateFromJson(json)asCompositeGeographicTransformation;
Create Projection Transformation
// methods need to be on the MCTArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{SpatialReferencesr4267=SpatialReferenceBuilder.CreateSpatialReference(4267);SpatialReferencesr4326=SpatialReferences.WGS84;SpatialReferencesr3857=SpatialReferences.WebMercator;// Create transformation from 4267 -> 3857ProjectionTransformationprojTransFromSRs=ArcGIS.Core.Geometry.ProjectionTransformation.Create(sr4267,sr3857);// create an envelopeEnvelopeenv=EnvelopeBuilderEx.CreateEnvelope(newCoordinate2D(2,2),newCoordinate2D(3,3),sr4267);// Project with one geo transform 4267 -> 3857EnvelopeprojectedEnvEx=GeometryEngine.Instance.ProjectEx(env,projTransFromSRs)asEnvelope;// Create inverse transformation, 3857 -> 4267ProjectionTransformationprojTransFromSRsInverse=ArcGIS.Core.Geometry.ProjectionTransformation.Create(sr3857,sr4267);// Project the projected envelope back using the inverse transformationEnvelopeprojectedEnvBack=GeometryEngine.Instance.ProjectEx(projectedEnvEx,projTransFromSRsInverse)asEnvelope;boolisEqual=env.IsEqual(projectedEnvBack);});
Create HV Datum Transformation
// Create from wkidHVDatumTransformationhv110018=HVDatumTransformation.Create(110018);intwkid=hv110018.Wkid;boolisForward=hv110018.IsForward;// isForward = truestringname=hv110018.Name;// Name = WGS_1984_To_WGS_1984_EGM2008_1x1_Height// Create from wktstringwkt=hv110018.Wkt;HVDatumTransformationhv110018FromWkt=HVDatumTransformation.Create(wkt);// Get the inverseHVDatumTransformationhv110018Inverse=hv110018.GetInverse()asHVDatumTransformation;// hv110018Inverse.IsForward = false
Create Composite HV Datum Transformation
HVDatumTransformationhv1=HVDatumTransformation.Create(108034);HVDatumTransformationhv2=HVDatumTransformation.Create(108033,false);List<HVDatumTransformation>hvs=newList<HVDatumTransformation>(){hv1,hv2};// create from enumerationCompositeHVDatumTransformationcompositehv=CompositeHVDatumTransformation.Create(hvs);intcount=compositehv.Count;// count = 2List<HVDatumTransformation>transforms=compositehv.TransformationsasList<HVDatumTransformation>;HVDatumTransformationtranform=transforms[0];// transform.Wkid = 108034// get inverseCompositeHVDatumTransformationinverse_compositehv=compositehv.GetInverse()asCompositeHVDatumTransformation;// create from xmlstringxml=compositehv.ToXml();//At 2.x - CompositeHVDatumTransformation xml_compositehv =// CompositeHVDatumTransformation.CreateFromXML(xml);varxml_compositehv=CompositeHVDatumTransformation.CreateFromXml(xml);// create from jsonstringjson=compositehv.ToJson();CompositeHVDatumTransformationjson_compositehv=DatumTransformation.CreateFromJson(json)asCompositeHVDatumTransformation;
Determine Transformations
// methods need to run on the MCTArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{//// find the first transformation used between spatial references 4267 and 4326//SpatialReferencesr4267=SpatialReferenceBuilder.CreateSpatialReference(4267);SpatialReferencesr4326=SpatialReferences.WGS84;List<ProjectionTransformation>transformations=ProjectionTransformation.FindTransformations(sr4267,sr4326);// transformations.Count = 1ProjectionTransformationprojTrans=transformations[0];CompositeGeographicTransformationcompositeGT=projTrans.TransformationasCompositeGeographicTransformation;GeographicTransformationgt=compositeGT[0];// gt.Wkid = 15851// gt.Name = "NAD_1927_To_WGS_1984_79_CONUS"// gt.IsForward = true//// find the first five transformation used between spatial references 4267 and 4326//transformations=ProjectionTransformation.FindTransformations(sr4267,sr4326,numResults:5);// transformations.Count = 5projTrans=transformations[0];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 1// compositeGT[0].Wkid = 15851// compositeGT[0].Name = "NAD_1927_To_WGS_1984_79_CONUS"// compositeGT[0].IsForward = trueprojTrans=transformations[1];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 1// compositeGT[0].Wkid = 1173// compositeGT[0].Name = "NAD_1927_To_WGS_1984_4"// compositeGT[0].IsForward = trueprojTrans=transformations[2];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 1// compositeGT[0].Wkid = 1172// compositeGT[0].Name = "NAD_1927_To_WGS_1984_3"// compositeGT[0].IsForward = trueprojTrans=transformations[3];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 2// compositeGT[0].Wkid = 1241// compositeGT[0].Name = "NAD_1927_To_NAD_1983_NADCON"// compositeGT[0].IsForward = true// compositeGT[1].Wkid = 108190// compositeGT[1].Name = "WGS_1984_(ITRF00)_To_NAD_1983"// compositeGT[1].IsForward = falseprojTrans=transformations[4];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 2// compositeGT[0].Wkid = 1241// compositeGT[0].Name = "NAD_1927_To_NAD_1983_NADCON"// compositeGT[0].IsForward = true// compositeGT[1].Wkid = 1515// compositeGT[1].Name = "NAD_1983_To_WGS_1984_5"// compositeGT[1].IsForward = true//// find the first transformation used between spatial// references 4267 and 4326 within Alaska//// AlaskaEnvelopeenvelope=EnvelopeBuilderEx.CreateEnvelope(-161,61,-145,69);transformations=ProjectionTransformation.FindTransformations(sr4267,sr4326,envelope);// transformations.Count = 1projTrans=transformations[0];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 2// compositeGT[0].Wkid = 1243// compositeGT[0].Name = "NAD_1927_To_NAD_1983_Alaska"// compositeGT[0].IsForward = true// compositeGT[1].Wkid = 108190// compositeGT[1].Name = "WGS_1984_(ITRF00)_To_NAD_1983"// compositeGT[1].IsForward = false//// find the first geographic transformation used between two spatial references with VCS (use vertical = false)//SpatialReferenceinSR=SpatialReferenceBuilder.CreateSpatialReference(4269,115702);SpatialReferenceoutSR=SpatialReferenceBuilder.CreateSpatialReference(4326,3855);// Even though each spatial reference has a VCS,// vertical = false should return geographic transformations.transformations=ProjectionTransformation.FindTransformations(inSR,outSR);// transformations.Count = 1projTrans=transformations[0];compositeGT=projTrans.TransformationasCompositeGeographicTransformation;// compositeGT.Count = 1// compositeGT[0].Wkid = 108190// compositeGT[0].Name = ""WGS_1984_(ITRF00)_To_NAD_1983"// compositeGT[0].IsForward = false//// find the first vertical transformation used between two spatial references with VCS (use vertical = true)//transformations=ProjectionTransformation.FindTransformations(inSR,outSR,vertical:true);// transformations.Count = 1projTrans=transformations[0];CompositeHVDatumTransformationcompositeHV=projTrans.TransformationasCompositeHVDatumTransformation;// compositeHV.Count = 2// compositeHV[0].Wkid = 1188// compositeHV[0].Name = "NAD_1983_To_WGS_1984_1"// compositeHV[0].IsForward = true// compositeHV[1].Wkid = 110019// compositeHV[1].Name = "WGS_1984_To_WGS_1984_EGM2008_2.5x2.5_Height"// compositeHV[1].IsForward = true});
MapPoint GeoCoordinateString
MapPoint - GeoCoordinateString Conversion
SpatialReferencesr=SpatialReferences.WGS84;SpatialReferencesr2=SpatialReferences.WebMercator;// create some pointsMapPointpoint0=MapPointBuilderEx.CreateMapPoint(0,0,sr);MapPointpoint1=MapPointBuilderEx.CreateMapPoint(10,20,sr);MapPointpoint2=GeometryEngine.Instance.Project(point1,sr2)asMapPoint;MapPointpointEmpty=MapPointBuilderEx.CreateMapPoint(sr);MapPointpointwithNoSR=MapPointBuilderEx.CreateMapPoint(1,1);MapPointpointZM=MapPointBuilderEx.CreateMapPoint(1,2,3,4,sr);// convert to MGRSToGeoCoordinateParametermgrsParam=newToGeoCoordinateParameter(GeoCoordinateType.MGRS);// 31NAA6602100000stringgeoCoordString=point0.ToGeoCoordinateString(mgrsParam);// use the builder to create a new point from the string.// Coordinates are the same // outPoint.x = 0; outPoint.Y = 0MapPointoutPoint=MapPointBuilderEx.FromGeoCoordinateString(geoCoordString,sr,GeoCoordinateType.MGRS);// 32QPH0460911794// outPoint.X = 10; outPoint.Y = 20geoCoordString=point1.ToGeoCoordinateString(mgrsParam);outPoint=MapPointBuilderEx.FromGeoCoordinateString(geoCoordString,sr,GeoCoordinateType.MGRS);// z, m are not transformed// outPoint.X = 1; outPoint.Y = 2; outPoint.Z = Nan; outPoint.M = Nan;geoCoordString=pointZM.ToGeoCoordinateString(mgrsParam);outPoint=MapPointBuilderEx.FromGeoCoordinateString(geoCoordString,sr,GeoCoordinateType.MGRS);// set the number of digits to 2 and convert// 32QPH0512// outPoint.X = 10; outPoint.Y = 20mgrsParam.NumDigits=2;geoCoordString=point1.ToGeoCoordinateString(mgrsParam);outPoint=MapPointBuilderEx.FromGeoCoordinateString(geoCoordString,sr,GeoCoordinateType.MGRS);// convert to UTMToGeoCoordinateParameterutmParam=newToGeoCoordinateParameter(GeoCoordinateType.UTM);// 31N 166021 0000000geoCoordString=point0.ToGeoCoordinateString(utmParam);// 32Q 604609 2211793geoCoordString=point1.ToGeoCoordinateString(utmParam);// convert to DMSToGeoCoordinateParameterdmsParam=newToGeoCoordinateParameter(GeoCoordinateType.DMS);// 00 00 00.00N 000 00 00.00EgeoCoordString=point0.ToGeoCoordinateString(dmsParam);// 20 00 00.00N 010 00 00.00EgeoCoordString=point1.ToGeoCoordinateString(dmsParam);// convert to DDMToGeoCoordinateParameterddmParam=newToGeoCoordinateParameter(GeoCoordinateType.DDM);// 00 00.0000N 000 00.0000EgeoCoordString=point0.ToGeoCoordinateString(ddmParam);// 20 00.0000N 010 00.0000EgeoCoordString=point1.ToGeoCoordinateString(ddmParam);// convert to DDToGeoCoordinateParameterddParam=newToGeoCoordinateParameter(GeoCoordinateType.DD);// 00.000000N 000.000000EgeoCoordString=point0.ToGeoCoordinateString(ddParam);// 20.000000N 010.000000EgeoCoordString=point1.ToGeoCoordinateString(ddParam);
AngularUnit
AngularUnit - Convert between degrees and radians
// convert 45 degrees to radiansdoubleradians=AngularUnit.Degrees.ConvertToRadians(45);// convert PI to degreesdoubledegrees=AngularUnit.Degrees.ConvertFromRadians(Math.PI);
AngularUnit - Create an AngularUnit with a factory code
try{// create a Grad unitvargrad=AngularUnit.CreateAngularUnit(9105);stringunitName=grad.Name;// GraddoubleconversionFactor=grad.ConversionFactor;// 0.015708doubleradiansPerUnit=grad.RadiansPerUnit;intfactoryCode=grad.FactoryCode;// 9105// convert 10 grads to degreesdoubleval=grad.ConvertTo(10,AngularUnit.Degrees);// convert 10 radians to gradsval=grad.ConvertFromRadians(10);}catch(ArgumentException){// ArgumentException will be thrown by CreateAngularUnit in// the following scenarios:// - if the factory code used is a non-angular factory code// (i.e. it corresponds to square meters which is an area unit code)// - if the factory code used is invalid// (i.e. it is negative or doesn't correspond to any factory code)}
AngularUnit - Create a Custom AngularUnit
// custom unit - 3 radians per unitvarmyAngularUnit=AngularUnit.CreateAngularUnit("myCustomAngularUnit",3);stringName=myAngularUnit.Name;// myCustomAngularUnitdoubleFactor=myAngularUnit.ConversionFactor;// 3intCode=myAngularUnit.FactoryCode;// 0 because it is a custom angular unitdoubleradiansUnit=myAngularUnit.RadiansPerUnit;// 3// convert 10 degrees to my unitdoubleconverted=AngularUnit.Degrees.ConvertTo(10,myAngularUnit);// convert it back to degreesconverted=myAngularUnit.ConvertTo(converted,AngularUnit.Degrees);// convert 1 radian into my angular unitsconverted=myAngularUnit.ConvertFromRadians(1);// get the wktstringwkt=myAngularUnit.Wkt;// create an angular unit from this wktvaranotherAngularUnit=AngularUnit.CreateAngularUnit(wkt);// anotherAngularUnit.ConversionFactor = 3// anotherAngularUnit.FactoryCode = 0 // anotherAngularUnit.RadiansPerUnit = 3
LinearUnit
LinearUnit - Convert between feet and meters
// convert 10 feet to metersdoublemetres=LinearUnit.Feet.ConvertToMeters(10);// convert 20 meters to feetdoublefeet=LinearUnit.Feet.ConvertFromMeters(20.0);
LinearUnit - Convert between centimeters and millimeters
// convert 11 centimeters to millimetersdoublemm=LinearUnit.Centimeters.ConvertTo(11,LinearUnit.Millimeters);// convert the result back to centimetersdoublecm=LinearUnit.Millimeters.ConvertTo(mm,LinearUnit.Centimeters);// convert the millimeter result back to metersdoublemeters=LinearUnit.Millimeters.ConvertToMeters(mm);
LinearUnit - Create a LinearUnit with a factory code
try{// create a british 1936 footvarbritFoot=LinearUnit.CreateLinearUnit(9095);stringunitName=britFoot.Name;// "Foot_British_1936"doubleconversionFactor=britFoot.ConversionFactor;// 0.3048007491doublemetersPerUnit=britFoot.MetersPerUnit;intfactoryCode=britFoot.FactoryCode;// 9095// convert 10 british 1936 feet to centimetersdoubleval=britFoot.ConvertTo(10,LinearUnit.Centimeters);// convert 10 m to british 1936 feetval=britFoot.ConvertFromMeters(10);}catch(ArgumentException){// ArgumentException will be thrown by CreateLinearUnit// in the following scenarios:// - if the factory code used is a non-linear factory code// (i.e. it corresponds to square meters which is an area unit code)// - if the factory code used is invalid// (i.e. it is negative or doesn't correspond to any factory code)}
LinearUnit - Create a Custom LinearUnit
// create a custom linear unit - there are 0.33 meters per myLinearUnitvarmyLinearUnit=LinearUnit.CreateLinearUnit("myCustomLinearUnit",0.33);stringname=myLinearUnit.Name;// myCustomLinearUnitdoubleconvFactor=myLinearUnit.ConversionFactor;// 0.33intcode=myLinearUnit.FactoryCode;// 0 for custom unitsdoublemetersUnit=myLinearUnit.MetersPerUnit;// 0.33stringtoString=myLinearUnit.ToString();// same as Name - myCustomLinearUnit// convert 10 centimeters to myLinearUnit doubleconvertedVal=LinearUnit.Centimeters.ConvertTo(10,myLinearUnit);// get the wktstringlu_wkt=myLinearUnit.Wkt;// create an angular unit from this wktvaranotherLinearUnit=LinearUnit.CreateLinearUnit(lu_wkt);// anotherLinearUnit.ConversionFactor = 0.33// anotherLinearUnit.FactoryCode = 0 // anotherLinearUnit.MetersPerUnit = 0.33
AreaUnit
AreaUnit - Convert between square feet and square meters
// convert 700 square meters to square feetdoublesqFeet=AreaUnit.SquareFeet.ConvertFromSquareMeters(700);// convert 1100 square feet to square metersdoublesqMeters=AreaUnit.SquareFeet.ConvertToSquareMeters(1000);
AreaUnit - Convert between hectares and acres
// convert 2 hectares to acresdoubleacres=AreaUnit.Hectares.ConvertTo(2,AreaUnit.Acres);
AreaUnit - Convert between hectares and square miles
// convert 300 hectares to square milesdoublesqMiles=AreaUnit.Hectares.ConvertTo(300,AreaUnit.SquareMiles);
AreaUnit - How many Square meters in various units
try{varmyFactoryCodeInit=AreaUnit.CreateAreaUnit(109439);// 109439 is the factory code for square milesvarmyWktUnit=AreaUnit.CreateAreaUnit("HECTARE_AREAUNIT[\"H\",10000.0]");varmyCustomUnit=AreaUnit.CreateAreaUnit("myAreaUnit",12);}catch(ArgumentException){// ArgumentException will be thrown by CreateAreaUnit in the following scenarios// - if the factory code used is a non-areal factory code (i.e. it corresponds to degrees which is an angular unit code)// - if the factory code used is invalid (i.e. it is negative or doesn't correspond to any factory code)}