/// <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); }
private void OnLineDigitized(double x1, double y1, double x2, double y2) { MgMapBase map = mgMapViewer1.GetMap(); //Create a coordiante system from the map's SRS MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem mapCs = csFactory.Create(map.GetMapSRS()); //Invoke the appropriate measure method depending on the type //of coordinate system double dist = 0.0; if (mapCs.GetType() == MgCoordinateSystemType.Geographic) { dist = mapCs.MeasureGreatCircleDistance(x1, y1, x2, y2); } else { dist = mapCs.MeasureEuclideanDistance(x1, y1, x2, y2); } //Convert this distance to meters dist = mapCs.ConvertCoordinateSystemUnitsToMeters(dist); MessageBox.Show("Distance is: " + dist + " meters"); }
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 MgLineMeasureControlImpl(IMapViewer viewer, MeasurementUnit preferredUnit) { InitializeComponent(); this.Title = Strings.TitleMeasure; _viewer = viewer; _segments = new BindingList<MeasuredLineSegment>(); cmbUnits.DataSource = Enum.GetValues(typeof(MeasurementUnit)); cmbUnits.SelectedItem = preferredUnit; lstSegments.DataSource = _segments; _mapCs = _viewer.GetProvider().GetMapCoordinateSystem(); }
public MgLineMeasureControlImpl(IMapViewer viewer, MeasurementUnit preferredUnit) { InitializeComponent(); this.Title = Strings.TitleMeasure; _viewer = viewer; _segments = new BindingList <MeasuredLineSegment>(); cmbUnits.DataSource = Enum.GetValues(typeof(MeasurementUnit)); cmbUnits.SelectedItem = preferredUnit; lstSegments.DataSource = _segments; _mapCs = _viewer.GetProvider().GetMapCoordinateSystem(); }
private static void Main(string[] args) { if (args.Length == 1) { if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MENTOR_DICTIONARY_PATH"))) { var currentDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); var dictionaryDir = Path.Combine(currentDir, "Dictionaries"); if (Directory.Exists(dictionaryDir)) { Environment.SetEnvironmentVariable("MENTOR_DICTIONARY_PATH", dictionaryDir, EnvironmentVariableTarget.Process); } else { Console.WriteLine("Error: Could not find CS-Map dictionary path"); } } MgCoordinateSystemFactory csFact = null; MgCoordinateSystem cs = null; try { csFact = new MgCoordinateSystemFactory(); cs = csFact.Create(args[0]); double mpu = cs.ConvertCoordinateSystemUnitsToMeters(1.0); Console.WriteLine(mpu); cs.Dispose(); csFact.Dispose(); } catch (MgException ex) { Console.WriteLine(ex.Message); ex.Dispose(); } finally { if (cs != null) { cs.Dispose(); } if (csFact != null) { csFact.Dispose(); } } } else { Console.WriteLine("Error: Insufficient arguments. Usage: MpuCalc.exe [Coord sys WKT]"); } }
public void Execute(IPlatformFactory factory, ITestLogger logger) { MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem coordSys = csFactory.CreateFromCode("LL84"); Assert.AreEqual(MgCoordinateSystemType.Geographic, coordSys.Type); Assert.AreEqual("DEGREE", coordSys.Units); Assert.AreEqual(-180, coordSys.MinX); Assert.AreEqual(-90, coordSys.MinY); Assert.AreEqual(180, coordSys.MaxX); Assert.AreEqual(90, coordSys.MaxY); Assert.AreEqual("LL84", coordSys.CsCode); Assert.AreEqual("WGS84 datum, Latitude-Longitude; Degrees", coordSys.Description); Assert.AreEqual("LL", coordSys.Projection); Assert.AreEqual("Null Projection, produces/processes Latitude & Longitude", coordSys.ProjectionDescription); Assert.AreEqual("WGS84", coordSys.Datum); Assert.AreEqual("World Geodetic System of 1984", coordSys.DatumDescription); Assert.AreEqual("WGS84", coordSys.Ellipsoid); Assert.AreEqual("World Geodetic System of 1984, GEM 10C", coordSys.EllipsoidDescription); }
/// <summary> /// Node GetListOfMAPCSLIBRAR for export to LSP file naming of coordinate systems (user or system) /// </summary> /// <param name="CS_value">Name of type "CoordinateSystem"</param> /// <param name="selection">If false - exporting only User's definitions; if true - exporting only system definitions</param> /// <param name="CS_Agree">Permit to add other associated definitions</param> /// <param name="Folder_Path">Directory path to save LSP file</param> public static void GetPartOfMAPCSLIBRARY(string Folder_Path, string CS_value, string CS_Agree, bool selection) { var guid = Guid.NewGuid(); string writePath = $@"{Folder_Path}\{guid}.lsp"; StringBuilder sb = new StringBuilder(); MgCoordinateSystemFactory coordSysFactory = new MgCoordinateSystemFactory(); MgCoordinateSystemCatalog csCatalog = coordSysFactory.GetCatalog(); MgCoordinateSystemDictionary csDict = csCatalog.GetCoordinateSystemDictionary(); MgCoordinateSystemEnum csDictEnum = csDict.GetEnum(); int csCount = csDict.GetSize(); sb.AppendLine(@"(command ""MAPCSLIBRARYEXPORT"""); MgStringCollection csNames = csDictEnum.NextName(csCount); string csName = null; MgCoordinateSystem cs = null; bool csProtect; for (int i = 0; i < csCount; i++) { csName = csNames.GetItem(i); cs = csDict.GetCoordinateSystem(csName); csProtect = cs.IsProtected(); if (csProtect == selection) { sb.AppendLine($@"""{csName}""" + " " + $"\"{CS_value}\""); } } string space = " "; sb.AppendLine(" " + $@"""{space}""" + " " + $@"""{CS_Agree}""" + " " + @"""""" + ")"); using (StreamWriter export_file = new StreamWriter(writePath, true, Encoding.UTF8)) { export_file.Write(sb.ToString()); } }
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(',', '.')); }
/// <summary> /// Node GetCSList returns an external txt file that Contains strings with CS's names /// </summary> /// <param name="Folder_Path">Directory path to save TXT file</param> /// <param name="selection">If = true, export all CS in Library, if false - only Users collection</param> public static string GetCSList(string Folder_Path, bool selection) { StringBuilder sb = new StringBuilder(); var guid = Guid.NewGuid(); string writePath = $@"{Folder_Path}\{guid}CS_List.txt"; MgCoordinateSystemFactory coordSysFactory = new MgCoordinateSystemFactory(); MgCoordinateSystemCatalog csCatalog = coordSysFactory.GetCatalog(); MgCoordinateSystemDictionary csDict = csCatalog.GetCoordinateSystemDictionary(); MgCoordinateSystemEnum csDictEnum = csDict.GetEnum(); int csCount = csDict.GetSize(); MgStringCollection csNames = csDictEnum.NextName(csCount); string csName = null; MgCoordinateSystem cs = null; bool csProtect; for (int i = 0; i < csCount; i++) { csName = csNames.GetItem(i); cs = csDict.GetCoordinateSystem(csName); csProtect = cs.IsProtected(); if (csProtect == selection) { sb.AppendLine(csName.ToString()); } } using (StreamWriter export_file = new StreamWriter(writePath, true, Encoding.UTF8)) { export_file.Write(sb.ToString()); } return(writePath); }
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 double Calculate(string csWkt, double units) { MgCoordinateSystem cs = _csFact.Create(csWkt); return(cs.ConvertCoordinateSystemUnitsToMeters(units)); }
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; } }
/// <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); }
private void OnMapSetOnProvider(object sender, EventArgs e) { _hasTiledLayers = null; _map = _provider.GetMap(); _mapCs = _provider.GetMapCoordinateSystem(); _mapMeasure = _mapCs.GetMeasure(); var bgColor = _map.GetBackgroundColor(); if (bgColor.Length == 8 || bgColor.Length == 6) { _mapBgColor = ColorTranslator.FromHtml("#" + bgColor); //NOXLATE this.BackColor = _mapBgColor; } _provider.SetDisplaySize(this.Width, this.Height); _selection = _provider.CreateSelectionForMap(); var env = _map.GetMapExtent(); var ll = env.LowerLeftCoordinate; var ur = env.UpperRightCoordinate; _extX1 = _orgX1 = ll.X; _extY2 = _orgY2 = ll.Y; _extX2 = _orgX2 = ur.X; _extY1 = _orgY1 = ur.Y; if ((_orgX1 - _orgX2) == 0 || (_orgY1 - _orgY2) == 0) { _extX1 = _orgX1 = -.1; _extY2 = _orgX2 = .1; _extX2 = _orgY1 = -.1; _extY1 = _orgY2 = .1; } if (this.ConvertTiledGroupsToNonTiled) { var groups = _map.GetLayerGroups(); for (int i = 0; i < groups.GetCount(); i++) { var group = groups.GetItem(i); _provider.MakeGroupNormal(group); } } #if VIEWER_DEBUG CreateDebugFeatureSource(); #endif this.Focus(); //Reset history stack _viewHistory.Clear(); OnPropertyChanged("ViewHistory"); //NOXLATE _viewHistoryIndex = -1; OnPropertyChanged("ViewHistoryIndex"); //NOXLATE var handler = this.MapLoaded; if (handler != null) handler(this, EventArgs.Empty); InitialMapView(); }
public LocalCSRef(MgCoordinateSystem cs) { _cs = cs; }