public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate c1 = gf.CreateCoordinateXY(1.0, 1.0); MgCoordinate c2 = gf.CreateCoordinateXY(2.0, 2.0); MgCoordinate c3 = gf.CreateCoordinateXY(3.0, 3.0); MgCoordinate c4 = gf.CreateCoordinateXY(4.0, 4.0); MgCoordinateCollection coll = new MgCoordinateCollection(); coll.Add(c1); coll.Insert(1, c2); coll.Add(c3); coll.Add(c4); Assert.AreEqual(4, coll.Count); Assert.AreEqual(1.0, coll[0].GetX()); coll[3] = coll[2]; Assert.AreEqual(3.0, coll[3].GetX()); double sum = 0.0; foreach (MgCoordinate coord in coll) { sum += coord.GetX(); } Assert.AreEqual(9.0, sum); }
public MgPolygon parseString(string coordinates) { MgPolygon polygon = null; //Please type in the code between the comments MgGeometryFactory geoFactory = new MgGeometryFactory(); MgCoordinateCollection coordCol = new MgCoordinateCollection(); string[] num_coords = coordinates.Split('~'); int num = Convert.ToInt16(num_coords[0]); string[] coords = num_coords[1].Split('_'); for (int i = 0; i < num; i++) { string[] xyString = coords[i].Split('!'); double x = Convert.ToDouble(xyString[0]); double y = Convert.ToDouble(xyString[1]); MgCoordinate coord = geoFactory.CreateCoordinateXY(x, y); coordCol.Add(coord); } MgLinearRing outRing = geoFactory.CreateLinearRing(coordCol); polygon = geoFactory.CreatePolygon(outRing, null); /////////////////////////////////////// return polygon; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ��Mapguide���ص�����ת��ΪKML // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public String createMuniMarker() { StringBuilder outString = new StringBuilder(); MgGeometryFactory geoFactory = new MgGeometryFactory(); outString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgResourceIdentifier resId = new MgResourceIdentifier("Library://MgTutorial/Data/WheatonMunicipalities.FeatureSource"); MgFeatureReader featureReader = featureService.SelectFeatures(resId, "WheatonMunicipalities", null); outString.Append("<markers>"); MgAgfReaderWriter geoReader = new MgAgfReaderWriter(); while (featureReader.ReadNext()) { String muniName = featureReader.GetString("MUNINAME"); MgByteReader byteReader = featureReader.GetGeometry("Geometry"); MgGeometry geo = geoReader.Read(byteReader); MgPoint pt = geo.GetCentroid(); double x = pt.GetCoordinate().GetX(); double y = pt.GetCoordinate().GetY(); outString.Append("<marker lat=\"" + y + "\" lng=\"" + x + "\" info=\"" + muniName + "\" />"); } featureReader.Close(); outString.Append("</markers>"); return outString.ToString(); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearSegment linearSegment = gf.CreateLinearSegment(coordinates); MgCurveSegmentCollection curveSegments = new MgCurveSegmentCollection(); curveSegments.Add(linearSegment); MgCurveRing outerRing = gf.CreateCurveRing(curveSegments); MgCurvePolygon cp = gf.CreateCurvePolygon(outerRing, null); Assert.AreEqual(outerRing.ToString(), cp.ExteriorRing.ToString()); Assert.AreEqual(0, cp.InteriorRingCount); Assert.AreEqual(MgGeometryType.CurvePolygon, cp.GeometryType); Assert.AreEqual(2, cp.Dimension); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearSegment linearSegment = gf.CreateLinearSegment(coordinates); MgCurveSegmentCollection curveSegments = new MgCurveSegmentCollection(); curveSegments.Add(linearSegment); MgCurveString curveString = gf.CreateCurveString(curveSegments); Assert.AreEqual(1, curveString.Count); Assert.AreEqual(pt1.ToString(), curveString.StartCoordinate.ToString()); Assert.AreEqual(pt4.ToString(), curveString.EndCoordinate.ToString()); Assert.AreEqual(MgGeometryType.CurveString, curveString.GeometryType); Assert.AreEqual(1, curveString.Dimension); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearSegment linearSegment = gf.CreateLinearSegment(coordinates); MgCurveSegmentCollection curveSegments = new MgCurveSegmentCollection(); curveSegments.Add(linearSegment); MgCurveString curveString = gf.CreateCurveString(curveSegments); MgCurveStringCollection csc = new MgCurveStringCollection(); csc.Add(curveString); MgMultiCurveString mcs = gf.CreateMultiCurveString(csc); Assert.AreEqual(1, mcs.Count); Assert.AreEqual(MgGeometryType.MultiCurveString, mcs.GeometryType); Assert.AreEqual(1, mcs.Dimension); }
/// <summary> /// Coordinate transformation between two world coordinate systems /// This Version works with coordinates as X, Y doubles /// </summary> /// <param name="wkTextSource">The wk text source.</param> /// <param name="wkTextTarget">The wk text target.</param> /// <param name="inputPointX">The input point X.</param> /// <param name="inputPointY">The input point Y.</param> /// <param name="transformedPointX">The transformed point X.</param> /// <param name="transformedPointY">The transformed point Y.</param> /// <returns></returns> public static bool TransformPoint2d(string wkTextSource, string wkTextTarget, double inputPointX, double inputPointY, ref double transformedPointX, ref double transformedPointY) { bool RetVal = false; //_logger.Debug("Start TransformPoint2d"); try { //Creating coordinate system factory MgCoordinateSystemFactory CSFactory = new MgCoordinateSystemFactory(); //Creating coordinate system objects MgCoordinateSystem SourceCS = CSFactory.Create(wkTextSource); MgCoordinateSystem TargetCS = CSFactory.Create(wkTextTarget); //Creating geometry factory MgGeometryFactory GeomFactory = new MgGeometryFactory(); //Populating geometry factory CreateCoordinateXY MgCoordinate SourceCoord = GeomFactory.CreateCoordinateXY(inputPointX, inputPointY); //Getting transformation definition MgCoordinateSystemTransform CSTransform = CSFactory.GetTransform(SourceCS, TargetCS); //Transforming coordinate MgCoordinate TargetCoord = CSTransform.Transform(SourceCoord); //Populating return coordinate objects transformedPointX = TargetCoord.X; transformedPointY = TargetCoord.Y; RetVal = true; } catch (System.Exception ex) { //_logger.Error("Error in TransformPoint2d", ex); throw; } //_logger.Debug("End TransformPoint2d"); return(RetVal); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearSegment linearSegment = gf.CreateLinearSegment(coordinates); MgCurveSegmentCollection curveSegments = new MgCurveSegmentCollection(); MgCurveRing curveRing = gf.CreateCurveRing(curveSegments); MgCurvePolygon cp = gf.CreateCurvePolygon(curveRing, null); MgCurvePolygonCollection cpc = new MgCurvePolygonCollection(); cpc.Add(cp); MgMultiCurvePolygon mcp = gf.CreateMultiCurvePolygon(cpc); Assert.AreEqual(1, mcp.Count); Assert.AreEqual(MgGeometryType.MultiCurvePolygon, mcp.GeometryType); Assert.AreEqual(2, mcp.Dimension); }
private void oneshotCallbackToolStripMenuItem_Click(object sender, EventArgs e) { MgGeometryFactory geomFact = new MgGeometryFactory(); mapViewer.DigitizePoint((x, y) => { MgCoordinate coord = geomFact.CreateCoordinateXY(x, y); MgPoint pt = geomFact.CreatePoint(coord); mapViewer.SelectByGeometry(pt, -1, (selection) => { if (selection == null) { MessageBox.Show("No selected features"); return; } else { MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null) { StringBuilder sb = new StringBuilder("Selection summary:"); for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase lyr = layers.GetItem(i); sb.Append(Environment.NewLine + lyr.GetName() + ": " + selection.GetSelectedFeaturesCount(lyr, lyr.GetFeatureClassName())); } MessageBox.Show(sb.ToString()); } else { MessageBox.Show("No selected features"); } } }); }); }
void OnDisposed(object sender, EventArgs e) { if (_geomFact != null) { _geomFact.Dispose(); _geomFact = null; } }
void OnDisposed(object sender, EventArgs e) { _properties.Clear(); _layers.Clear(); _wktRw.Dispose(); _wktRw = null; _geomFact.Dispose(); _geomFact = null; }
public RedlineEditor(IMapViewer viewer, RedlineLayer layer) { _viewer = viewer; _layer = layer; var provider = viewer.GetProvider(); _featSvc = (MgFeatureService)provider.CreateService(MgServiceType.FeatureService); _wktRW = new MgWktReaderWriter(); _agfRW = new MgAgfReaderWriter(); _geomFact = new MgGeometryFactory(); }
string pointTransformAndWriteZ(string geom, MgMap map) { double[] x = new double[1]; double[] y = new double[1]; double[] z = new double[1]; MgWktReaderWriter wktrwdmr = new MgWktReaderWriter(); MgPoint cntr = wktrwdmr.Read(geom).Centroid; x[0] = cntr.Coordinate.X; y[0] = cntr.Coordinate.Y; z[0] = 0; StringBuilder output = new StringBuilder(); output.Append("<table width=\"100%\" class=\"results\">"); //WGS preko MG API MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktFrom = map.GetMapSRS(); string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem CSSource = fact.Create(wktFrom); MgCoordinateSystem CSTarget = fact.Create(wktTo); MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget); MgGeometryFactory geomFact = new MgGeometryFactory(); // GK //samo prvo višino zaenkrat, dokler ni enačbe za Z output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0]))); int i = 0; //transformacija preko MG koordinatnega sistema foreach (double pointX in x) { MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]); coord = coordTransform.Transform(coord); x[i] = coord.X; y[i] = coord.Y; i++; } double[] xwgs = x; double[] ywgs = y; output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0]))); output.Append("</table>"); return(output.ToString()); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinateXY coord = gf.CreateCoordinateXY(100, 100) as MgCoordinateXY; Assert.AreEqual(100, coord.X); Assert.AreEqual(100, coord.Y); MgCoordinate coord2 = coord; Assert.AreEqual(100, coord2.X); Assert.AreEqual(100, coord2.Y); }
public void ArcSegment() { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinateXY start = gf.CreateCoordinateXY(0, 0) as MgCoordinateXY; MgCoordinateXY end = gf.CreateCoordinateXY(10, 10) as MgCoordinateXY; MgCoordinateXY control = gf.CreateCoordinateXY(5, 5) as MgCoordinateXY; MgArcSegment arcSegment = gf.CreateArcSegment(start, end, control); Assert.AreEqual(MgGeometryComponentType.ArcSegment, arcSegment.ComponentType); Assert.AreEqual(control.ToString(), arcSegment.ControlCoordinate.ToString()); Assert.AreEqual(start.ToString(), arcSegment.StartCoordinate.ToString()); Assert.AreEqual(end.ToString(), arcSegment.EndCoordinate.ToString()); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinateXY start = gf.CreateCoordinateXY(0, 0) as MgCoordinateXY; MgCoordinateXY end = gf.CreateCoordinateXY(10, 10) as MgCoordinateXY; MgCoordinateXY control = gf.CreateCoordinateXY(5, 5) as MgCoordinateXY; MgArcSegment arcSegment = gf.CreateArcSegment(start, end, control); Assert.AreEqual(MgGeometryComponentType.ArcSegment, arcSegment.ComponentType); Assert.AreEqual(control.ToString(), arcSegment.ControlCoordinate.ToString()); Assert.AreEqual(start.ToString(), arcSegment.StartCoordinate.ToString()); Assert.AreEqual(end.ToString(), arcSegment.EndCoordinate.ToString()); }
private void InitBase(IMapViewer viewer) { this.Title = Strings.TitleQuery; this.Disposed += new EventHandler(OnDisposed); _viewer = viewer; _properties = new BindingList <MgDataPropertyDefinition>(); _layers = new BindingList <MgLayerBase>(); _wktRw = new MgWktReaderWriter(); _geomFact = new MgGeometryFactory(); cmbOperator.DataSource = Enum.GetValues(typeof(QueryOperator)); cmbLayer.DataSource = _layers; cmbProperty.DataSource = _properties; cmbOperator.SelectedIndex = 0; }
private void InitBase(IMapViewer viewer) { this.Title = Strings.TitleQuery; this.Disposed += new EventHandler(OnDisposed); _viewer = viewer; _properties = new BindingList<MgDataPropertyDefinition>(); _layers = new BindingList<MgLayerBase>(); _wktRw = new MgWktReaderWriter(); _geomFact = new MgGeometryFactory(); cmbOperator.DataSource = Enum.GetValues(typeof(QueryOperator)); cmbLayer.DataSource = _layers; cmbProperty.DataSource = _properties; cmbOperator.SelectedIndex = 0; }
public DigitizingAndRedlining(IMapViewer viewer) { InitializeComponent(); _viewer = viewer; _geomFact = new MgGeometryFactory(); _wktRW = new MgWktReaderWriter(); _agfRW = new MgAgfReaderWriter(); this.Title = "Digitizing and Redlining"; _viewer.PropertyChanged += OnViewerPropertyChanged; MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); if (layers.IndexOf("Redline") >= 0) { _redlineLayer = (MgdLayer)layers.GetItem("Redline"); } CheckDigitizingState(); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearRing linearRing = gf.CreateLinearRing(coordinates); Assert.AreEqual(MgGeometryComponentType.LinearRing, linearRing.ComponentType); Assert.AreEqual(2, linearRing.Dimension); }
protected override void OnLoad(EventArgs e) { _wktRw = new MgWktReaderWriter(); _geomFact = new MgGeometryFactory(); new MapViewerController(mgMapViewer1, //The MgMapViewer mgLegend1, //The MgLegend this, //The IMapStatusBar mgPropertyPane1); //The MgPropertyPane MgdServiceFactory factory = new MgdServiceFactory(); MgdResourceService resSvc = (MgdResourceService)factory.CreateService(MgServiceType.ResourceService); MgResourceIdentifier mapDefId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition"); //If this map definition doesn't exist, we ask the user to //load the Sheboygan package if (!resSvc.ResourceExists(mapDefId)) { using (OpenFileDialog diag = new OpenFileDialog()) { diag.Filter = "MapGuide Packages (*.mgp)|*.mgp"; if (diag.ShowDialog() == DialogResult.OK) { MgByteSource source = new MgByteSource(diag.FileName); MgByteReader reader = source.GetReader(); resSvc.ApplyResourcePackage(reader); } else { //No map, nothing to do here Application.Exit(); } } } //Create our runtime map MgdMap map = new MgdMap(mapDefId); //Create our viewer provider MgMapViewerProvider provider = new MgDesktopMapViewerProvider(map); //Initialize our viewer with this provider mgMapViewer1.Init(provider); UpdateButtonCheckedState(); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearSegment linearSegment = gf.CreateLinearSegment(coordinates); Assert.AreEqual(MgGeometryComponentType.LinearSegment, linearSegment.ComponentType); Assert.AreEqual(pt1.ToString(), linearSegment.StartCoordinate.ToString()); Assert.AreEqual(pt4.ToString(), linearSegment.EndCoordinate.ToString()); Assert.AreEqual(1, linearSegment.Dimension); }
//---------------------------------------------------------------------------------------- // �� �ܣ� ��ѯָ����Χ�ڵ�Ҫ�� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public ParcelProperty[] GetNearParcels(string parcelType, GeocodeAddress geocodeAddress, double bufferDistance) { ParcelProperty[] parcelProperties = null; //���ڵ�ַ���� ���ε�͵�Ļ������������Σ� MgGeometryFactory geoFactory = new MgGeometryFactory(); MgCoordinate coord = geoFactory.CreateCoordinateXY(Convert.ToDouble(geocodeAddress.lon), Convert.ToDouble(geocodeAddress.lat)); MgPoint pt = geoFactory.CreatePoint(coord); //��ѯ��ָ����Χ�ڣ�����Σ���Ҫ�� MgPolygon buffer = (MgPolygon)pt.Buffer(bufferDistance, null); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter("RTYPE LIKE '" + parcelType + "%'"); query.SetSpatialFilter("SHPGEOM", buffer, MgFeatureSpatialOperations.Inside); MgResourceIdentifier resId = new MgResourceIdentifier("Library://Samples/Sheboygan/Data/Parcels.FeatureSource"); MgFeatureReader featReader = featureService.SelectFeatures(resId, "Parcels", query); //�����ѯ��� ArrayList props = new ArrayList(); while (featReader.ReadNext()) { ParcelProperty prop = new ParcelProperty(); prop.ID = featReader.GetInt32("Autogenerated_SDF_ID").ToString(); prop.Acreage = featReader.GetString("RACRE"); prop.BillingAddr = featReader.GetString("RBILAD"); prop.Description1 = featReader.GetString("RLDESCR1"); prop.Description2 = featReader.GetString("RLDESCR2"); prop.Description3 = featReader.GetString("RLDESCR3"); prop.Description4 = featReader.GetString("RLDESCR4"); prop.LotDimension = featReader.GetString("RLOT"); prop.LotSize = featReader.GetInt32("RSQFT"); prop.Owner = featReader.GetString("RNAME"); prop.Zoning = featReader.GetString("RTYPE"); props.Add(prop); } parcelProperties = (ParcelProperty[])props.ToArray(typeof(ParcelProperty)); return parcelProperties; }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearRing linearRing = gf.CreateLinearRing(coordinates); MgPolygon polygon = gf.CreatePolygon(linearRing, null); Assert.AreEqual(linearRing.ToString(), polygon.ExteriorRing.ToString()); Assert.AreEqual(0, polygon.InteriorRingCount); Assert.AreEqual(MgGeometryType.Polygon, polygon.GeometryType); Assert.AreEqual(2, polygon.Dimension); }
public static string TransformGK2Wgs(double x, double y, string ss, string mpN) { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); //Create coordinate system factory MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktFrom = map.GetMapSRS(); string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem coordinateSystemSource = fact.Create(wktFrom); MgCoordinateSystem coordinateSystemTarget = fact.Create(wktTo); MgGeometryFactory geomFact = new MgGeometryFactory(); MgCoordinateSystemTransform coordTransform = fact.GetTransform(coordinateSystemSource, coordinateSystemTarget); MgCoordinate coord = coordTransform.Transform(x, y); return coord.X.ToString().Replace(',', '.') + ";" + coord.Y.ToString().Replace(',', '.'); }
public override void Invoke() { var viewer = this.Viewer; viewer.DigitizePolygon((coordinates) => { if (_geomFact == null) { _geomFact = new MgGeometryFactory(); } MgCoordinateCollection coords = new MgCoordinateCollection(); for (int i = 0; i < coordinates.GetLength(0); i++) { coords.Add(_geomFact.CreateCoordinateXY(coordinates[i, 0], coordinates[i, 1])); } coords.Add(_geomFact.CreateCoordinateXY(coordinates[0, 0], coordinates[0, 1])); MgLinearRing ring = _geomFact.CreateLinearRing(coords); MgGeometry poly = _geomFact.CreatePolygon(ring, null); viewer.SelectByGeometry(poly); }); }
public static string TransformGK2Wgs(double x, double y, string ss, string mpN) //Transform from Map to WGS 84 Coordtnate System { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); //Create coordinate system factory MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktFrom = map.GetMapSRS(); string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem coordinateSystemSource = fact.Create(wktFrom); MgCoordinateSystem coordinateSystemTarget = fact.Create(wktTo); MgGeometryFactory geomFact = new MgGeometryFactory(); MgCoordinateSystemTransform coordTransform = fact.GetTransform(coordinateSystemSource, coordinateSystemTarget); MgCoordinate coord = coordTransform.Transform(x, y); return(coord.X.ToString().Replace(',', '.') + ";" + coord.Y.ToString().Replace(',', '.')); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgPoint mgpt1 = gf.CreatePoint(pt1); MgPoint mgpt2 = gf.CreatePoint(pt2); MgPoint mgpt3 = gf.CreatePoint(pt3); MgPoint mgpt4 = gf.CreatePoint(pt4); MgPointCollection points = new MgPointCollection(); points.Add(mgpt1); points.Add(mgpt2); points.Add(mgpt3); points.Add(mgpt4); MgMultiPoint mp = gf.CreateMultiPoint(points); Assert.AreEqual(4, mp.Count); Assert.AreEqual(MgGeometryType.MultiPoint, mp.GeometryType); Assert.AreEqual(0, mp.Dimension); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearSegment linearSegment = gf.CreateLinearSegment(coordinates); MgCurveSegmentCollection curveSegments = new MgCurveSegmentCollection(); curveSegments.Add(linearSegment); MgCurveRing outerRing = gf.CreateCurveRing(curveSegments); Assert.AreEqual(MgGeometryComponentType.CurveRing, outerRing.ComponentType); Assert.AreEqual(1, outerRing.Count); Assert.AreEqual(2, outerRing.Dimension); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLineString ls = gf.CreateLineString(coordinates); MgLineStringCollection lineStringCollection = new MgLineStringCollection(); lineStringCollection.Add(ls); MgMultiLineString mls = gf.CreateMultiLineString(lineStringCollection); Assert.AreEqual(1, mls.Count); Assert.AreEqual(MgGeometryType.MultiLineString, mls.GeometryType); Assert.AreEqual(1, mls.Dimension); }
private void btnCreate_Click(object sender, EventArgs e) { btnCreate.Enabled = false; try { var layerName = txtBufferLayer.Text.Trim(); if (string.IsNullOrEmpty(layerName)) { MessageBox.Show(Strings.MsgEnterNameForLayer); return; } if (lstLayers.SelectedItems.Count == 0) { MessageBox.Show(Strings.MsgIncludeLayersToBuffer); return; } var map = _viewer.GetMap(); var layers = map.GetLayers(); var provider = _viewer.GetProvider(); //From here, it's the same logic as buffer.aspx in .net MapGuide AJAX viewer MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.FeatureSource"); //NOXLATE MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.LayerDefinition"); //NOXLATE MgLayerBase layer = Util.FindLayer(layers, txtBufferLayer.Text); string[] layerNames = GetLayerNames(); double distance = Convert.ToDouble(numBufferDistance.Value); MeasurementUnit bUnits = (MeasurementUnit)cmbUnits.SelectedItem; switch (bUnits) { case MeasurementUnit.Feet: distance *= 0.30480; break; case MeasurementUnit.Kilometers: distance *= 1000; break; case MeasurementUnit.Miles: distance *= 1609.35; break; } String srsDefMap = Util.GetMapSrs(map); MgCoordinateSystem srsMap = provider.GetMapCoordinateSystem(); string mapSrsUnits = ""; bool arbitraryMapSrs = (srsMap.GetType() == MgCoordinateSystemType.Arbitrary); if (arbitraryMapSrs) mapSrsUnits = srsMap.GetUnits(); String xtrans = String.Format("{0:x2}", ((int)(255 * Convert.ToInt32(numFillTransparency.Value) / 100))); //NOXLATE var lineColor = Util.ToHtmlColor(pnlBorderColor.BackColor); var foreColor = Util.ToHtmlColor(pnlFillColor.BackColor); var backColor = Util.ToHtmlColor(pnlFillBackColor.BackColor); String layerTempl = string.Format(Properties.Resources.AreaLayerDef, fsId.ToString(), "BufferSchema:Buffer", //NOXLATE "GEOM", //NOXLATE cmbFillPattern.SelectedItem, xtrans + foreColor, ((0 != 1/*transparent*/) ? "ff" : "00") + backColor, //NOXLATE cmbBorderPattern.SelectedItem, numLineThickness.Value.ToString(NumberFormatInfo.InvariantInfo), lineColor ); byte[] bytes = Encoding.UTF8.GetBytes(layerTempl); MgByteSource src = new MgByteSource(bytes, bytes.Length); MgByteReader layerDefContent = src.GetReader(); _resSvc.SetResource(ldfId, layerDefContent, null); bool newBuffer = false; if (layer == null) { newBuffer = true; //Targetting a new layer. create a data source for it // MgClassDefinition classDef = new MgClassDefinition(); classDef.SetName("Buffer"); //NOXLATE classDef.SetDescription("Feature class for buffer layer"); //NOXLATE classDef.SetDefaultGeometryPropertyName("GEOM"); //NOXLATE //Set KEY property MgDataPropertyDefinition prop = new MgDataPropertyDefinition("KEY"); //NOXLATE prop.SetDataType(MgPropertyType.Int32); prop.SetAutoGeneration(true); prop.SetReadOnly(true); classDef.GetIdentityProperties().Add(prop); classDef.GetProperties().Add(prop); //Set ID property. Hold this segment ID prop = new MgDataPropertyDefinition("ID"); //NOXLATE prop.SetDataType(MgPropertyType.Int32); classDef.GetProperties().Add(prop); //Set geometry property MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM"); //NOXLATE //prop.SetGeometryTypes(MgFeatureGeometricType.mfgtSurface); //TODO use the constant when exposed geomProp.SetGeometryTypes(4); classDef.GetProperties().Add(geomProp); //Create the schema MgFeatureSchema schema = new MgFeatureSchema("BufferSchema", "Temporary buffer schema"); //NOXLATE schema.GetClasses().Add(classDef); //finally, creation of the feature source MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", map.GetMapSRS(), schema); //NOXLATE _featSvc.CreateFeatureSource(fsId, sdfParams); //Add layer to map layer = provider.CreateLayer(ldfId); layer.SetName(txtBufferLayer.Text); layer.SetLegendLabel(txtBufferLayer.Text); layer.SetDisplayInLegend(true); layer.SetSelectable(true); layers.Insert(0, layer); } else { //data source already exist. clear its content // Util.ClearDataSource(_featSvc, fsId, "BufferSchema:Buffer"); //NOXLATE } var sel = _viewer.GetSelection(); var selLayers = sel.GetLayers(); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); MgGeometryCollection bufferGeometries = new MgGeometryCollection(); MgGeometry geomBuffer; MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); int featId = 0; MgBatchPropertyCollection propCollection = new MgBatchPropertyCollection(); int excludedLayers = 0; MgCoordinateSystem srsDs = null; MgGeometryCollection inputGeometries = new MgGeometryCollection(); int bufferFeatures = 0; for (int li = 0; li < selLayers.GetCount(); li++) { MgLayerBase selLayer = selLayers.GetItem(li); bool inputLayer = false; String selLayerName = selLayer.GetName(); for (int il = 0; il < layerNames.Length; il++) { if (layerNames[il].Equals(selLayerName)) { inputLayer = true; break; } } if (inputLayer == false) { continue; } // get the data source SRS // MgResourceIdentifier featSourceId = new MgResourceIdentifier(selLayer.GetFeatureSourceId()); MgSpatialContextReader ctxs = _featSvc.GetSpatialContexts(featSourceId, false); String srsDefDs = string.Empty; if (ctxs != null && ctxs.ReadNext()) srsDefDs = ctxs.GetCoordinateSystemWkt(); if (srsDefDs == null || srsDefDs.Length == 0) { excludedLayers++; continue; } var srsFactory = new MgCoordinateSystemFactory(); srsDs = srsFactory.Create(srsDefDs); bool arbitraryDsSrs = (srsDs.GetType() == MgCoordinateSystemType.Arbitrary); String dsSrsUnits = string.Empty; if (arbitraryDsSrs) dsSrsUnits = srsDs.GetUnits(); // exclude layer if: // the map is non-arbitrary and the layer is arbitrary or vice-versa // or // layer and map are both arbitrary but have different units // if ((arbitraryDsSrs != arbitraryMapSrs) || (arbitraryDsSrs && (dsSrsUnits != mapSrsUnits))) { excludedLayers++; continue; } // calculate distance in the data source SRS units // double dist = srsDs.ConvertMetersToCoordinateSystemUnits(distance); // calculate great circle unless data source srs is arbitrary MgCoordinateSystemMeasure measure; if (!arbitraryDsSrs) measure = srsDs.GetMeasure(); else measure = null; // create a SRS transformer if necessary MgCoordinateSystemTransform srsXform; if (!srsDefDs.Equals(srsDefMap)) srsXform = srsFactory.GetTransform(srsDs, srsMap); else srsXform = null; String featureClassName = selLayer.GetFeatureClassName(); String filter = sel.GenerateFilter(selLayer, featureClassName); if (filter == null || filter.Length == 0) continue; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(filter); MgResourceIdentifier featureSource = new MgResourceIdentifier(selLayer.GetFeatureSourceId()); MgFeatureReader features = _featSvc.SelectFeatures(featureSource, featureClassName, query); if (features.ReadNext()) { MgClassDefinition classDef = features.GetClassDefinition(); String geomPropName = classDef.GetDefaultGeometryPropertyName(); do { MgByteReader geomReader = features.GetGeometry(geomPropName); MgGeometry geom = agfRW.Read(geomReader); if (!chkMergeBuffers.Checked) { geomBuffer = geom.Buffer(dist, measure); if (geomBuffer != null) { if (srsXform != null) geomBuffer = (MgGeometry)geomBuffer.Transform(srsXform); Util.AddFeatureToCollection(propCollection, agfRW, featId++, geomBuffer); bufferFeatures++; } } else { if (srsXform != null) geom = (MgGeometry)geom.Transform(srsXform); inputGeometries.Add(geom); } } while (features.ReadNext()); features.Close(); } } if (chkMergeBuffers.Checked) { if (inputGeometries.GetCount() > 0) { double dist = srsMap.ConvertMetersToCoordinateSystemUnits(distance); MgCoordinateSystemMeasure measure; if (!arbitraryMapSrs) measure = srsMap.GetMeasure(); else measure = null; MgGeometryFactory geomFactory = new MgGeometryFactory(); geomBuffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(dist, measure); if (geomBuffer != null) { Util.AddFeatureToCollection(propCollection, agfRW, featId, geomBuffer); bufferFeatures = 1; } } } if (propCollection.GetCount() > 0) { commands.Add(new MgInsertFeatures("BufferSchema:Buffer", propCollection)); //NOXLATE //Insert the features in the temporary data source // Util.ReleaseReader(_featSvc.UpdateFeatures(fsId, commands, false), commands); } // Save the new map state // layer.ForceRefresh(); _viewer.RefreshMap(); //build report message if (newBuffer) MessageBox.Show(string.Format(Strings.MsgBufferLayerCreated, txtBufferLayer.Text)); else MessageBox.Show(string.Format(Strings.MsgBufferLayerUpdated, txtBufferLayer.Text)); } finally { btnCreate.Enabled = true; } }
private void btnCreateBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase layer = layers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 100; // measured in metres int bufferRingCount = 5; // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); string sessionId = Guid.NewGuid().ToString(); BufferHelper helper = new BufferHelper(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. MgdLayer bufferLayer = null; int layerIndex = mapLayers.IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); mapLayers.Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Get the selected features from the MgSelection object MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName()); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Add buffer features to the temporary feature source. // Create multiple concentric buffers to show area. // If the stylization for the layer draws the features // partially transparent, the concentric rings will be // progressively darker towards the center. // The stylization is set in the layer template file, which // is used in function CreateBufferLayer(). for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++) { double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1)); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); MgFeatureReader fr = bufferLayer.InsertFeatures(properties); fr.Close(); } bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); MessageBox.Show("Buffer created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } }
/// <summary> /// Initializes this viewer with the specified viewer provider, if the provider contains a map /// it will load that as well. Otherwise a call to <see cref="LoadMap"/> is required afterwards /// </summary> /// <param name="provider">The provider.</param> public void Init(MgMapViewerProvider provider) { if (_agfRW == null) _agfRW = new MgAgfReaderWriter(); if (_wktRW == null) _wktRW = new MgWktReaderWriter(); if (_geomFact == null) _geomFact = new MgGeometryFactory(); _provider = provider; if (_resSvc != null) //Forward looking, dispose the existing one as it may be of a different implementation { _resSvc.Dispose(); _resSvc = null; } _resSvc = (MgResourceService)_provider.CreateService(MgServiceType.ResourceService); _overlayRenderOpts = CreateMapRenderingOptions(0, 0, 255); _selectionRenderOpts = CreateSelectionRenderingOptions(0, 0, 255); if (_provider != null) { _provider.MapLoaded -= OnMapSetOnProvider; _provider = null; } _provider = provider; _provider.MapLoaded += OnMapSetOnProvider; var map = _provider.GetMap(); if (map != null) OnMapSetOnProvider(this, EventArgs.Empty); }
public override System.IO.Stream RenderRuntimeMap(RuntimeMap rtmap, double x1, double y1, double x2, double y2, int width, int height, int dpi, string format, bool clip) { var resourceId = rtmap.ResourceID; MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgGeometryFactory gf = new MgGeometryFactory(); string mapname = new ResourceIdentifier(resourceId).Path; //TODO: The render is missing the clip param for the extent override method GetByteReaderMethod fetch = () => { MgMap map = new MgMap(); map.Open(res, mapname); MgSelection sel = new MgSelection(map); //The color accepted by MgColor has alpha as the last value, but the returned has alpha first MgColor color = new MgColor(Utility.ParseHTMLColor(map.GetBackgroundColor())); MgEnvelope env = new MgEnvelope(gf.CreateCoordinateXY(x1, y1), gf.CreateCoordinateXY(x2, y2)); return rnd.RenderMap(map, sel, env, width, height, color, format); }; LogMethodCall("MgRenderingService::RenderMap", true, "MgMap", "MgSelection", "MgEnvelope", width.ToString(), height.ToString(), "MgColor", format); return new MgReadOnlyStream(fetch); }
/// <summary> /// Releases the unmanaged resources used by the <see cref="T:System.Windows.Forms.Control"/> and its child controls and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { base.MouseUp -= OnMapMouseUp; base.MouseMove -= OnMapMouseMove; base.MouseDown -= OnMapMouseDown; base.MouseClick -= OnMapMouseClick; base.MouseDoubleClick -= OnMapMouseDoubleClick; base.MouseHover -= OnMapMouseHover; base.MouseEnter -= OnMouseEnter; base.MouseLeave -= OnMapMouseLeave; if (renderWorker != null) { renderWorker.DoWork -= renderWorker_DoWork; renderWorker.RunWorkerCompleted -= renderWorker_RunWorkerCompleted; } if (_csFact != null) { _csFact.Dispose(); _csFact = null; } if (_resSvc != null) { _resSvc.Dispose(); _resSvc = null; } if (_selection != null) { _selection.Dispose(); _selection = null; } if (_mapCs != null) { _mapCs.Dispose(); _mapCs = null; } if (_agfRW != null) { _agfRW.Dispose(); _agfRW = null; } if (_wktRW != null) { _wktRW.Dispose(); _wktRW = null; } if (_geomFact != null) { _geomFact.Dispose(); _geomFact = null; } if (_mapMeasure != null) { _mapMeasure.Dispose(); _mapMeasure = null; } } base.Dispose(disposing); }
public void AddPolygon() { MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgAgfReaderWriter agfWriter = new MgAgfReaderWriter(); String[] vertices = GetParameter(this.args, "GEOMETRY").Split(new Char[] { ',' }); int count = (int)Double.Parse(vertices[0]); MgCoordinateCollection coords = new MgCoordinateCollection(); for (int i = 0; i < count; i++) { MgCoordinate coord = geometryFactory.CreateCoordinateXY(Double.Parse(vertices[(i * 2) + 1]), Double.Parse(vertices[(i * 2) + 2])); coords.Add(coord); } MgLinearRing linearRing = geometryFactory.CreateLinearRing(coords); MgPolygon polygon = geometryFactory.CreatePolygon(linearRing, null); polygon = (MgPolygon)polygon.Transform(this.GetTransform()); MgByteReader byteReader = agfWriter.Write(polygon); MgPropertyCollection propertyValues = CreatePropertyCollection(byteReader); this.InsertMarkupFeature(propertyValues); }
public void MultiPoint() { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgPoint mgpt1 = gf.CreatePoint(pt1); MgPoint mgpt2 = gf.CreatePoint(pt2); MgPoint mgpt3 = gf.CreatePoint(pt3); MgPoint mgpt4 = gf.CreatePoint(pt4); MgPointCollection points = new MgPointCollection(); points.Add(mgpt1); points.Add(mgpt2); points.Add(mgpt3); points.Add(mgpt4); MgMultiPoint mp = gf.CreateMultiPoint(points); Assert.AreEqual(4, mp.Count); Assert.AreEqual(MgGeometryType.MultiPoint, mp.GeometryType); Assert.AreEqual(0, mp.Dimension); }
private void btnCreatePointsOfInterest_Click(object sender, EventArgs e) { string layerName = "Points"; string legendLabel = "Points of Interest"; string groupName = "Analysis"; MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerGroupCollection groups = map.GetLayerGroups(); //NOTE: mg-desktop has no formal concept of a session repository, but we still //support session-based resources as a form of temporary resource (for the duration //of the application). Session ids in mg-desktop can be any arbitrary string string sessionId = Guid.NewGuid().ToString(); if (layers.IndexOf(layerName) >= 0) { MessageBox.Show("Layer (" + layerName + ") already created"); return; } //---------------------------------------------------// // Create a feature source with point data. // (The Sheboygan sample data does not contain such data, // so we"ll create it.) // Create a feature class definition for the new feature source MgClassDefinition classDefinition = new MgClassDefinition(); classDefinition.SetName("Points"); classDefinition.SetDescription("Feature class with point data."); classDefinition.SetDefaultGeometryPropertyName("GEOM"); MgPropertyDefinitionCollection idProps = classDefinition.GetIdentityProperties(); MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties(); // Create an identify property MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY"); identityProperty.SetDataType(MgPropertyType.Int32); identityProperty.SetAutoGeneration(true); identityProperty.SetReadOnly(true); // Add the identity property to the class definition clsProps.Add(identityProperty); idProps.Add(identityProperty); // Create a name property MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME"); nameProperty.SetDataType(MgPropertyType.String); // Add the name property to the class definition clsProps.Add(nameProperty); // Create a geometry property MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM"); geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point); // Add the geometry property to the class definition clsProps.Add(geometryProperty); // Create a feature schema MgFeatureSchema featureSchema = new MgFeatureSchema("PointSchema", "Point schema"); MgClassDefinitionCollection classes = featureSchema.GetClasses(); // Add the feature schema to the class definition classes.Add(classDefinition); // Create the feature source String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource"; MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName); //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]"; String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", wkt, featureSchema); featureService.CreateFeatureSource(resourceIdentifier, sdfParams); // We need to add some data to the sdf before using it. The spatial context // reader must have an extent. MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); // Make four points batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter)); // Old way commented out /* * // Add the batch property collection to the feature source * MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection); * MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection(); * featureCommandCollection.Add(cmd); * * // Execute the "add" commands * featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false); */ // Here's the mg-desktop way MgFeatureReader insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection); insertResult.Close(); // ... //---------------------------------------------------// // Create a new layer LayerDefinitionFactory factory = new LayerDefinitionFactory(); // Create a mark symbol String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary"; String symbolName = "PushPin"; String width = "24"; // unit = points String height = "24"; // unit = points String color = "FFFF0000"; String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color); // Create a text symbol String text = "ID"; String fontHeight = "12"; String foregroundColor = "FF000000"; String textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor); // Create a point rule. String ruleLegendLabel = "trees"; String filter = ""; String pointRule = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol); // Create a point type style. String pointTypeStyle = factory.CreatePointTypeStyle(pointRule); // Create a scale range. String minScale = "0"; String maxScale = "1000000000000"; String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle); // Create the layer definiton. String featureName = "PointSchema:Points"; String geometry = "GEOM"; String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange); //---------------------------------------------------// // ... XmlDocument domDocument = new XmlDocument(); domDocument.LoadXml(layerDefinition); //Add the layer to the map // TODO: Should probably validate this XML content using (MemoryStream ms = new MemoryStream()) { domDocument.Save(ms); ms.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] ldfBytes = ms.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(ldfBytes)); ldfBytes = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(ldfBytes, ldfBytes.Length); MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition"); resourceService.SetResource(resourceID, byteSource.GetReader(), null); //Insert this layer to our map MgdLayer newLayer = new MgdLayer(resourceID, resourceService); newLayer.Name = layerName; newLayer.LegendLabel = legendLabel; newLayer.DisplayInLegend = true; newLayer.SetVisible(true); layers.Insert(0, newLayer); //Create analysis group if not already created if (groups.IndexOf(groupName) < 0) { MgLayerGroup group = new MgLayerGroup(groupName); group.LegendLabel = groupName; group.DisplayInLegend = true; groups.Add(group); newLayer.Group = group; } MessageBox.Show("Layer (" + layerName + ") created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } }
public void AddBuffer() { MgMap map = new MgMap(); map.Open(_resourceService, GetParameter(this.args, "MAPNAME")); MgSelection selection = new MgSelection(map); selection.Open(_resourceService, map.Name); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null && layers.Count == 1) { MgFeatureQueryOptions opt = new MgFeatureQueryOptions(); opt.SetFilter(selection.GenerateFilter(layers[0], layers[0].FeatureClassName)); MgFeatureReader featureReader = _featureService.SelectFeatures(new MgResourceIdentifier(layers[0].FeatureSourceId), layers[0].FeatureClassName, opt); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); MgGeometryCollection inputGeometries = new MgGeometryCollection(); MgClassDefinition classDef = _featureService.GetClassDefinition( new MgResourceIdentifier(layers[0].FeatureSourceId), layers[0].FeatureClassName.Split(':')[0], layers[0].FeatureClassName.Split(':')[1]); while (featureReader.ReadNext()) { MgByteReader byteReader = featureReader.GetGeometry(classDef.DefaultGeometryPropertyName); MgGeometry geom = agfRW.Read(byteReader); inputGeometries.Add(geom); } if (inputGeometries.Count > 0) { MgCoordinateSystemFactory coordSysFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem mapSrs = coordSysFactory.Create(map.MapSRS); double distance = mapSrs.ConvertMetersToCoordinateSystemUnits(7.0); MgCoordinateSystemMeasure measure = mapSrs.GetMeasure(); MgGeometryFactory geomFactory = new MgGeometryFactory(); MgGeometry buffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(distance, measure); if (buffer != null) { MgByteReader byteReader = agfRW.Write(buffer); MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgAgfReaderWriter agfWriter = new MgAgfReaderWriter(); MgPropertyCollection propertyValues = CreatePropertyCollection(byteReader); this.InsertMarkupFeature(propertyValues); } } } }
public RenderMapControl() { InitializeComponent(); _geomFact = new MgGeometryFactory(); }
public void AddPoint() { MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgAgfReaderWriter agfWriter = new MgAgfReaderWriter(); String[] vertices = GetParameter(this.args, "GEOMETRY").Split(new Char[] { ',' }); MgCoordinate coord = geometryFactory.CreateCoordinateXY(Double.Parse(vertices[0]), Double.Parse(vertices[1])); MgPoint point = geometryFactory.CreatePoint(coord); point = (MgPoint)point.Transform(this.GetTransform()); MgByteReader byteReader = agfWriter.Write(point); MgPropertyCollection propertyValues = CreatePropertyCollection(byteReader); this.InsertMarkupFeature(propertyValues); }
string pointTransformAndWriteZ(string geom, MgMap map) { double[] x = new double[1]; double[] y = new double[1]; double[] z = new double[1]; MgWktReaderWriter wktrwdmr = new MgWktReaderWriter(); MgPoint cntr = wktrwdmr.Read(geom).Centroid; x[0] = cntr.Coordinate.X; y[0] = cntr.Coordinate.Y; z[0] = 0; StringBuilder output = new StringBuilder(); output.Append("<table width=\"100%\" class=\"results\">"); //WGS preko MG API MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktFrom = map.GetMapSRS(); string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem CSSource = fact.Create(wktFrom); MgCoordinateSystem CSTarget = fact.Create(wktTo); MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget); MgGeometryFactory geomFact = new MgGeometryFactory(); // GK //samo prvo višino zaenkrat, dokler ni enačbe za Z output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0]))); int i = 0; //transformacija preko MG koordinatnega sistema foreach (double pointX in x) { MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]); coord = coordTransform.Transform(coord); x[i] = coord.X; y[i] = coord.Y; i++; } double[] xwgs = x; double[] ywgs = y; output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0]))); output.Append("</table>"); return output.ToString(); }
public void Polygon() { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLinearRing linearRing = gf.CreateLinearRing(coordinates); MgPolygon polygon = gf.CreatePolygon(linearRing, null); Assert.AreEqual(linearRing.ToString(), polygon.ExteriorRing.ToString()); Assert.AreEqual(0, polygon.InteriorRingCount); Assert.AreEqual(MgGeometryType.Polygon, polygon.GeometryType); Assert.AreEqual(2, polygon.Dimension); }
private void btnCreatePointsOfInterest_Click(object sender, EventArgs e) { string layerName = "Points"; string legendLabel = "Points of Interest"; string groupName = "Analysis"; MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerGroupCollection groups = map.GetLayerGroups(); //NOTE: mg-desktop has no formal concept of a session repository, but we still //support session-based resources as a form of temporary resource (for the duration //of the application). Session ids in mg-desktop can be any arbitrary string string sessionId = Guid.NewGuid().ToString(); if (layers.IndexOf(layerName) >= 0) { MessageBox.Show("Layer (" + layerName + ") already created"); return; } //---------------------------------------------------// // Create a feature source with point data. // (The Sheboygan sample data does not contain such data, // so we"ll create it.) // Create a feature class definition for the new feature source MgClassDefinition classDefinition = new MgClassDefinition(); classDefinition.SetName("Points"); classDefinition.SetDescription("Feature class with point data."); classDefinition.SetDefaultGeometryPropertyName("GEOM"); MgPropertyDefinitionCollection idProps = classDefinition.GetIdentityProperties(); MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties(); // Create an identify property MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY"); identityProperty.SetDataType(MgPropertyType.Int32); identityProperty.SetAutoGeneration(true); identityProperty.SetReadOnly(true); // Add the identity property to the class definition clsProps.Add(identityProperty); idProps.Add(identityProperty); // Create a name property MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME"); nameProperty.SetDataType(MgPropertyType.String); // Add the name property to the class definition clsProps.Add(nameProperty); // Create a geometry property MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM"); geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point); // Add the geometry property to the class definition clsProps.Add(geometryProperty); // Create a feature schema MgFeatureSchema featureSchema = new MgFeatureSchema("PointSchema", "Point schema"); MgClassDefinitionCollection classes = featureSchema.GetClasses(); // Add the feature schema to the class definition classes.Add(classDefinition); // Create the feature source String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource"; MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName); //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]"; String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCreateSdfParams sdfParams = new MgCreateSdfParams("LatLong", wkt, featureSchema); featureService.CreateFeatureSource(resourceIdentifier, sdfParams); // We need to add some data to the sdf before using it. The spatial context // reader must have an extent. MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); // Make four points batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter)); // Old way commented out /* // Add the batch property collection to the feature source MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection); MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection(); featureCommandCollection.Add(cmd); // Execute the "add" commands featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false); */ // Here's the mg-desktop way MgPropertyCollection insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection); for (int i = 0; i < insertResult.GetCount(); i++) { MgFeatureProperty fp = insertResult.GetItem(i) as MgFeatureProperty; if (fp != null) { MgFeatureReader fr = fp.GetValue(); fr.Close(); } } // ... //---------------------------------------------------// // Create a new layer LayerDefinitionFactory factory = new LayerDefinitionFactory(); // Create a mark symbol String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary"; String symbolName = "PushPin"; String width = "24"; // unit = points String height = "24"; // unit = points String color = "FFFF0000"; String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color); // Create a text symbol String text = "ID"; String fontHeight = "12"; String foregroundColor = "FF000000"; String textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor); // Create a point rule. String ruleLegendLabel = "trees"; String filter = ""; String pointRule = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol); // Create a point type style. String pointTypeStyle = factory.CreatePointTypeStyle(pointRule); // Create a scale range. String minScale = "0"; String maxScale = "1000000000000"; String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle); // Create the layer definiton. String featureName = "PointSchema:Points"; String geometry = "GEOM"; String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange); //---------------------------------------------------// // ... XmlDocument domDocument = new XmlDocument(); domDocument.LoadXml(layerDefinition); //Add the layer to the map // TODO: Should probably validate this XML content using (MemoryStream ms = new MemoryStream()) { domDocument.Save(ms); ms.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] ldfBytes = ms.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(ldfBytes)); ldfBytes = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(ldfBytes, ldfBytes.Length); MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition"); resourceService.SetResource(resourceID, byteSource.GetReader(), null); //Insert this layer to our map MgdLayer newLayer = new MgdLayer(resourceID, resourceService); newLayer.Name = layerName; newLayer.LegendLabel = legendLabel; newLayer.DisplayInLegend = true; newLayer.SetVisible(true); layers.Insert(0, newLayer); //Create analysis group if not already created if (groups.IndexOf(groupName) < 0) { MgLayerGroup group = new MgLayerGroup(groupName); group.LegendLabel = groupName; group.DisplayInLegend = true; groups.Add(group); newLayer.Group = group; } MessageBox.Show("Layer (" + layerName + ") created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) legend.RefreshLegend(); } }
public void MultiLineString() { MgGeometryFactory gf = new MgGeometryFactory(); MgCoordinate pt1 = gf.CreateCoordinateXY(0, 0); MgCoordinate pt2 = gf.CreateCoordinateXY(0, 10); MgCoordinate pt3 = gf.CreateCoordinateXY(10, 10); MgCoordinate pt4 = gf.CreateCoordinateXY(10, 0); MgCoordinateCollection coordinates = new MgCoordinateCollection(); coordinates.Add(pt1); coordinates.Add(pt2); coordinates.Add(pt3); coordinates.Add(pt4); MgLineString ls = gf.CreateLineString(coordinates); MgLineStringCollection lineStringCollection = new MgLineStringCollection(); lineStringCollection.Add(ls); MgMultiLineString mls = gf.CreateMultiLineString(lineStringCollection); Assert.AreEqual(1, mls.Count); Assert.AreEqual(MgGeometryType.MultiLineString, mls.GeometryType); Assert.AreEqual(1, mls.Dimension); }
private void btnCreate_Click(object sender, EventArgs e) { btnCreate.Enabled = false; try { var layerName = txtBufferLayer.Text.Trim(); if (string.IsNullOrEmpty(layerName)) { MessageBox.Show(Strings.MsgEnterNameForLayer); return; } if (lstLayers.SelectedItems.Count == 0) { MessageBox.Show(Strings.MsgIncludeLayersToBuffer); return; } var map = _viewer.GetMap(); var layers = map.GetLayers(); var provider = _viewer.GetProvider(); //From here, it's the same logic as buffer.aspx in .net MapGuide AJAX viewer MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.FeatureSource"); //NOXLATE MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + _sessionId + "//" + txtBufferLayer.Text + "_Buffer.LayerDefinition"); //NOXLATE MgLayerBase layer = Util.FindLayer(layers, txtBufferLayer.Text); string[] layerNames = GetLayerNames(); double distance = Convert.ToDouble(numBufferDistance.Value); MeasurementUnit bUnits = (MeasurementUnit)cmbUnits.SelectedItem; switch (bUnits) { case MeasurementUnit.Feet: distance *= 0.30480; break; case MeasurementUnit.Kilometers: distance *= 1000; break; case MeasurementUnit.Miles: distance *= 1609.35; break; } String srsDefMap = Util.GetMapSrs(map); MgCoordinateSystem srsMap = provider.GetMapCoordinateSystem(); string mapSrsUnits = ""; bool arbitraryMapSrs = (srsMap.GetType() == MgCoordinateSystemType.Arbitrary); if (arbitraryMapSrs) { mapSrsUnits = srsMap.GetUnits(); } String xtrans = String.Format("{0:x2}", ((int)(255 * Convert.ToInt32(numFillTransparency.Value) / 100))); //NOXLATE var lineColor = Util.ToHtmlColor(pnlBorderColor.BackColor); var foreColor = Util.ToHtmlColor(pnlFillColor.BackColor); var backColor = Util.ToHtmlColor(pnlFillBackColor.BackColor); String layerTempl = string.Format(Properties.Resources.AreaLayerDef, fsId.ToString(), "BufferSchema:Buffer", //NOXLATE "GEOM", //NOXLATE cmbFillPattern.SelectedItem, xtrans + foreColor, ((0 != 1 /*transparent*/) ? "ff" : "00") + backColor, //NOXLATE cmbBorderPattern.SelectedItem, numLineThickness.Value.ToString(NumberFormatInfo.InvariantInfo), lineColor ); byte[] bytes = Encoding.UTF8.GetBytes(layerTempl); MgByteSource src = new MgByteSource(bytes, bytes.Length); MgByteReader layerDefContent = src.GetReader(); _resSvc.SetResource(ldfId, layerDefContent, null); bool newBuffer = false; if (layer == null) { newBuffer = true; //Targetting a new layer. create a data source for it // MgClassDefinition classDef = new MgClassDefinition(); classDef.SetName("Buffer"); //NOXLATE classDef.SetDescription("Feature class for buffer layer"); //NOXLATE classDef.SetDefaultGeometryPropertyName("GEOM"); //NOXLATE //Set KEY property MgDataPropertyDefinition prop = new MgDataPropertyDefinition("KEY"); //NOXLATE prop.SetDataType(MgPropertyType.Int32); prop.SetAutoGeneration(true); prop.SetReadOnly(true); classDef.GetIdentityProperties().Add(prop); classDef.GetProperties().Add(prop); //Set ID property. Hold this segment ID prop = new MgDataPropertyDefinition("ID"); //NOXLATE prop.SetDataType(MgPropertyType.Int32); classDef.GetProperties().Add(prop); //Set geometry property MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM"); //NOXLATE //prop.SetGeometryTypes(MgFeatureGeometricType.mfgtSurface); //TODO use the constant when exposed geomProp.SetGeometryTypes(4); classDef.GetProperties().Add(geomProp); //Create the schema MgFeatureSchema schema = new MgFeatureSchema("BufferSchema", "Temporary buffer schema"); //NOXLATE schema.GetClasses().Add(classDef); //finally, creation of the feature source MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", map.GetMapSRS(), schema); //NOXLATE _featSvc.CreateFeatureSource(fsId, sdfParams); //Add layer to map layer = provider.CreateLayer(ldfId); layer.SetName(txtBufferLayer.Text); layer.SetLegendLabel(txtBufferLayer.Text); layer.SetDisplayInLegend(true); layer.SetSelectable(true); layers.Insert(0, layer); } else { //data source already exist. clear its content // Util.ClearDataSource(_featSvc, fsId, "BufferSchema:Buffer"); //NOXLATE } var sel = _viewer.GetSelection(); var selLayers = sel.GetLayers(); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); MgGeometryCollection bufferGeometries = new MgGeometryCollection(); MgGeometry geomBuffer; MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); int featId = 0; MgBatchPropertyCollection propCollection = new MgBatchPropertyCollection(); int excludedLayers = 0; MgCoordinateSystem srsDs = null; MgGeometryCollection inputGeometries = new MgGeometryCollection(); int bufferFeatures = 0; for (int li = 0; li < selLayers.GetCount(); li++) { MgLayerBase selLayer = selLayers.GetItem(li); bool inputLayer = false; String selLayerName = selLayer.GetName(); for (int il = 0; il < layerNames.Length; il++) { if (layerNames[il].Equals(selLayerName)) { inputLayer = true; break; } } if (inputLayer == false) { continue; } // get the data source SRS // MgResourceIdentifier featSourceId = new MgResourceIdentifier(selLayer.GetFeatureSourceId()); MgSpatialContextReader ctxs = _featSvc.GetSpatialContexts(featSourceId, false); String srsDefDs = string.Empty; if (ctxs != null && ctxs.ReadNext()) { srsDefDs = ctxs.GetCoordinateSystemWkt(); } if (srsDefDs == null || srsDefDs.Length == 0) { excludedLayers++; continue; } var srsFactory = new MgCoordinateSystemFactory(); srsDs = srsFactory.Create(srsDefDs); bool arbitraryDsSrs = (srsDs.GetType() == MgCoordinateSystemType.Arbitrary); String dsSrsUnits = string.Empty; if (arbitraryDsSrs) { dsSrsUnits = srsDs.GetUnits(); } // exclude layer if: // the map is non-arbitrary and the layer is arbitrary or vice-versa // or // layer and map are both arbitrary but have different units // if ((arbitraryDsSrs != arbitraryMapSrs) || (arbitraryDsSrs && (dsSrsUnits != mapSrsUnits))) { excludedLayers++; continue; } // calculate distance in the data source SRS units // double dist = srsDs.ConvertMetersToCoordinateSystemUnits(distance); // calculate great circle unless data source srs is arbitrary MgCoordinateSystemMeasure measure; if (!arbitraryDsSrs) { measure = srsDs.GetMeasure(); } else { measure = null; } // create a SRS transformer if necessary MgCoordinateSystemTransform srsXform; if (!srsDefDs.Equals(srsDefMap)) { srsXform = srsFactory.GetTransform(srsDs, srsMap); } else { srsXform = null; } String featureClassName = selLayer.GetFeatureClassName(); String filter = sel.GenerateFilter(selLayer, featureClassName); if (filter == null || filter.Length == 0) { continue; } MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(filter); MgResourceIdentifier featureSource = new MgResourceIdentifier(selLayer.GetFeatureSourceId()); MgFeatureReader features = _featSvc.SelectFeatures(featureSource, featureClassName, query); if (features.ReadNext()) { MgClassDefinition classDef = features.GetClassDefinition(); String geomPropName = classDef.GetDefaultGeometryPropertyName(); do { MgByteReader geomReader = features.GetGeometry(geomPropName); MgGeometry geom = agfRW.Read(geomReader); if (!chkMergeBuffers.Checked) { geomBuffer = geom.Buffer(dist, measure); if (geomBuffer != null) { if (srsXform != null) { geomBuffer = (MgGeometry)geomBuffer.Transform(srsXform); } Util.AddFeatureToCollection(propCollection, agfRW, featId++, geomBuffer); bufferFeatures++; } } else { if (srsXform != null) { geom = (MgGeometry)geom.Transform(srsXform); } inputGeometries.Add(geom); } }while (features.ReadNext()); features.Close(); } } if (chkMergeBuffers.Checked) { if (inputGeometries.GetCount() > 0) { double dist = srsMap.ConvertMetersToCoordinateSystemUnits(distance); MgCoordinateSystemMeasure measure; if (!arbitraryMapSrs) { measure = srsMap.GetMeasure(); } else { measure = null; } MgGeometryFactory geomFactory = new MgGeometryFactory(); geomBuffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(dist, measure); if (geomBuffer != null) { Util.AddFeatureToCollection(propCollection, agfRW, featId, geomBuffer); bufferFeatures = 1; } } } if (propCollection.GetCount() > 0) { commands.Add(new MgInsertFeatures("BufferSchema:Buffer", propCollection)); //NOXLATE //Insert the features in the temporary data source // Util.ReleaseReader(_featSvc.UpdateFeatures(fsId, commands, false), commands); } // Save the new map state // layer.ForceRefresh(); _viewer.RefreshMap(); //build report message if (newBuffer) { MessageBox.Show(string.Format(Strings.MsgBufferLayerCreated, txtBufferLayer.Text)); } else { MessageBox.Show(string.Format(Strings.MsgBufferLayerUpdated, txtBufferLayer.Text)); } } finally { btnCreate.Enabled = true; } }
private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection selectedLayers = selection.GetLayers(); if (selectedLayers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < selectedLayers.GetCount(); i++) { MgLayerBase layer = selectedLayers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 500; // measured in metres // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); string sessionId = Guid.NewGuid().ToString(); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. BufferHelper helper = new BufferHelper(); MgdLayer bufferLayer = null; int layerIndex = map.GetLayers().IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); map.GetLayers().Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Check for a parcel marker layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the parcel markers. MgdLayer parcelMarkerLayer = null; layerIndex = map.GetLayers().IndexOf("ParcelMarker"); if (layerIndex < 0) { MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource"); helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId); parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId); map.GetLayers().Insert(0, parcelMarkerLayer); } else { parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); parcelMarkerLayer.DeleteFeatures("ID like '%'"); } // Check each layer in the selection. for (int i = 0; i < selectedLayers.GetCount(); i++) { // Only check selected features in the Parcels layer. MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i); if (layer.GetName() == "Parcels") { string geomName = layer.GetFeatureGeometryName(); System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'"); MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(geomName); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Create a buffer from the merged geometries double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); // Create a filter to select parcels within the buffer. Combine // a basic filter and a spatial filter to select all parcels // within the buffer that are of type "MFG". MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions(); queryOptions.SetFilter("RTYPE = 'MFG'"); queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside); featureReader = layer.SelectFeatures(queryOptions); // Get the features from the feature source, // determine the centroid of each selected feature, and // add a point to the ParcelMarker layer to mark the // centroid. // Collect all the points into an MgFeatureCommandCollection, // so they can all be added in one operation. MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection(); int inserted = 0; while (featureReader.ReadNext()) { MgByteReader byteReader = featureReader.GetGeometry(geomName); MgGeometry geometry = agfReaderWriter.Read(byteReader); MgPoint point = geometry.GetCentroid(); // Create an insert command for this parcel. MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point))); //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties)); MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties); fr.Close(); inserted++; } featureReader.Close(); if (inserted == 0) { MessageBox.Show("No parcels within the buffer area match."); return; } // Create a feature in the buffer feature source to show the area covered by the buffer. MgPropertyCollection props = new MgPropertyCollection(); props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); bufferLayer.InsertFeatures(props); // Ensure that the buffer layer is visible and in the legend. bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); parcelMarkerLayer.SetVisible(true); parcelMarkerLayer.ForceRefresh(); MessageBox.Show("Done"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) legend.RefreshLegend(); } } }
private MgPolygon CreatePolygonFromGeomText(String geomText) { MgGeometryFactory geometryFactory = new MgGeometryFactory(); String[] vertices = geomText.Split(new Char[] { ',' }); int count = Int32.Parse(vertices[0]); MgCoordinateCollection coords = new MgCoordinateCollection(); for (int i = 0; i < count; i++) { MgCoordinate coord = geometryFactory.CreateCoordinateXY(Double.Parse(vertices[(i * 2) + 1]), Double.Parse(vertices[(i * 2) + 2])); coords.Add(coord); } MgLinearRing linearRing = geometryFactory.CreateLinearRing(coords); MgPolygon polygon = geometryFactory.CreatePolygon(linearRing, null); return polygon; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ������ʱ�� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public bool CreatePointsLayer(String rootPath, String sessionId) { // ��ȡҪ�ط������Դ���� MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); // ��ͼ MgMap map = new MgMap(); map.Open(resourceService, "Sheboygan"); // ---Ҫ�����Ҫ�ز������û��������������滹Ҫ���ܣ�--��ʼ // ���������ݵ�Ҫ��Դ CreateFeatureSource(sessionId); String featureSourceName = "Session:" + sessionId + "//Points.FeatureSource"; MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName); MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); // �������¼ MgPropertyCollection propertyCollection = MakePoint("Point A", -87.727, 43.748); batchPropertyCollection.Add(propertyCollection); propertyCollection = MakePoint("Point B", -87.728, 43.730); batchPropertyCollection.Add(propertyCollection); propertyCollection = MakePoint("Point C", -87.726, 43.750); batchPropertyCollection.Add(propertyCollection); propertyCollection = MakePoint("Point D", -87.728, 43.750); batchPropertyCollection.Add(propertyCollection); // ��������Ҫ��������ӵ�Ҫ��Դ MgInsertFeatures Insertcmd = new MgInsertFeatures("Points", batchPropertyCollection); MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection(); featureCommandCollection.Add(Insertcmd); featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false); MgResourceIdentifier resourceID = null; //--------------Ҫ�����Ҫ�ز��� ���� // �����㣬ͨ���㹤��LayerDefinitionFactory LayerDefinitionFactory factory = new LayerDefinitionFactory(); factory.RootDirectoryPath = rootPath; //-------------------��������ʽ------------------------// // ������Ƿ���l string resourceSymbel = "Library://MgTutorial/Symbols/BasicSymbols.SymbolLibrary"; string symbolName = "PushPin"; string width = "24"; // unit = points string height = "24"; // unit = points string color = "FFFF0000"; string markSymbol = factory.CreateMarkSymbol(resourceSymbel, symbolName, width, height, color); // �����ı� string text = "ID"; string fontHeight = "12"; string foregroundColor = "FF000000"; string textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor); // ��������� string legendLabel = "trees"; string filter = ""; string pointRule = factory.CreatePointRule(legendLabel, filter, textSymbol, markSymbol); // ��������ʽ string pointTypeStyle = factory.CreatePointTypeStyle(pointRule); // �������ŷ�Χ string minScale = "0"; string maxScale = "1000000000000"; string pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle); // �����㶨�� string featureName = "PointSchema:Points"; string geometry = "GEOM"; string layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange); MgByteSource byteSource = new MgByteSource(Encoding.UTF8.GetBytes(layerDefinition), layerDefinition.Length); MgByteReader byteReader = byteSource.GetReader(); resourceID = new MgResourceIdentifier("Session:" + sessionId + "//Points.LayerDefinition"); resourceService.SetResource(resourceID, byteReader, null); //��������IJ㶨�����ݣ������ã� MgByteSink byteSink = new MgByteSink(resourceService.GetResourceContent(resourceID)); string filePath = "C:\\Temp\\LayerDefinition.xml"; byteSink.ToFile(filePath); // �����㲢��ӵ�����͵�ͼ�� MgLayer newLayer = CreateLayerResource(resourceID, resourceService, "Points", "��ʱ��", map); AddLayerToGroup(newLayer, "Analysis", "����", map); MgLayerCollection layerCollection = map.GetLayers(); if (layerCollection.Contains("Points")) { MgLayer pointsLayer = layerCollection.GetItem("Points"); pointsLayer.SetVisible(true); } // �����ͼ map.Save(resourceService); return true; }
MgGeometry MultiGeometryFromSelection(MgFeatureService featureSrvc, MgMap map, String selText) { MgSelection sel = new MgSelection(map); sel.FromXml(selText); MgReadOnlyLayerCollection selLayers = sel.GetLayers(); if (selLayers == null) return null; MgGeometryCollection geomColl = new MgGeometryCollection(); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); bool polyOnly = true; for (int i = 0; i < selLayers.GetCount(); i++) { MgLayer layer = (MgLayer)selLayers.GetItem(i); // TODO: How to get selectionSize? //int selectionSize = 20; string filter = sel.GenerateFilter(layer, layer.GetFeatureClassName()); if (filter == "") continue; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(filter); MgResourceIdentifier featureSource = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureReader features = featureSrvc.SelectFeatures(featureSource, layer.GetFeatureClassName(), query); if (features != null) { MgClassDefinition classDef = features.GetClassDefinition(); String geomPropName = classDef.GetDefaultGeometryPropertyName(); int j = 0; //bool isPoly = true; while (features.ReadNext()) { MgByteReader geomReader = features.GetGeometry(geomPropName); MgGeometry geom = agfRW.Read(geomReader); if (j++ == 0) { int type = geom.GetGeometryType(); if (type == MgGeometryType.MultiPolygon || type == MgGeometryType.CurvePolygon || type == MgGeometryType.MultiCurvePolygon) { //isPoly = false; polyOnly = false; } else if (type != MgGeometryType.Polygon) { break; } } geomColl.Add(geom); } features.Close(); features.Dispose(); } } if (geomColl.GetCount() == 0) { return null; } MgGeometryFactory gf = new MgGeometryFactory(); if (polyOnly) { MgPolygonCollection polyColl = new MgPolygonCollection(); for (int j = 0; j < geomColl.GetCount(); j++) { polyColl.Add((MgPolygon)geomColl.GetItem(j)); } return gf.CreateMultiPolygon(polyColl); } else { return gf.CreateMultiGeometry(geomColl); } }
MgGeometry MultiGeometryFromSelection(MgFeatureService featureSrvc, MgMap map, String selText) { MgSelection sel = new MgSelection(map); sel.FromXml(selText); MgReadOnlyLayerCollection selLayers = sel.GetLayers(); if (selLayers == null) { return(null); } MgGeometryCollection geomColl = new MgGeometryCollection(); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); bool polyOnly = true; for (int i = 0; i < selLayers.GetCount(); i++) { MgLayer layer = (MgLayer)selLayers.GetItem(i); // TODO: How to get selectionSize? //int selectionSize = 20; string filter = sel.GenerateFilter(layer, layer.GetFeatureClassName()); if (filter == "") { continue; } MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(filter); MgResourceIdentifier featureSource = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureReader features = featureSrvc.SelectFeatures(featureSource, layer.GetFeatureClassName(), query); if (features != null) { MgClassDefinition classDef = features.GetClassDefinition(); String geomPropName = classDef.GetDefaultGeometryPropertyName(); int j = 0; //bool isPoly = true; while (features.ReadNext()) { MgByteReader geomReader = features.GetGeometry(geomPropName); MgGeometry geom = agfRW.Read(geomReader); if (j++ == 0) { int type = geom.GetGeometryType(); if (type == MgGeometryType.MultiPolygon || type == MgGeometryType.CurvePolygon || type == MgGeometryType.MultiCurvePolygon) { //isPoly = false; polyOnly = false; } else if (type != MgGeometryType.Polygon) { break; } } geomColl.Add(geom); } features.Close(); features.Dispose(); } } if (geomColl.GetCount() == 0) { return(null); } MgGeometryFactory gf = new MgGeometryFactory(); if (polyOnly) { MgPolygonCollection polyColl = new MgPolygonCollection(); for (int j = 0; j < geomColl.GetCount(); j++) { polyColl.Add((MgPolygon)geomColl.GetItem(j)); } return(gf.CreateMultiPolygon(polyColl)); } else { return(gf.CreateMultiGeometry(geomColl)); } }
public void InitMapGuide() { MapGuideApi.MgInitializeWebTier("d:/mgdev/web/src/webconfig.ini"); factory = new MgGeometryFactory(); wkt = new MgWktReaderWriter(); build = new GeomBuild(); }
private void btnCreateBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase layer = layers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 100; // measured in metres int bufferRingCount = 5; // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); string sessionId = Guid.NewGuid().ToString(); BufferHelper helper = new BufferHelper(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. MgdLayer bufferLayer = null; int layerIndex = mapLayers.IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); mapLayers.Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Get the selected features from the MgSelection object MgFeatureReader featureReader = selection.GetSelectedFeatures(parcels, parcels.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(parcels.GetFeatureGeometryName()); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Add buffer features to the temporary feature source. // Create multiple concentric buffers to show area. // If the stylization for the layer draws the features // partially transparent, the concentric rings will be // progressively darker towards the center. // The stylization is set in the layer template file, which // is used in function CreateBufferLayer(). for (int bufferRing = 0; bufferRing < bufferRingCount; bufferRing++) { double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize * (bufferRing + 1)); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); MgFeatureReader fr = bufferLayer.InsertFeatures(properties); fr.Close(); } bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); MessageBox.Show("Buffer created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) legend.RefreshLegend(); }
private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection selectedLayers = selection.GetLayers(); if (selectedLayers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < selectedLayers.GetCount(); i++) { MgLayerBase layer = selectedLayers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 500; // measured in metres // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); string sessionId = Guid.NewGuid().ToString(); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. BufferHelper helper = new BufferHelper(); MgdLayer bufferLayer = null; int layerIndex = map.GetLayers().IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); map.GetLayers().Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Check for a parcel marker layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the parcel markers. MgdLayer parcelMarkerLayer = null; layerIndex = map.GetLayers().IndexOf("ParcelMarker"); if (layerIndex < 0) { MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource"); helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId); parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId); map.GetLayers().Insert(0, parcelMarkerLayer); } else { parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); parcelMarkerLayer.DeleteFeatures("ID like '%'"); } // Check each layer in the selection. for (int i = 0; i < selectedLayers.GetCount(); i++) { // Only check selected features in the Parcels layer. MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i); if (layer.GetName() == "Parcels") { string geomName = layer.GetFeatureGeometryName(); System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'"); MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(geomName); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Create a buffer from the merged geometries double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); // Create a filter to select parcels within the buffer. Combine // a basic filter and a spatial filter to select all parcels // within the buffer that are of type "MFG". MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions(); queryOptions.SetFilter("RTYPE = 'MFG'"); queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside); featureReader = layer.SelectFeatures(queryOptions); // Get the features from the feature source, // determine the centroid of each selected feature, and // add a point to the ParcelMarker layer to mark the // centroid. // Collect all the points into an MgFeatureCommandCollection, // so they can all be added in one operation. MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection(); int inserted = 0; while (featureReader.ReadNext()) { MgByteReader byteReader = featureReader.GetGeometry(geomName); MgGeometry geometry = agfReaderWriter.Read(byteReader); MgPoint point = geometry.GetCentroid(); // Create an insert command for this parcel. MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point))); //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties)); MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties); fr.Close(); inserted++; } featureReader.Close(); if (inserted == 0) { MessageBox.Show("No parcels within the buffer area match."); return; } // Create a feature in the buffer feature source to show the area covered by the buffer. MgPropertyCollection props = new MgPropertyCollection(); props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); bufferLayer.InsertFeatures(props); // Ensure that the buffer layer is visible and in the legend. bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); parcelMarkerLayer.SetVisible(true); parcelMarkerLayer.ForceRefresh(); MessageBox.Show("Done"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } } }
public override System.IO.Stream RenderRuntimeMap(RuntimeMap rtmap, double x, double y, double scale, int width, int height, int dpi, string format, bool clip) { var resourceId = rtmap.ResourceID; MgRenderingService rnd = this.Connection.CreateService(MgServiceType.RenderingService) as MgRenderingService; MgResourceService res = this.Connection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgGeometryFactory gf = new MgGeometryFactory(); string mapname = new ResourceIdentifier(resourceId).Path; GetByteReaderMethod fetch = () => { MgMap map = new MgMap(); map.Open(res, mapname); MgSelection sel = new MgSelection(map); //The color accepted by MgColor has alpha as the last value, but the returned has alpha first MgColor color = new MgColor(Utility.ParseHTMLColor(map.GetBackgroundColor())); MgCoordinate coord = gf.CreateCoordinateXY(x, y); return rnd.RenderMap(map, sel, coord, scale, width, height, color, format, true); }; LogMethodCall("MgRenderingService::RenderMap", true, "MgMap", "MgSelection", "MgPoint("+ x + "," + y + ")", scale.ToString(), width.ToString(), height.ToString(), "MgColor", format, true.ToString()); return new MgReadOnlyStream(fetch); }