private void btnFindFeaturesInBuffer_Click(object sender, EventArgs e) { MgSelectionBase selection = _viewer.GetSelection(); MgReadOnlyLayerCollection selectedLayers = selection.GetLayers(); if (selectedLayers == null) { MessageBox.Show("Select a parcel"); return; } MgLayerBase parcels = null; for (int i = 0; i < selectedLayers.GetCount(); i++) { MgLayerBase layer = selectedLayers.GetItem(i); if (layer.Name == "Parcels") { parcels = layer; break; } } if (parcels == null) { MessageBox.Show("Select a parcel"); return; } int bufferRingSize = 500; // measured in metres // Set up some objects for coordinate conversion MgMapBase map = _viewer.GetMap(); MgLayerCollection mapLayers = map.GetLayers(); MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //Casting to MgdFeatureService because we want to use convenience APIs MgFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); string sessionId = Guid.NewGuid().ToString(); String mapWktSrs = map.GetMapSRS(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgCoordinateSystemFactory coordinateSystemFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem srs = coordinateSystemFactory.Create(mapWktSrs); MgMeasure srsMeasure = srs.GetMeasure(); // Check for a buffer layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the buffer. BufferHelper helper = new BufferHelper(); MgdLayer bufferLayer = null; int layerIndex = map.GetLayers().IndexOf("Buffer"); if (layerIndex < 0) { // The layer does not exist and must be created. MgResourceIdentifier bufferFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//Buffer.FeatureSource"); helper.CreateBufferFeatureSource(featureService, mapWktSrs, bufferFeatureResId); bufferLayer = helper.CreateBufferLayer(resourceService, bufferFeatureResId, sessionId); map.GetLayers().Insert(0, bufferLayer); } else { bufferLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); bufferLayer.DeleteFeatures("ID like '%'"); } // Check for a parcel marker layer. If it exists, delete // the current features. // If it does not exist, create a feature source and // a layer to hold the parcel markers. MgdLayer parcelMarkerLayer = null; layerIndex = map.GetLayers().IndexOf("ParcelMarker"); if (layerIndex < 0) { MgResourceIdentifier parcelFeatureResId = new MgResourceIdentifier("Session:" + sessionId + "//ParcelMarker.FeatureSource"); helper.CreateParcelMarkerFeatureSource(featureService, mapWktSrs, parcelFeatureResId); parcelMarkerLayer = helper.CreateParcelMarkerLayer(resourceService, parcelFeatureResId, sessionId); map.GetLayers().Insert(0, parcelMarkerLayer); } else { parcelMarkerLayer = (MgdLayer)map.GetLayers().GetItem(layerIndex); parcelMarkerLayer.DeleteFeatures("ID like '%'"); } // Check each layer in the selection. for (int i = 0; i < selectedLayers.GetCount(); i++) { // Only check selected features in the Parcels layer. MgdLayer layer = (MgdLayer)selectedLayers.GetItem(i); if (layer.GetName() == "Parcels") { string geomName = layer.GetFeatureGeometryName(); System.Diagnostics.Trace.TraceInformation("Marking all parcels inside the buffer that are of type 'MFG'"); MgFeatureReader featureReader = selection.GetSelectedFeatures(layer, layer.GetFeatureClassName(), false); // Process each item in the MgFeatureReader. Get the // geometries from all the selected features and // merge them into a single geometry. MgGeometryCollection inputGeometries = new MgGeometryCollection(); while (featureReader.ReadNext()) { MgByteReader featureGeometryData = featureReader.GetGeometry(geomName); MgGeometry featureGeometry = agfReaderWriter.Read(featureGeometryData); inputGeometries.Add(featureGeometry); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgGeometry mergedGeometries = geometryFactory.CreateMultiGeometry(inputGeometries); // Create a buffer from the merged geometries double bufferDist = srs.ConvertMetersToCoordinateSystemUnits(bufferRingSize); MgGeometry bufferGeometry = mergedGeometries.Buffer(bufferDist, srsMeasure); // Create a filter to select parcels within the buffer. Combine // a basic filter and a spatial filter to select all parcels // within the buffer that are of type "MFG". MgFeatureQueryOptions queryOptions = new MgFeatureQueryOptions(); queryOptions.SetFilter("RTYPE = 'MFG'"); queryOptions.SetSpatialFilter(geomName, bufferGeometry, MgFeatureSpatialOperations.Inside); featureReader = layer.SelectFeatures(queryOptions); // Get the features from the feature source, // determine the centroid of each selected feature, and // add a point to the ParcelMarker layer to mark the // centroid. // Collect all the points into an MgFeatureCommandCollection, // so they can all be added in one operation. MgFeatureCommandCollection parcelMarkerCommands = new MgFeatureCommandCollection(); int inserted = 0; while (featureReader.ReadNext()) { MgByteReader byteReader = featureReader.GetGeometry(geomName); MgGeometry geometry = agfReaderWriter.Read(byteReader); MgPoint point = geometry.GetCentroid(); // Create an insert command for this parcel. MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgGeometryProperty("ParcelLocation", agfReaderWriter.Write(point))); //parcelMarkerCommands.Add(new MgInsertFeatures("ParcelMarkerClass", properties)); MgFeatureReader fr = parcelMarkerLayer.InsertFeatures(properties); fr.Close(); inserted++; } featureReader.Close(); if (inserted == 0) { MessageBox.Show("No parcels within the buffer area match."); return; } // Create a feature in the buffer feature source to show the area covered by the buffer. MgPropertyCollection props = new MgPropertyCollection(); props.Add(new MgGeometryProperty("BufferGeometry", agfReaderWriter.Write(bufferGeometry))); bufferLayer.InsertFeatures(props); // Ensure that the buffer layer is visible and in the legend. bufferLayer.SetVisible(true); bufferLayer.ForceRefresh(); bufferLayer.SetDisplayInLegend(true); parcelMarkerLayer.SetVisible(true); parcelMarkerLayer.ForceRefresh(); MessageBox.Show("Done"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } } }
private 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 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; } }