private void AddRedlineLayerToMap(MgResourceIdentifier ldfId) { MgLayerGroup group = null; var layers = _map.GetLayers(); var groups = _map.GetLayerGroups(); if (groups.Contains(GROUP_NAME)) { group = groups.GetItem(GROUP_NAME); } else { group = new MgLayerGroup(GROUP_NAME); group.SetVisible(true); group.SetLegendLabel(Strings.RedlineLayerGroupLabel); group.SetDisplayInLegend(true); groups.Add(group); } var provider = _viewer.GetProvider(); var newLayer = provider.CreateLayer(ldfId); newLayer.SetDisplayInLegend(true); newLayer.SetName("_" + ldfId.Name); newLayer.SetLegendLabel(ldfId.Name); newLayer.SetSelectable(true); newLayer.SetGroup(group); layers.Insert(0, newLayer); }
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()); }
private void btnLayerVisibility_Click(object sender, EventArgs e) { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); new LayerVisibilityDialog(layers).ShowDialog(); }
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(); }
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(); }
protected MgLayerBase FindLayer(string name) { if (_map != null) { var layers = _map.GetLayers(); var lidx = layers.IndexOf(name); if (lidx >= 0) { return(layers.GetItem(lidx)); } } return(null); }
public static String MakeUniqueLayerName(MgMapBase map, String layerName, String themeName) { String desiredName = "_" + layerName + themeName; //NOXLATE String uniqueName = desiredName; int index = 1; var layers = map.GetLayers(); while (layers.Contains(uniqueName)) { uniqueName = desiredName + index.ToString(); index++; } return(uniqueName); }
private void btnListLayers_Click(object sender, EventArgs e) { MgMapBase map = _viewer.GetMap(); MgResourceIdentifier resId = map.MapDefinition; MgLayerCollection layers = map.GetLayers(); List <string> results = new List <string>(); for (int i = 0; i < layers.GetCount(); i++) { MgLayerBase layer = layers.GetItem(i); results.Add(layer.Name + " (" + layer.LegendLabel + ")"); } MessageBox.Show("Map (" + resId.ToString() + ") has " + layers.GetCount() + " layers: " + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, results.ToArray())); }
public InteractingWithLayers(IMapViewer viewer) { InitializeComponent(); _viewer = viewer; this.Title = "Interacting With Layers"; MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); if (layers.IndexOf("Roads") >= 0 && layers.IndexOf("Streets") < 0) { btnRenameRoadsLayer.Text = "Rename Roads Layer to Streets"; } else if (layers.IndexOf("Roads") < 0 && layers.IndexOf("Streets") >= 0) { btnRenameRoadsLayer.Text = "Rename Streets Layer to Roads"; } }
private void btnRefreshLayersOnMap_Click(object sender, EventArgs e) { lstLayersOnMap.Clear(); var mgr = GetRedlineManager(); MgMapBase map = _component.Viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); foreach (var layer in mgr.GetAvailableLayers()) { //Omit those not on the map if (layers.IndexOf(layer.SystemName) < 0) { continue; } AddRedlineLayerOnMap(layer); } }
public DigitizingAndRedlining(IMapViewer viewer) { InitializeComponent(); _viewer = viewer; _geomFact = new MgGeometryFactory(); _wktRW = new MgWktReaderWriter(); _agfRW = new MgAgfReaderWriter(); this.Title = "Digitizing and Redlining"; _viewer.PropertyChanged += OnViewerPropertyChanged; MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); if (layers.IndexOf("Redline") >= 0) { _redlineLayer = (MgdLayer)layers.GetItem("Redline"); } CheckDigitizingState(); }
internal void UpdateRedlineText(string text, int[] ids) { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerBase redlineLayer = layers.GetItem(_layer.SystemName); //HACK: Workaround FeatId leaky abstraction in SHP provider MgClassDefinition cls = redlineLayer.GetClassDefinition(); MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties(); MgPropertyDefinition idProp = idProps.GetItem(0); redlineLayer.ForceRefresh(); //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us //Gotta go the old verbose route List <string> filters = new List <string>(); foreach (int id in ids) { filters.Add(idProp.Name + " = " + id); } string updateFilter = string.Join(" OR ", filters.ToArray()); MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); MgPropertyCollection updateValues = new MgPropertyCollection(); MgStringProperty updateProp = new MgStringProperty(RedlineSchemaFactory.TEXT_NAME, text); updateValues.Add(updateProp); MgUpdateFeatures update = new MgUpdateFeatures(redlineLayer.FeatureClassName, updateValues, updateFilter); commands.Add(update); MgPropertyCollection result = redlineLayer.UpdateFeatures(commands); MgInt32Property updateResult = result.GetItem(0) as MgInt32Property; MgStringProperty errorResult = result.GetItem(0) as MgStringProperty; if (errorResult != null) { throw new Exception(errorResult.GetValue()); } _viewer.RefreshMap(); }
private void btnRenameRoadsLayer_Click(object sender, EventArgs e) { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); bool bRefresh = false; if (layers.IndexOf("Roads") >= 0) { MgLayerBase roads = layers.GetItem("Roads"); roads.Name = "Streets"; roads.LegendLabel = "Streets"; MessageBox.Show("Layer (Roads) has been changed to (Streets)"); btnRenameRoadsLayer.Text = "Rename Streets Layer to Roads"; bRefresh = true; } else if (layers.IndexOf("Streets") >= 0) { MgLayerBase streets = layers.GetItem("Streets"); streets.Name = "Roads"; streets.LegendLabel = "Roads"; MessageBox.Show("Layer (Streets) has been changed to (Roads)"); btnRenameRoadsLayer.Text = "Rename Roads Layer to Streets"; bRefresh = true; } if (bRefresh) { _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } }
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(); } } }
internal void DeleteRedlines(int[] ids) { MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerBase redlineLayer = layers.GetItem(_layer.SystemName); //HACK: Workaround FeatId leaky abstraction in SHP provider MgClassDefinition cls = redlineLayer.GetClassDefinition(); MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties(); MgPropertyDefinition idProp = idProps.GetItem(0); redlineLayer.ForceRefresh(); //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us //Gotta go the old verbose route List <string> filters = new List <string>(); foreach (int id in ids) { filters.Add(idProp.Name + " = " + id); } string deleteFilter = string.Join(" OR ", filters.ToArray()); MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); MgDeleteFeatures delete = new MgDeleteFeatures(redlineLayer.FeatureClassName, deleteFilter); commands.Add(delete); MgPropertyCollection result = redlineLayer.UpdateFeatures(commands); MgInt32Property deleteResult = result.GetItem(0) as MgInt32Property; if (deleteResult != null && deleteResult.GetValue() > 0) { _viewer.RefreshMap(); } }
private void btnShowBuildings_Click(object sender, EventArgs e) { MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); string layerName = "RecentlyBuilt"; string legendLabel = "Built after 1980"; string groupName = "Analysis"; MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerGroupCollection groups = map.GetLayerGroups(); if (layers.IndexOf(layerName) >= 0) { MessageBox.Show("Layer (" + layerName + ") already created"); return; } //NOTE: mg-desktop has no formal concept of a session repository, but we still //support session-based resources as a form of temporary resource (for the duration //of the application). Session ids in mg-desktop can be any arbitrary string string sessionId = Guid.NewGuid().ToString(); XmlDocument domDocument = new XmlDocument(); domDocument.LoadXml(Layers.RecentlyBuilt); // Get a list of all the <AreaRule><Filter> elements in // the XML. XmlNodeList nodes = domDocument.SelectNodes("//AreaRule/Filter"); // Find the correct node and change it foreach (XmlNode node in nodes) { if (node.InnerText == "YRBUILT > 1950") { node.InnerText = "YRBUILT > 1980"; } } // Get a list of all the <LegendLabel> elements in the // XML. nodes = domDocument.SelectNodes("//LegendLabel"); // Find the correct node and change it foreach (XmlNode node in nodes) { if (node.InnerText == "Built after 1950") { node.InnerText = "Built after 1980"; } } //Add the layer to the map // TODO: Should probably validate this XML content using (MemoryStream ms = new MemoryStream()) { domDocument.Save(ms); ms.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] layerDefinition = ms.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(layerDefinition)); layerDefinition = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(layerDefinition, layerDefinition.Length); MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition"); resourceService.SetResource(resourceID, byteSource.GetReader(), null); //Insert this layer to our map MgdLayer newLayer = new MgdLayer(resourceID, resourceService); newLayer.Name = layerName; newLayer.LegendLabel = legendLabel; newLayer.DisplayInLegend = true; newLayer.SetVisible(true); layers.Insert(0, newLayer); //Create analysis group if not already created if (groups.IndexOf(groupName) < 0) { MgLayerGroup group = new MgLayerGroup(groupName); group.LegendLabel = groupName; group.DisplayInLegend = true; groups.Add(group); newLayer.Group = group; } //Turn off square footage if it exists if (layers.IndexOf("SquareFootage") >= 0) { MgLayerBase layer = layers.GetItem("SquareFootage"); layer.SetVisible(false); } MessageBox.Show("Layer (" + layerName + ") created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } }
private void InsertRedlineGeometry(string text, MgGeometry geom, RedlineAction onRedlineAdded) { MgPropertyCollection feature = new MgPropertyCollection(); MgByteReader agf = _agfRW.Write(geom); MgGeometryProperty geomProp = new MgGeometryProperty(RedlineSchemaFactory.GEOM_NAME, agf); feature.Add(geomProp); MgStringProperty strProp = new MgStringProperty(RedlineSchemaFactory.TEXT_NAME, text); feature.Add(strProp); MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerBase redlineLayer = layers.GetItem(_layer.SystemName); MgClassDefinition cls = redlineLayer.GetClassDefinition(); MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties(); MgPropertyDefinition idProp = idProps.GetItem(0); redlineLayer.ForceRefresh(); //This lib doesn't reference mg-desktop so the convenience APIs aren't available to us //Gotta go the old verbose route MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); MgInsertFeatures insert = new MgInsertFeatures(redlineLayer.FeatureClassName, feature); commands.Add(insert); MgPropertyCollection result = redlineLayer.UpdateFeatures(commands); //Insert result is a MgFeatureProperty containing an MgFeatureReader MgFeatureProperty insertResult = result.GetItem(0) as MgFeatureProperty; MgStringProperty errorResult = result.GetItem(0) as MgStringProperty; if (insertResult != null) { var reader = insertResult.GetValue(); int inserted = 0; int?id = null; try { if (reader.ReadNext()) { inserted++; id = reader.GetInt32(idProp.Name); } } catch (MgException ex) { ex.Dispose(); } finally { reader.Close(); } if (inserted > 0) { _viewer.RefreshMap(); onRedlineAdded(id, text); } } else if (errorResult != null) { throw new Exception(errorResult.GetValue()); } }
public static String MakeUniqueLayerName(MgMapBase map, String layerName, String themeName) { String desiredName = "_" + layerName + themeName; //NOXLATE String uniqueName = desiredName; int index = 1; var layers = map.GetLayers(); while (layers.Contains(uniqueName)) { uniqueName = desiredName + index.ToString(); index++; } return uniqueName; }
private void btnCreateHydroLine_Click(object sender, EventArgs e) { string layerName = "Hydro"; string legendLabel = "Hydro"; string groupName = "Analysis"; MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerGroupCollection groups = map.GetLayerGroups(); //NOTE: mg-desktop has no formal concept of a session repository, but we still //support session-based resources as a form of temporary resource (for the duration //of the application). Session ids in mg-desktop can be any arbitrary string string sessionId = Guid.NewGuid().ToString(); if (layers.IndexOf(layerName) >= 0) { MessageBox.Show("Layer (" + layerName + ") already created"); return; } //---------------------------------------------------// // Create a new layer LayerDefinitionFactory factory = new LayerDefinitionFactory(); // Create a line rule. String ruleLegendLabel = ""; String filter = ""; String color = "FF0000FF"; String lineRule = factory.CreateLineRule(ruleLegendLabel, filter, color); // Create a line type style. String lineTypeStyle = factory.CreateLineTypeStyle(lineRule); // Create a scale range. String minScale = "0"; String maxScale = "1000000000000"; String lineScaleRange = factory.CreateScaleRange(minScale, maxScale, lineTypeStyle); // Create the layer definiton. String featureClass = "Library://Samples/Sheboygan/Data/HydrographicLines.FeatureSource"; String featureName = "SHP_Schema:HydrographicLines"; String geometry = "SHPGEOM"; String layerDefinition = factory.CreateLayerDefinition(featureClass, featureName, geometry, lineScaleRange); //---------------------------------------------------// // ... XmlDocument domDocument = new XmlDocument(); domDocument.LoadXml(layerDefinition); //Add the layer to the map // TODO: Should probably validate this XML content using (MemoryStream ms = new MemoryStream()) { domDocument.Save(ms); ms.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] ldfBytes = ms.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(ldfBytes)); ldfBytes = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(ldfBytes, ldfBytes.Length); MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition"); resourceService.SetResource(resourceID, byteSource.GetReader(), null); //Insert this layer to our map MgdLayer newLayer = new MgdLayer(resourceID, resourceService); newLayer.Name = layerName; newLayer.LegendLabel = legendLabel; newLayer.DisplayInLegend = true; newLayer.SetVisible(true); layers.Insert(0, newLayer); //Create analysis group if not already created if (groups.IndexOf(groupName) < 0) { MgLayerGroup group = new MgLayerGroup(groupName); group.LegendLabel = groupName; group.DisplayInLegend = true; groups.Add(group); newLayer.Group = group; } MessageBox.Show("Layer (" + layerName + ") created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } }
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(); } } } }
private void CreateRedlineLayer() { MgMapBase map = mgMapViewer1.GetMap(); MgdServiceFactory fact = new MgdServiceFactory(); MgdFeatureService featSvc = (MgdFeatureService)fact.CreateService(MgServiceType.FeatureService); MgResourceService resSvc = (MgResourceService)fact.CreateService(MgServiceType.ResourceService); //Note that mg-desktop does not have a concept of sessions like the //official MapGuide API, but it *does* allow session-based resources //as a way of having temporary resources. Such resources will reside //in a special directory for session resources (specified in Platform.ini) // //You can plug whatever string as the session id, but the resource identifier //must satisfy the session id pattern: // // Session:<session id string>//Path/To/Your.ResourceType // //These files are removed with MgPlatform.Terminate(), which is called in this //application as part of the exiting process. string sessionId = Guid.NewGuid().ToString(); MgResourceIdentifier fsId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.FeatureSource"); MgResourceIdentifier ldfId = new MgResourceIdentifier("Session:" + sessionId + "//Redline.LayerDefinition"); //Create our point redline schema. It looks like this: // // Default // Redline // ID (int32, autogenerated) // Geometry (coordinate system same as map string featureClass = "Default:Redline"; string geometry = "Geometry"; MgFeatureSchema schema = new MgFeatureSchema("Default", "Redline schema"); MgClassDefinition cls = new MgClassDefinition(); cls.Name = "Redline"; MgDataPropertyDefinition id = new MgDataPropertyDefinition("ID"); id.DataType = MgPropertyType.Int32; id.SetAutoGeneration(true); MgGeometricPropertyDefinition geom = new MgGeometricPropertyDefinition(geometry); geom.SpatialContextAssociation = "Default"; geom.GeometryTypes = MgFeatureGeometricType.Curve | MgFeatureGeometricType.Point | MgFeatureGeometricType.Solid | MgFeatureGeometricType.Surface; MgPropertyDefinitionCollection clsProps = cls.GetProperties(); clsProps.Add(id); clsProps.Add(geom); MgPropertyDefinitionCollection idProps = cls.GetIdentityProperties(); idProps.Add(id); cls.DefaultGeometryPropertyName = geometry; MgClassDefinitionCollection classes = schema.GetClasses(); classes.Add(cls); //Create the feature source with this schema. We use the map's //coordinate system for the feature source to ensure features //that we create, will line up with the map MgFileFeatureSourceParams create = new MgFileFeatureSourceParams("OSGeo.SDF", "Default", map.GetMapSRS(), schema); featSvc.CreateFeatureSource(fsId, create); //Then create the layer definition. RedlineLayer.xml contains the template string xml = string.Format(File.ReadAllText("RedlineLayer.xml"), fsId.ToString(), featureClass, geometry); var bytes = Encoding.UTF8.GetBytes(xml); MgByteSource source = new MgByteSource(bytes, bytes.Length); resSvc.SetResource(ldfId, source.GetReader(), null); //Now create the runtime layer and add to map _pointLayer = new MgdLayer(ldfId, resSvc); _pointLayer.LegendLabel = "Redlining"; _pointLayer.Name = "Redline"; _pointLayer.Visible = true; _pointLayer.Selectable = true; _pointLayer.DisplayInLegend = true; var layers = map.GetLayers(); layers.Insert(0, _pointLayer); }
private void btnCreatePointsOfInterest_Click(object sender, EventArgs e) { string layerName = "Points"; string legendLabel = "Points of Interest"; string groupName = "Analysis"; MgMapViewerProvider provider = _viewer.GetProvider(); MgResourceService resourceService = (MgResourceService)provider.CreateService(MgServiceType.ResourceService); //We use MgdFeatureService instead of MgFeatureService as this sample demonstrates APIs unique to mg-desktop MgdFeatureService featureService = (MgdFeatureService)provider.CreateService(MgServiceType.FeatureService); MgMapBase map = _viewer.GetMap(); MgLayerCollection layers = map.GetLayers(); MgLayerGroupCollection groups = map.GetLayerGroups(); //NOTE: mg-desktop has no formal concept of a session repository, but we still //support session-based resources as a form of temporary resource (for the duration //of the application). Session ids in mg-desktop can be any arbitrary string string sessionId = Guid.NewGuid().ToString(); if (layers.IndexOf(layerName) >= 0) { MessageBox.Show("Layer (" + layerName + ") already created"); return; } //---------------------------------------------------// // Create a feature source with point data. // (The Sheboygan sample data does not contain such data, // so we"ll create it.) // Create a feature class definition for the new feature source MgClassDefinition classDefinition = new MgClassDefinition(); classDefinition.SetName("Points"); classDefinition.SetDescription("Feature class with point data."); classDefinition.SetDefaultGeometryPropertyName("GEOM"); MgPropertyDefinitionCollection idProps = classDefinition.GetIdentityProperties(); MgPropertyDefinitionCollection clsProps = classDefinition.GetProperties(); // Create an identify property MgDataPropertyDefinition identityProperty = new MgDataPropertyDefinition("KEY"); identityProperty.SetDataType(MgPropertyType.Int32); identityProperty.SetAutoGeneration(true); identityProperty.SetReadOnly(true); // Add the identity property to the class definition clsProps.Add(identityProperty); idProps.Add(identityProperty); // Create a name property MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME"); nameProperty.SetDataType(MgPropertyType.String); // Add the name property to the class definition clsProps.Add(nameProperty); // Create a geometry property MgGeometricPropertyDefinition geometryProperty = new MgGeometricPropertyDefinition("GEOM"); geometryProperty.SetGeometryTypes(MgFeatureGeometricType.Point); // Add the geometry property to the class definition clsProps.Add(geometryProperty); // Create a feature schema MgFeatureSchema featureSchema = new MgFeatureSchema("PointSchema", "Point schema"); MgClassDefinitionCollection classes = featureSchema.GetClasses(); // Add the feature schema to the class definition classes.Add(classDefinition); // Create the feature source String featureSourceName = "Library://Samples/DevGuide/Data/points.FeatureSource"; MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName); //wkt = "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]"; String wkt = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgFileFeatureSourceParams sdfParams = new MgFileFeatureSourceParams("OSGeo.SDF", "LatLong", wkt, featureSchema); featureService.CreateFeatureSource(resourceIdentifier, sdfParams); // We need to add some data to the sdf before using it. The spatial context // reader must have an extent. MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); // Make four points batchPropertyCollection.Add(MakePoint("Point A", -87.727, 43.748, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point B", -87.728, 43.730, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point C", -87.726, 43.750, wktReaderWriter, agfReaderWriter)); batchPropertyCollection.Add(MakePoint("Point D", -87.728, 43.750, wktReaderWriter, agfReaderWriter)); // Old way commented out /* * // Add the batch property collection to the feature source * MgInsertFeatures cmd = new MgInsertFeatures("Points", batchPropertyCollection); * MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection(); * featureCommandCollection.Add(cmd); * * // Execute the "add" commands * featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false); */ // Here's the mg-desktop way MgFeatureReader insertResult = featureService.InsertFeatures(resourceIdentifier, "Points", batchPropertyCollection); insertResult.Close(); // ... //---------------------------------------------------// // Create a new layer LayerDefinitionFactory factory = new LayerDefinitionFactory(); // Create a mark symbol String resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary"; String symbolName = "PushPin"; String width = "24"; // unit = points String height = "24"; // unit = points String color = "FFFF0000"; String markSymbol = factory.CreateMarkSymbol(resourceId, symbolName, width, height, color); // Create a text symbol String text = "ID"; String fontHeight = "12"; String foregroundColor = "FF000000"; String textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor); // Create a point rule. String ruleLegendLabel = "trees"; String filter = ""; String pointRule = factory.CreatePointRule(ruleLegendLabel, filter, textSymbol, markSymbol); // Create a point type style. String pointTypeStyle = factory.CreatePointTypeStyle(pointRule); // Create a scale range. String minScale = "0"; String maxScale = "1000000000000"; String pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle); // Create the layer definiton. String featureName = "PointSchema:Points"; String geometry = "GEOM"; String layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange); //---------------------------------------------------// // ... XmlDocument domDocument = new XmlDocument(); domDocument.LoadXml(layerDefinition); //Add the layer to the map // TODO: Should probably validate this XML content using (MemoryStream ms = new MemoryStream()) { domDocument.Save(ms); ms.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] ldfBytes = ms.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(ldfBytes)); ldfBytes = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, ldfBytes, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(ldfBytes, ldfBytes.Length); MgResourceIdentifier resourceID = new MgResourceIdentifier("Session:" + sessionId + "//" + layerName + ".LayerDefinition"); resourceService.SetResource(resourceID, byteSource.GetReader(), null); //Insert this layer to our map MgdLayer newLayer = new MgdLayer(resourceID, resourceService); newLayer.Name = layerName; newLayer.LegendLabel = legendLabel; newLayer.DisplayInLegend = true; newLayer.SetVisible(true); layers.Insert(0, newLayer); //Create analysis group if not already created if (groups.IndexOf(groupName) < 0) { MgLayerGroup group = new MgLayerGroup(groupName); group.LegendLabel = groupName; group.DisplayInLegend = true; groups.Add(group); newLayer.Group = group; } MessageBox.Show("Layer (" + layerName + ") created"); _viewer.RefreshMap(); IMapLegend legend = Shell.Instance.Legend; if (legend != null) { legend.RefreshLegend(); } } }
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(); }