private void btnQueryDistrict1_Click(object sender, EventArgs e) { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerBase districts = layers.GetItem("Districts"); MgLayerBase parcels = layers.GetItem("Parcels"); //Query the geometry of district 1 MgFeatureQueryOptions districtQuery = new MgFeatureQueryOptions(); districtQuery.SetFilter("Autogenerated_SDF_ID = 1"); MgFeatureReader reader = districts.SelectFeatures(districtQuery); MgGeometry districtGeom = null; MgAgfReaderWriter agfRw = new MgAgfReaderWriter(); try { reader.ReadNext(); MgByteReader geomAgf = reader.GetGeometry(districts.GetFeatureGeometryName()); districtGeom = agfRw.Read(geomAgf); } finally { reader.Close(); } //Now use this geometry as the basis of our 2nd query MgFeatureQueryOptions parcelQuery = new MgFeatureQueryOptions(); parcelQuery.SetFilter("RNAME LIKE 'SCHMITT%'"); parcelQuery.SetSpatialFilter(parcels.GetFeatureGeometryName(), districtGeom, MgFeatureSpatialOperations.Inside); //Select the features reader = parcels.SelectFeatures(parcelQuery); List <string> results = new List <string>(); try { while (reader.ReadNext()) { if (!reader.IsNull("RPROPAD")) { results.Add(reader.GetString("RPROPAD")); } } } finally { reader.Close(); } new ParcelQueryResultWindow(results).ShowDialog(); }
internal RedlineLayer[] GetAvailableLayers(MgMapBase map) { var fsId = GetRegistryFeatureSource(); MgLayerCollection mapLayers = map.GetLayers(); List <RedlineLayer> layers = new List <RedlineLayer>(); MgFeatureReader reader = null; try { reader = _featSvc.SelectFeatures(fsId, "Default:MarkupRegistry", null); while (reader.ReadNext()) { layers.Add(new RedlineLayer(reader.GetString("Name"), reader.GetString("ResourceId"), reader.GetString("LayerDefinition"), reader.GetInt32("GeometryTypes"), (RedlineStylizationType)reader.GetInt32("StyleType"))); } } finally { if (reader != null) { reader.Close(); } } return(layers.ToArray()); }
protected override IFeature ReadNextFeature() { if (_reader.ReadNext()) { return(new LocalNativeFeature(_reader, _mgReader, _agfRw, _wktRw)); } return(null); }
private void btnSelectDistrict1_Click(object sender, EventArgs e) { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerBase districts = layers.GetItem("Districts"); MgLayerBase parcels = layers.GetItem("Parcels"); //Query the geometry of district 1 MgFeatureQueryOptions districtQuery = new MgFeatureQueryOptions(); districtQuery.SetFilter("Autogenerated_SDF_ID = 1"); MgFeatureReader reader = districts.SelectFeatures(districtQuery); MgGeometry districtGeom = null; MgAgfReaderWriter agfRw = new MgAgfReaderWriter(); try { reader.ReadNext(); MgByteReader geomAgf = reader.GetGeometry(districts.GetFeatureGeometryName()); districtGeom = agfRw.Read(geomAgf); } finally { reader.Close(); } //Now use this geometry as the basis of our 2nd query MgFeatureQueryOptions parcelQuery = new MgFeatureQueryOptions(); parcelQuery.SetFilter("RNAME LIKE 'SCHMITT%'"); parcelQuery.SetSpatialFilter(parcels.GetFeatureGeometryName(), districtGeom, MgFeatureSpatialOperations.Inside); //Select the features reader = parcels.SelectFeatures(parcelQuery); MgSelectionBase selection = _viewer.GetSelection(); try { selection.FromXml(""); //Clear existing selection data selection.AddFeatures(parcels, reader, 0); } finally { reader.Close(); } //Because we manipulated the active selection outside the viewer //We need to call UpdateSelection() to instruct the viewer to //re-render the active selection. The "true" parameter instructs //the viewer to raise the SelectionChanged event as well, so that //subscribers like the Property Pane get updated as well. _viewer.UpdateSelection(true); _viewer.RefreshMap(); }
/// <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 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; } } } }
public void LoadResults(MgLayerBase layer, MgFeatureQueryOptions query) { MgClassDefinition clsDef = layer.GetClassDefinition(); MgPropertyDefinitionCollection idProps = clsDef.GetIdentityProperties(); MgPropertyDefinition idProp = idProps[0]; string idPropName = idProp.Name; string geomName = layer.FeatureGeometryName; MgFeatureReader reader = layer.SelectFeatures(query); MgAgfReaderWriter agfRw = new MgAgfReaderWriter(); try { while (reader.ReadNext()) { var res = new ParcelFeatureModel(); res.ID = reader.GetInt32(idPropName); res.Owner = reader.IsNull("RNAME") ? "(unknown)" : reader.GetString("RNAME"); res.Address = reader.IsNull("RPROPAD") ? "(unknown)" : reader.GetString("RPROPAD"); if (!reader.IsNull(geomName)) { MgByteReader agf = reader.GetGeometry(geomName); MgGeometry geom = agfRw.Read(agf); MgPoint center = geom.Centroid; MgCoordinate coord = center.Coordinate; res.X = coord.X; res.Y = coord.Y; } this.Results.Add(res); } } finally { reader.Close(); } }
public IEnumerable <RedlineObject> GetAllFeatures() { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerBase redlineLayer = layers.GetItem(_layer.SystemName); MgResourceIdentifier resId = new MgResourceIdentifier(redlineLayer.GetFeatureSourceId()); MgFeatureReader reader = null; try { reader = _featSvc.SelectFeatures(resId, RedlineSchemaFactory.CLASS_NAME, null); //HACK: Another leaky abstraction. SHP will always choose FeatId, so once again //use the class definition to determine the identity property name MgClassDefinition cls = reader.GetClassDefinition(); MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties(); MgPropertyDefinition keyProp = idProps.GetItem(0); string idName = keyProp.GetName(); while (reader.ReadNext()) { int id = reader.GetInt32(idName); string text = reader.IsNull(RedlineSchemaFactory.TEXT_NAME) ? string.Empty : reader.GetString(RedlineSchemaFactory.TEXT_NAME); yield return(new RedlineObject(id, text)); } } finally { if (reader != null) { reader.Close(); } } }
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(); // обновляем строку статуса }
private void SetPropertyMinMaxCount(MgLayerBase layer, MgDataPropertyDefinition prop) { var provider = _viewer.GetProvider(); var featureService = (MgFeatureService)provider.CreateService(MgServiceType.FeatureService); MgResourceIdentifier resId = new MgResourceIdentifier(layer.GetFeatureSourceId()); String minValue = null; String maxValue = null; int count = 0; MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions(); queryOptions.AddFeatureProperty(prop.Name); MgFeatureReader featureReader = featureService.SelectFeatures(resId, layer.GetFeatureClassName(), queryOptions); Dictionary <string, string> bucket = new Dictionary <string, string>(); while (featureReader.ReadNext()) { String value = Util.GetFeaturePropertyValue(featureReader, prop.Name); bucket[value] = value; int propertyType = featureReader.GetPropertyType(prop.Name); if (count == 0) { maxValue = value; minValue = value; } switch (propertyType) { case MgPropertyType.String: if (value.Length > 0) { if (value.CompareTo(maxValue) > 0) { maxValue = value; } if (value.CompareTo(minValue) < 0) { minValue = value; } } break; case MgPropertyType.Byte: case MgPropertyType.Int16: case MgPropertyType.Int32: case MgPropertyType.Int64: if (value.Length > 0) { if (Int64.Parse(value) > Int64.Parse(maxValue)) { maxValue = value; } if (Int64.Parse(value) < Int64.Parse(minValue)) { minValue = value; } } break; case MgPropertyType.Single: case MgPropertyType.Double: if (value != null) { if (Double.Parse(value) > Double.Parse(maxValue)) { maxValue = value; } if (Double.Parse(value) < Double.Parse(minValue)) { minValue = value; } } count++; break; case MgPropertyType.Boolean: case MgPropertyType.DateTime: case MgPropertyType.Null: case MgPropertyType.Blob: case MgPropertyType.Clob: case MgPropertyType.Feature: case MgPropertyType.Geometry: break; } count++; } featureReader.Close(); txtMin.Text = minValue; txtMax.Text = maxValue; if (THEME_INDIVIDUAL == cmbDistribution.SelectedValue.ToString()) { count = bucket.Count; } numRules.Value = featureCount = count; }
//--------------------------------------------------------------------------------------- // // ���ܣ�GetPropertyType()������GetPropertyName()������ʹ�� // // ���ߣ� // // ���ڣ� 2007.5.23 // // ����ʷ���� // //--------------------------------------------------------------------------------------- public void OutputReader(MgFeatureReader featureReader) { while (featureReader.ReadNext()) { int propCount = featureReader.GetPropertyCount(); for (int j = 0; j < propCount; j++) { string propertyName = featureReader.GetPropertyName(j); bool boolVal = featureReader.IsNull(propertyName); if (boolVal) { continue; } //MgPropertyType propertyType = (MgPropertyType)featureReader.GetPropertyType(propertyName); int proType = featureReader.GetPropertyType(propertyName); GetPropertyValue(featureReader, proType, propertyName); } } }
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; } }
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)); } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string sessionId = GetRequestParameters(Request)["SESSION"]; string mapName = GetRequestParameters(Request)["MAPNAME"]; string locale = GetRequestParameters(Request)["LOCALE"]; if (string.IsNullOrEmpty(sessionId)) { Response.Clear(); Response.End(); return; } if (string.IsNullOrEmpty(mapName)) { Response.Clear(); Response.End(); return; } MgResourceService resourceSrvc = GetMgResurceService(sessionId); MgFeatureService featureSrvc = GetMgFeatureService(sessionId); MgMap map = new MgMap(); map.Open(resourceSrvc, mapName); string layernames = GetRequestParameters(Request)["LAYERNAMES"]; string GEOMETRY = GetRequestParameters(Request)["GEOMETRY"]; string selVar = GetRequestParameters(Request)["SELECTIONVARIANT"]; string type = GetRequestParameters(Request)["tp"]; string inputSel = GetRequestParameters(Request)["SELECTION"]; bool hasInputGeom = false; if (!string.IsNullOrEmpty(GEOMETRY)) { hasInputGeom = true; } //selection ima prednost pred podano geometrijo ... MgWktReaderWriter wktrw = new MgWktReaderWriter(); if (!string.IsNullOrEmpty(inputSel)) { MgGeometry inputGeom = MultiGeometryFromSelection(featureSrvc, map, inputSel); GEOMETRY = wktrw.Write(inputGeom); } MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); int nLayer = 0; // pobrišem in zgradim na novo samo tiste, ki imajo zadetke ... int nSloj = 0; string filter = ""; StringBuilder sbOut = new StringBuilder(); sbOut.Append("<table width=\"100%\" class=\"results\">"); sbOut.Append("<tr><td class='header'></td><td class='header'>" + "Layer" + "</td><td class='header' align=\"center\">" + "Select" + "</td><td class='header' align=\"center\">" + "Report" + "</td></tr>"); MgSelection selAll = new MgSelection(map); foreach (MgLayer layer in map.GetLayers()) { if (type != "2") { if (!layer.IsVisible()) { goto nextlay; } } if (layer.LegendLabel == "") { goto nextlay; } try { nLayer++; filter = String.Format("{0} {1} GeomFromText('{2}')", layer.GetFeatureGeometryName(), selVar, GEOMETRY); //preveriti še filter na Layerju. Ker ne gre drugače, je potrebno pogledati v XML MgResourceIdentifier layerDefResId = layer.GetLayerDefinition(); MgByteReader byteReader = resourceSrvc.GetResourceContent(layerDefResId); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); String xmlLayerDef = byteReader.ToString(); doc.LoadXml(xmlLayerDef); KALI.MGE.Objects.KALILayerDefinition.LayerDefinition ld = KALI.MGE.Objects.KALILayerDefinition.LayerDefinition.Parse(xmlLayerDef); if (!string.IsNullOrEmpty(ld.VectorLayerDefinition.Filter)) { filter += " AND (" + ld.VectorLayerDefinition.Filter + ")"; } //query the features MgFeatureQueryOptions opts = new MgFeatureQueryOptions(); opts.SetFilter(filter); String featureClassName = layer.GetFeatureClassName(); MgResourceIdentifier srcId = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureReader features = featureSrvc.SelectFeatures(srcId, featureClassName, opts); bool hasResult = features.ReadNext(); if (hasResult) { nSloj++; int n = 0; MgClassDefinition classDef = features.GetClassDefinition(); MgPropertyDefinitionCollection classDefProps = classDef.GetIdentityProperties(); ArrayList idPropNames = new ArrayList(classDefProps.GetCount()); for (int j = 0; j < classDefProps.GetCount(); j++) { MgPropertyDefinition idProp = classDefProps.GetItem(j); idPropNames.Add(idProp.GetName()); } MgSelection sel = new MgSelection(map); do { // Generate XML to selection this feature MgPropertyCollection idProps = new MgPropertyCollection(); foreach (string id in idPropNames) { int idPropType = features.GetPropertyType(id); switch (idPropType) { case MgPropertyType.Int32: idProps.Add(new MgInt32Property(id, features.GetInt32(id))); break; case MgPropertyType.String: idProps.Add(new MgStringProperty(id, features.GetString(id))); break; case MgPropertyType.Int64: idProps.Add(new MgInt64Property(id, features.GetInt64(id))); break; case MgPropertyType.Double: idProps.Add(new MgDoubleProperty(id, features.GetDouble(id))); break; case MgPropertyType.Single: idProps.Add(new MgSingleProperty(id, features.GetSingle(id))); break; case MgPropertyType.DateTime: idProps.Add(new MgDateTimeProperty(id, features.GetDateTime(id))); break; default: //throw new SearchError(String.Format(MgLocalizer.GetString("SEARCHTYYPENOTSUP", locale), new Object[] { idPropType.ToString() }), searchError); break; } } sel.AddFeatureIds(layer, featureClassName, idProps); selAll.AddFeatureIds(layer, featureClassName, idProps); n++; //if (n > 1000) break; } while (features.ReadNext()); features.Close(); features.Dispose(); string selText = EscapeForHtml(sel.ToXml()); string seljs = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/></div>"; string seljs3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/></div>"; string linfo = "<b>" + layer.LegendLabel + "</b><br />" + n.ToString() + " " + "Hits"; sbOut.Append("<tr><td class=\"results\">" + nSloj.ToString() + "</td><td class=\"results\">" + linfo + "</td><td align=\"center\" class=\"results\">" + seljs + "</td><td align=\"center\" class=\"results\">" + seljs3 + "</td></tr>"); } } catch (Exception) { continue; } nextlay: continue; } sbOut.Append("</table>"); string selAllText = EscapeForHtml(selAll.ToXml()); string seljsAll = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/>" + "Select All" + "</div>"; string seljsAll3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/>" + "Report All" + "</div>"; sbOut.Append(string.Format("<br /><table width=\"100%\" class=\"results\"><tr><td class=\"results\">{0}</td><td class=\"results\">{1}</td></tr></table>", seljsAll, seljsAll3)); featureSrvc.Dispose(); resourceSrvc.Dispose(); if (nSloj > 0) { litPrebodi.Text = sbOut.ToString(); } else { litPrebodiTitle.Visible = false; litPrebodi.Text = "<b>" + "None layer lies below the selected item/area!" + "</b>"; } MgGeometry inGeom = wktrw.Read(GEOMETRY); double rw = map.ViewScale / Math.Sqrt(inGeom.Area); //koordinate if (hasInputGeom & rw > 400) { string output = ""; output = pointTransformAndWriteZ(GEOMETRY, map); litKoordinate.Text = output; litKoordinateTitle.Text = "Coordinates of selected points:"; } } }