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 CheckSelectionState() { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); btnListSelected.Enabled = (layers != null); }
/// <summary> /// Установка зумирования и активной выборки (запуск через командную строку - отсюда название) /// </summary> /// <param name="sel_base">выборка, которую следует отобразить</param> internal static void ThroughAssZoomAndSelection(MgSelectionBase sel_base) { internal_saved_selection = AcMapFeatureEntityService.AddFeaturesToSelectionSet(null, sel_base); // преобразование в SelectionSet и обратно, sel_base = AcMapFeatureEntityService.GetSelection(internal_saved_selection); // иначе дает сбой метод GetSelectedFeatures() MgEnvelope extents = new MgEnvelope(); MgReadOnlyLayerCollection layers = sel_base.GetLayers(); foreach (MgLayerBase layer in layers) { MgFeatureReader ftr_reader = sel_base.GetSelectedFeatures(layer, layer.FeatureClassName, false); string geom_prop_name = ftr_reader.GetClassDefinition().DefaultGeometryPropertyName; while (ftr_reader.ReadNext()) { MgByteReader byte_reader = ftr_reader.GetGeometry(geom_prop_name); MgAgfReaderWriter agf_reader_writer = new MgAgfReaderWriter(); MgGeometry curr_geom = agf_reader_writer.Read(byte_reader); extents.ExpandToInclude(curr_geom.Envelope()); } } // зумирование и вызов функции выбора через командную строку Core.no_handle_selection = true; // чтобы изменение выборки не обрабатывалось string zoom_str; if ((extents.Width == 0) && (extents.Width == extents.Height)) { zoom_str = "'_zoom _c " + extents.LowerLeftCoordinate.X.ToString() + "," + extents.LowerLeftCoordinate.Y.ToString() + " "; } else { zoom_str = "'_zoom _w " + (extents.LowerLeftCoordinate.X - extents.Width / 2).ToString() + "," + (extents.LowerLeftCoordinate.Y - extents.Height / 2).ToString() + " " + (extents.UpperRightCoordinate.X + extents.Width / 2).ToString() + "," + (extents.UpperRightCoordinate.Y + extents.Height / 2).ToString(); } Core.SendStringToExecute(zoom_str + "\n" + "ThroughAssZoomAndSelectionHelperFunction\n" , true, false, false); }
private void CheckSelectionState() { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null) { btnClearSelection.Enabled = true; } else { btnClearSelection.Enabled = false; } }
private void mgMapViewer1_SelectionChanged(object sender, EventArgs e) { MgSelectionBase selection = mgMapViewer1.GetSelection(); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null) { for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase layer = layers.GetItem(i); if (layer.Name == "Parcels") //The selected layer is parcels { //Check that we only have one selected object int count = selection.GetSelectedFeaturesCount(layer, layer.FeatureClassName); if (count == 1) { MgFeatureReader reader = null; try { reader = selection.GetSelectedFeatures(layer, layer.FeatureClassName, false); if (reader.ReadNext()) { //Address is in the RPROPAD property if (reader.IsNull("RPROPAD")) { MessageBox.Show("Selected parcel has no address"); } else { MessageBox.Show("Address: " + reader.GetString("RPROPAD")); } } } finally //Must close all readers, otherwise connections will leak { reader.Close(); } } else { MessageBox.Show("Please select only one parcel"); } break; } } } }
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(); } } } }
} //method internal static void SelectionToDataGridView(MgSelectionBase _selection_base) { palette_window.links_control.is_suspended = true; // информируем о заморозке palette_window.links_control.SuspendLayout(); // замораживаем логику palette_window.links_control.data_grid.Enabled = false; palette_window.links_control.data_grid.SuspendLayout(); // замораживаем логику DataGridView palette_window.links_control.layers_list.Enabled = false; palette_window.links_control.progressbar_in_status.Visible = true; // включение ProgressBar palette_window.links_control.status_strip.Refresh(); MgReadOnlyLayerCollection layers = _selection_base.GetLayers(); int curr_features_count = 0, features_count = 0; // подсчет количества выбранных объектов foreach (MgLayerBase layer in layers) { features_count += _selection_base.GetSelectedFeaturesCount(layer, layer.FeatureClassName); } if (features_count == 0) { return; } // заполнение списка слоев palette_window.links_control.layers_list.Items.Clear(); // очищаем список if (layers.Count > 1) { palette_window.links_control.layers_list.Items.Add("(Все выбранные)"); } foreach (MgLayerBase layer in layers) { palette_window.links_control.layers_list.Items.Add(layer.Name); } palette_window.links_control.layers_list.SelectedIndex = 0; // заполнение DataGridView palette_window.links_control.data_grid.Rows.Clear(); // очищаем строки foreach (MgLayerBase layer in layers) { int curr_ftr_class_idx = config.IndexOf(layer.FeatureClassName); if (curr_ftr_class_idx == -1) { curr_features_count += _selection_base.GetSelectedFeaturesCount(layer, layer.FeatureClassName);; palette_window.links_control.UpdateStatusRowCounterLabelAndProgressBar(curr_features_count, features_count); continue; } FeatureClassLinkInfo curr_link_info = config.link_info_array[curr_ftr_class_idx]; MgFeatureReader ftr_rdr = _selection_base.GetSelectedFeatures(layer, layer.FeatureClassName, false); MgPropertyDefinitionCollection identity_prop_defs = ftr_rdr.GetClassDefinition().GetIdentityProperties(); // получаем набор идентификационных полей while (ftr_rdr.ReadNext()) { curr_features_count++; DataGridViewRow link_row = new DataGridViewRow(); // новая строка DataGridViewLinkCell link_cell; // ячейка // формирование URL link_cell = new DataGridViewLinkCell(); string title_str = ResolveLinkStringByValueFromReader(ftr_rdr, curr_link_info.LinkTitle); link_cell.Value = String.IsNullOrEmpty(title_str)? "<Null>": title_str; link_cell.ToolTipText = curr_link_info.LinkCommandPath + command_splitter + ResolveLinkStringByValueFromReader(ftr_rdr, curr_link_info.LinkURL); link_row.Cells.Add(link_cell); // вставка ячейки // формирование ID MgPropertyCollection curr_identity_props = GetPropertiesFromReader(ftr_rdr, identity_prop_defs); SelectedFeatureInfo sel_info = new SelectedFeatureInfo(layer, curr_identity_props); link_cell = new DataGridViewLinkCell(); link_cell.Value = sel_info; link_row.Cells.Add(link_cell); // вставка ячейки // добавлени строки в DataGridView palette_window.links_control.data_grid.Rows.Add(link_row); // обновление ProgressBar'а и счетчика строк palette_window.links_control.UpdateStatusRowCounterLabelAndProgressBar(curr_features_count, features_count); } /// while (ftr_rdr.ReadNext()) } /// foreach (MgLayerBase layer in layers) palette_window.links_control.URL.SortMode = DataGridViewColumnSortMode.NotSortable; // сброс сортировки palette_window.links_control.URL.SortMode = DataGridViewColumnSortMode.Automatic; // на исходную автоматическую palette_window.links_control.data_grid.SelectAll(); // выбираем все строки palette_window.links_control.progressbar_in_status.Visible = false; palette_window.links_control.layers_list.Enabled = true; palette_window.links_control.data_grid.Enabled = true; palette_window.links_control.data_grid.ResumeLayout(); // размораживаем логику DataGridView palette_window.links_control.ResumeLayout(); // размораживаем логику palette_window.links_control.is_suspended = false; palette_window.links_control.UpdateStatusRowCounterLabel(); // обновляем строку статуса }
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)); } }