public void InsertXMapBaseLayers(LayerCollection layers, XMapMetaInfo meta, string profile) { var baseLayer = new TiledLayer("Background") { TiledProvider = new ExtendedXMapTiledProvider(meta.Url, meta.User, meta.Password) { ContextKey = "in case of context key", CustomProfile = profile + "-bg", }, Copyright = meta.CopyrightText, Caption = MapLocalizer.GetString(MapStringId.Background), IsBaseMapLayer = true, Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png"), }; var labelLayer = new UntiledLayer("Labels") { UntiledProvider = new XMapTiledProvider( meta.Url, XMapMode.Town) { User = meta.User, Password = meta.Password, ContextKey = "in case of context key", CustomProfile = profile + "-fg", }, Copyright = meta.CopyrightText, MaxRequestSize = meta.MaxRequestSize, Caption = MapLocalizer.GetString(MapStringId.Labels), Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Labels.png"), }; layers.Add(baseLayer); layers.Add(labelLayer); }
private void LoadWebMapButton_Click(object sender, System.Windows.RoutedEventArgs e) { if (!string.IsNullOrEmpty(WebMapTextBox.Text)) { Document webMap = new Document(); webMap.GetMapCompleted += (s, a) => { if (a.Error != null) MessageBox.Show(string.Format("Unable to load webmap. {0}", a.Error.Message)); else { MyMap.Extent = a.Map.Extent; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in a.Map.Layers) layerCollection.Add(layer); a.Map.Layers.Clear(); MyMap.Layers = layerCollection; WebMapPropertiesTextBox.DataContext = a.ItemInfo; } }; webMap.GetMapAsync(WebMapTextBox.Text); } }
public Viewshed() { InitializeComponent(); // Initialize the tap points graphics collection TapPoints = new ObservableCollection<Graphic>(); // Initialize layers Layers = new LayerCollection(); // Create the basemap layer and add it to the map Layers.Add(new ArcGISTiledMapServiceLayer() { ServiceUri = "http://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer" }); // Symbol for tap points layer SimpleLineSymbol tapPointsOutline = new SimpleLineSymbol() { Color = Colors.Black }; SimpleMarkerSymbol tapPointsSymbol = new SimpleMarkerSymbol() { Color = Colors.White, Outline = tapPointsOutline }; // Tap points layer m_tapPointsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = tapPointsSymbol } }; // Bind the TapPoints property to the GraphicsSource of the tap points layer Binding b = new Binding("TapPoints") { Source = this }; BindingOperations.SetBinding(m_tapPointsLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer to the map Layers.Add(m_tapPointsLayer); // Set the data context to the page instance to allow for binding to the page's properties // in its XAML DataContext = this; }
public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) { return(null); } var layers = value as LayerCollection; var layersCollection = new LayerCollection(); foreach (var layer in layers.OfType <FeatureLayer>()) { layersCollection.Add(layer); } return(layersCollection); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return(null); } var layers = value as LayerCollection; var layersCollection = new LayerCollection(); foreach (var layer in layers.OfType <FeatureLayer>()) { layersCollection.Add(layer); } return(layersCollection); }
private async void OnButton2Clicked(object sender, EventArgs e) { try { // Define the Uri to the WMTS service (NOTE: iOS applications require the use of Uri's to be https:// and not http://) var myUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS"); // Define a new instance of the WMTS service WmtsService myWmtsService = new WmtsService(myUri); // Load the WMTS service await myWmtsService.LoadAsync(); // Get the service information (i.e. metadata) about the WMTS service WmtsServiceInfo myWMTSServiceInfo = myWmtsService.ServiceInfo; // Obtain the read only list of WMTS layer info objects IReadOnlyList <WmtsLayerInfo> myWmtsLayerInfos = myWMTSServiceInfo.LayerInfos; // Create a new instance of a WMTS layer using the first item in the read only list of WMTS layer info objects WmtsLayer myWmtsLayer = new WmtsLayer(myWmtsLayerInfos[0]); // Create a new map Map myMap = new Map(); // Get the basemap from the map Basemap myBasemap = myMap.Basemap; // Get the layer collection for the base layers LayerCollection myLayerCollection = myBasemap.BaseLayers; // Add the WMTS layer to the layer collection of the map myLayerCollection.Add(myWmtsLayer); // Assign the map to the MapView _myMapView.Map = myMap; } catch (Exception ex) { // Report error UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alert, true, null); } }
private void Layers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { bool featureLayerUpdated = (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset); if (e.OldItems != null) { var featureLayers = new List <FeatureLayer>(); foreach (object layer in e.OldItems) { if (layer is FeatureLayer && !string.IsNullOrEmpty((layer as FeatureLayer).ID)) { featureLayers.Add(layer as FeatureLayer); } } featureLayerUpdated = featureLayers.Count > 0; DetachLayerEventHandler(featureLayers); } if (e.NewItems != null) { var hookToInitialized = new LayerCollection(); var hookToPropertyChangedOnly = new LayerCollection(); foreach (object layer in e.NewItems) { if (layer is FeatureLayer && !string.IsNullOrEmpty((layer as FeatureLayer).ID)) { if (mapLayersInitialized && !(layer as FeatureLayer).IsInitialized) { hookToInitialized.Add(layer as FeatureLayer); } else { hookToPropertyChangedOnly.Add(layer as FeatureLayer); } } } featureLayerUpdated = hookToPropertyChangedOnly.Count > 0; AttachLayerEventHandler(GetLayers(LayerIDs, hookToInitialized), true); AttachLayerEventHandler(GetLayers(LayerIDs, hookToPropertyChangedOnly), false); } if (this.mapLayersInitialized && featureLayerUpdated) { this.setTemplates(); } }
private async void Button2_Click(object sender, RoutedEventArgs e) { try { // Define the Uri to the WMTS service var myUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer/WMTS"); // Define a new instance of the WMTS service WmtsService myWmtsService = new WmtsService(myUri); // Load the WMTS service await myWmtsService.LoadAsync(); // Get the service information (i.e. metadata) about the WMTS service WmtsServiceInfo myWMTSServiceInfo = myWmtsService.ServiceInfo; // Obtain the read only list of WMTS layer info objects IReadOnlyList <WmtsLayerInfo> myWmtsLayerInfos = myWMTSServiceInfo.LayerInfos; // Create a new instance of a WMTS layer using the first item in the read only list of WMTS layer info objects WmtsLayer myWmtsLayer = new WmtsLayer(myWmtsLayerInfos[0]); // Create a new map Map myMap = new Map(); // Get the basemap from the map Basemap myBasemap = myMap.Basemap; // Get the layer collection for the base layers LayerCollection myLayerCollection = myBasemap.BaseLayers; // Add the WMTS layer to the layer collection of the map myLayerCollection.Add(myWmtsLayer); // Assign the map to the MapView MyMapView.Map = myMap; } catch (Exception ex) { MessageDialog messageDlg = new MessageDialog(ex.ToString(), "Error"); await messageDlg.ShowAsync(); } }
public LayerCollection ToAnnotationUI(LayerData[] layers, Size[] pageSizes) { LayerCollection retLayers = new LayerCollection(); if (layers != null) { ConvertFromWDV(layers, pageSizes); foreach (LayerData layer in layers) { AnnotationUI outAnnot = _factories.GetAnnotationFromData(layer); LayerAnnotation layerAnnot = outAnnot as LayerAnnotation; retLayers.Add(layerAnnot); } } return retLayers; }
public void Initialize() { myMap = new Map(); TileCache tileCache = new TileCache(@"D:\workshops\offlinemap-app-hands-on\samples\SampleData\public_map.tpk"); ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tileCache); LayerCollection baseLayers = new LayerCollection(); baseLayers.Add(tiledLayer); myMap.Basemap.BaseLayers = baseLayers; // 主題図の表示 addFeatureLayer(); MyMapView.Map = myMap; // PC内の geodatabase ファイル作成パスを取得する getGeodatabasePath(); }
public void CreateMapFromID(string webMapID) { if (!string.IsNullOrEmpty(webMapID)) { Document webMap = new Document(); webMap.GetMapCompleted += (s, e) => { MyMap.Extent = e.Map.Extent; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) layerCollection.Add(layer); e.Map.Layers.Clear(); MyMap.Layers = layerCollection; WebMapPropertiesTextBox.DataContext = e.ItemInfo; }; webMap.GetMapAsync(webMapID); } }
void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e) { if (e.Error == null) { MyMap.Extent = e.Map.Extent; int i = 0; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) { layer.ID = i.ToString(); layerCollection.Add(layer); if (layer is FeatureLayer) (layer as FeatureLayer).MouseLeftButtonUp += WebMapFeatureServicePopups_MouseLeftButtonUp; i++; } e.Map.Layers.Clear(); MyMap.Layers = layerCollection; } }
/// <summary> /// Clone layer collection in document for modification /// </summary> /// <param name="dxfDocument"></param> public Layer(netDxf.DxfDocument dxfDocument) { foreach (netDxf.Tables.Layer layer in dxfDocument.Layers) { var newLayer = new DxfLayerExtended(layer.Name) { IsVisible = layer.IsVisible, IsFrozen = layer.IsFrozen, IsLocked = layer.IsLocked, Plot = layer.Plot, Color = layer.Color, Linetype = layer.Linetype, Lineweight = layer.Lineweight, Transparency = layer.Transparency, }; LayerCollection.Add(newLayer); } DataContext = this; InitializeComponent(); }
/// <summary> /// Finalizes the network internal structure and locks it against the further changes. /// </summary> /// <param name="outputActivation">The activation function of the output layer.</param> public void FinalizeStructure(AFAnalogBase outputActivation) { if (Finalized) { throw new InvalidOperationException($"Network structure has been already finalized."); } if (outputActivation.DependsOnSorround && NumOfOutputValues < 2) { throw new ArgumentException("Activation requires multiple input for the Compute method but number of output values is less than 2.", "outputActivation"); } //Add output layer LayerCollection.Add(new Layer(NumOfOutputValues, outputActivation)); //Finalize layers int numOfInputNodes = NumOfInputValues; int neuronsFlatStartIdx = 0; int weightsFlatStartIdx = 0; _isAllowedNguyenWidrowRandomization = true; foreach (Layer layer in LayerCollection) { layer.FinalizeStructure(numOfInputNodes, neuronsFlatStartIdx, weightsFlatStartIdx); neuronsFlatStartIdx += layer.NumOfLayerNeurons; weightsFlatStartIdx += layer.NumOfLayerNeurons * layer.NumOfInputNodes + layer.NumOfLayerNeurons; numOfInputNodes = layer.NumOfLayerNeurons; if (layer.Activation.GetType() != typeof(AFAnalogElliot) && layer.Activation.GetType() != typeof(AFAnalogTanH) ) { _isAllowedNguyenWidrowRandomization = false; } } if (LayerCollection.Count < 2) { _isAllowedNguyenWidrowRandomization = false; } NumOfNeurons = neuronsFlatStartIdx; _flatWeights = new double[weightsFlatStartIdx]; return; }
public SharpMapTileProvider(ITileSchema schema, ITileCache <byte[]> cache, params ILayer[] layers) { if (schema == null) { throw new ArgumentNullException("schema"); } if (layers == null) { throw new ArgumentNullException("layers"); } this.Schema = schema; this.cache = cache ?? new NullCache(); LayerCollection collection = new LayerCollection(); foreach (ILayer layer in layers) { collection.Add(layer); } this.layers = collection; }
void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e) { if (e.Error == null) { MyMap.Extent = e.Map.Extent; int i = 0; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) { layer.ID = i.ToString(); layerCollection.Add(layer); if (layer is FeatureLayer) { (layer as FeatureLayer).MouseLeftButtonUp += WebMapFeatureServicePopups_MouseLeftButtonUp; } i++; } e.Map.Layers.Clear(); MyMap.Layers = layerCollection; } }
public void CreateMapFromID(string webMapID) { if (!string.IsNullOrEmpty(webMapID)) { Document webMap = new Document(); webMap.GetMapCompleted += (s, e) => { MyMap.Extent = e.Map.Extent; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) { layerCollection.Add(layer); } e.Map.Layers.Clear(); MyMap.Layers = layerCollection; WebMapPropertiesTextBox.DataContext = e.ItemInfo; }; webMap.GetMapAsync(webMapID); } }
void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e) { if (e.Error == null) { MyMap.Extent = e.Map.Extent; int i = 0; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) { layer.ID = i.ToString(); layerCollection.Add(layer); if (layer is GroupLayer) // the graphicslayer we are interested in is in a grouplayer foreach (Layer childLayer in (layer as GroupLayer).ChildLayers) if (childLayer is GraphicsLayer) (childLayer as GraphicsLayer).MouseLeftButtonUp += WebMapMapNotesPopups_MouseLeftButtonUp; i++; } e.Map.Layers.Clear(); MyMap.Layers = layerCollection; } }
void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e) { if (e.Error == null) { MyMap.Extent = e.Map.Extent; int i = 0; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) { layer.ID = i.ToString(); if (layer is FeatureLayer) { mapTipsElements.Add(layer.ID, (layer as FeatureLayer).MapTip); } layerCollection.Add(layer); i++; } e.Map.Layers.Clear(); MyMap.Layers = layerCollection; } }
// Initializes the set of layers used by the operation private void initializeLayers() { Layers = new LayerCollection(); // Create the basemap layer and add it to the map Layers.Add(new ArcGISTiledMapServiceLayer() { ServiceUri = "http://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer" }); // Symbol for clipped counties (results) layer SimpleLineSymbol countiesOutline = new SimpleLineSymbol() { Color = Colors.Blue }; SimpleFillSymbol countiesSymbol = new SimpleFillSymbol() { Color = Color.FromArgb(127, 200, 200, 255), Outline = countiesOutline }; // Clipped counties layer GraphicsLayer clippedCountiesLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = countiesSymbol } }; // Bind the ClippedCounties property to the GraphicsSource of the clipped counties layer Binding b = new Binding("ClippedCounties") { Source = this }; BindingOperations.SetBinding(clippedCountiesLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer Layers.Add(clippedCountiesLayer); // Symbol for clip lines layer SimpleLineSymbol clipLineSymbol = new SimpleLineSymbol() { Color = Colors.Red, Width = 2 }; // Clip lines layer m_clipLinesLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = clipLineSymbol } }; // Bind the ClipLines property to the GraphicsSource of the clip lines layer b = new Binding("ClipLines") { Source = this }; BindingOperations.SetBinding(m_clipLinesLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer Layers.Add(m_clipLinesLayer); }
public static LayerCollection AddLayer(this LayerCollection self, ILayer layer) { self.Add(layer); return(self); }
public TextView(OptionsData options) { Options = options; Layers = new LayerCollection(this); TextLayer = Layers.Add(new Layer_Text(this)); }
public override bool LoadLayers(LayerCollection newLayers, ProgressStatus progress, FileInfo[] files) { bool bOK = true; float fPercentage = 0.0f; string layerDir = LayerDirectoryName; Dictionary<FileInfo, bool> layersToLoad = new Dictionary<FileInfo, bool>(); foreach (FileInfo file in files) { // Key is FileInfo, Value bool says if a layer backup should be loaded instead of the original layer file. // The layer may have been filtered if it belongs to a zone that isn't currently loaded. if (file != null) { layersToLoad.Add(file, false); } } // Check if there's any layers with backup files and mark their value with true. _layersBackupRestoreSelection.Clear(); if (CheckLayersInterimBackup(layersToLoad, layerDir)) { // Open layer lock dialog where user can select the layers to restore from the backup file. LayerRestoreDlg dlg = new LayerRestoreDlg(); dlg.RestoreLayerList = layersToLoad; dlg.ShowDialog(); // If the user chooses the layers to restore, the layers to restore will be locked, all others won't. _useLayersBackupRestore = true; } else { _useLayersBackupRestore = false; } foreach (var fileInfoEntry in layersToLoad) { FileInfo fileInfo = fileInfoEntry.Key; fPercentage += 100.0f / (float)files.Length; if (fileInfo == null || (fileInfo.Attributes & FileAttributes.Directory) != 0) // file info can be null continue; if (string.Compare(fileInfo.Extension, IScene.LayerFileExtension, true) != 0) continue; string layerFile = fileInfo.Name; if (!fileInfo.FullName.StartsWith(LayerDirectoryName)) // assume it is a layer reference layerFile = this.Project.MakeRelative(fileInfo.FullName); Layer layer = Layers.GetLayerByFilename(layerFile); Layer.LayerFileStatus_e newState = Layer.LayerFileStatus_e.NewLayer; if (layer != null) // already there { bool bModified = layer.LastModified != fileInfo.LastWriteTime; System.Diagnostics.Debug.Assert(!layer.OwnsLock || !bModified); if (bModified && !layer.OwnsLock) { newState = Layer.LayerFileStatus_e.Modified; } else { // don't add the non-modified layer to the list layer.FileStatus = Layer.LayerFileStatus_e.NotModified; continue; } } // If the layer is loaded from the backup, it will load the content from the backup file // and lock the layer right away bool useBackupRestore = fileInfoEntry.Value == true; IFormatter fmt = SerializationHelper.AUTO_FORMATTER; try { string layerToLoad = fileInfo.FullName; // If the layer was marked to load the backup file, add this here if (useBackupRestore) { layerToLoad += IScene.InterimBackupFileExtension; } // open the layer in read-only mode using (FileStream fs = new FileStream(layerToLoad, FileMode.Open, FileAccess.Read)) { layer = (Layer)fmt.Deserialize(fs); } // make sure there is only one layer of type V3DLayer [#18824] if (layer is V3DLayer) { foreach (Layer other in newLayers) if (other is V3DLayer) throw new Exception("The Layer directory contains more than one Layer of type 'Main Layer'. E.g. '" + layer.LayerFilename + "' and '" + other.LayerFilename + "'.\n\nIgnoring '" + layer.LayerFilename + "'"); } } catch (Exception ex) { EditorManager.DumpException(ex); EditorManager.ShowMessageBox("An exception occurred while loading layer '" + fileInfo.Name + "'\n\nDetailed Message:\n" + ex.Message, "Layer loading error", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } if (fileInfo.FullName.StartsWith(layerDir)) layer.SetLayerFileNameInternal(fileInfo.Name); else { // this layer is a reference string name = Project.MakeRelative(fileInfo.FullName); layer.SetLayerFileNameInternal(name); layer.IsReference = true; } layer.UpdateLastModified(fileInfo); layer.FileStatus = newState; layer.UpdateReadOnlyState(fileInfo); newLayers.Add(layer); if (progress != null) progress.Percentage = fPercentage; // If we restore a backup, we will always try to lock the layer and bypass a potential user choice for locking layers if (useBackupRestore) { _layersBackupRestoreSelection.Add(layer); } } return bOK; }
// Initializes the set of layers used by the operation private void initializeLayers() { Layers = new LayerCollection(); // Create the basemap layer and add it to the map Layers.Add(new ArcGISTiledMapServiceLayer() { ServiceUri = "http://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer" }); // Symbol for ocean current (results) layer SimpleLineSymbol currentSymbol = new SimpleLineSymbol() { Color = Colors.Red, Width = 3, Style = SimpleLineStyle.DashDotDot }; // ocean currents layer GraphicsLayer oceanCurrentsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = currentSymbol} }; // Bind the ClippedCounties property to the GraphicsSource of the clipped counties layer Binding b = new Binding("Currents") { Source = this }; BindingOperations.SetBinding(oceanCurrentsLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer Layers.Add(oceanCurrentsLayer); // Symbol for tap points layer SimpleLineSymbol tapPointsOutline = new SimpleLineSymbol() { Color = Colors.Black }; SimpleMarkerSymbol tapPointsSymbol = new SimpleMarkerSymbol() { Color = Colors.White, Outline = tapPointsOutline }; // Tap points layer GraphicsLayer tapPointsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = tapPointsSymbol } }; // Bind the TapPoints property to the GraphicsSource of the tap points layer b = new Binding("TapPoints") { Source = this }; BindingOperations.SetBinding(tapPointsLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer to the map Layers.Add(tapPointsLayer); }
// Public public void UpdateMenu() { if (MyMap != null && MenuItems.Items.Count < 1) { LayerCollection lc = new LayerCollection(); foreach (EsriMap3D.EsriMapLayer mapLayer in MyLayers) { lc.Add(mapLayer.MyLayer); if (mapLayer.MyLayer is ArcGISDynamicMapServiceLayer) { ArcGISDynamicMapServiceLayer dLayer = (ArcGISDynamicMapServiceLayer)mapLayer.MyLayer; foreach (LayerInfo dLayerInfo in dLayer.Layers) MyLayerMapping.Add(dLayerInfo, dLayer); } } MenuItems.ItemsSource = lc.Reverse(); } }
public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) return null; var layers = value as LayerCollection; var layersCollection = new LayerCollection(); foreach (var layer in layers.OfType<FeatureLayer>()) layersCollection.Add(layer); return layersCollection; }
private void mapBox_MapQueried(FeatureDataTable data) { filterCollection.Add(dataManagement.getLayerFromFeatureDataTable(data)); }
/// <summary> /// return IndexofActiveLayer /// </summary> /// <returns></returns> public int CreateNewLayer() { activeLayer = new Layer(); LayerCollection.Add(activeLayer); return(IndexofActiveLayer); }
public object Convert(object value, Type targetType, object parameter, string language) { if (value == null) return null; var layer = value as Layer; var layersCollection = new LayerCollection(); layersCollection.Add(layer); return layersCollection; }
/// <summary> /// Converts a layer hierarchy that may include group layers into a flat collection of layers. /// </summary> private static IEnumerable<Layer> FlattenLayers(this IEnumerable<Layer> layers, GroupLayer parent = null) { LayerCollection flattenedLayers = new LayerCollection(); foreach (Layer layer in layers) { if (layer is GroupLayer && !(layer is KmlLayer)) { // Flatten group layers GroupLayer groupLayer = (GroupLayer)layer; foreach (Layer child in groupLayer.ChildLayers.FlattenLayers(groupLayer)) flattenedLayers.Add(child); } else { // If the layer was within a group layer, account for the group layer's visibility // and opacity if (parent != null) { layer.Visible = !parent.Visible ? false : layer.Visible; layer.Opacity = parent.Opacity * layer.Opacity; layer.DisplayName = parent.DisplayName; } flattenedLayers.Add(layer); } } return flattenedLayers; }
/// <summary> /// Opens a dialog to confirm all the layer changes /// </summary> public void UpdateLayers() { LayerCollection modifiedLayers = new LayerCollection(); ZoneCollection modifiedZones = new ZoneCollection(); // gather new and modified layers GatherZones(modifiedZones); GatherLayers(modifiedLayers, null); // gather deleted layers foreach (Layer layer in Layers) { if (layer.OwnsLock) // cannot be deleted or modified continue; if (File.Exists(layer.AbsoluteLayerFilename)) continue; layer.FileStatus = Layer.LayerFileStatus_e.Deleted; modifiedLayers.Add(layer); } if (modifiedLayers.Count == 0 && modifiedZones.Count == 0) { EditorManager.ShowMessageBox("No updated, new or deleted layers/zones have been detected", "Update Layers", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } LayerUpdateDlg dlg = new LayerUpdateDlg(); dlg.SetModifiedFiles(modifiedLayers, modifiedZones); if (dlg.ShowDialog() != DialogResult.OK) return; EditorManager.Actions.StartGroup("Update Layers"); // add new zones foreach (Zone zone in modifiedZones) { zone.ParentScene = this; Zones.Add(zone); } // now merge the layers into the scene foreach (Layer layer in modifiedLayers) { Layer.LayerFileStatus_e status = layer.FileStatus; if (status == Layer.LayerFileStatus_e.Deleted) { EditorManager.Actions.Add(new RemoveLayerAction(layer)); continue; } if (status == Layer.LayerFileStatus_e.NewLayer) { EditorManager.Actions.Add(new AddLayerAction(layer, false)); // no unique filenames, use as-is continue; } if (status == Layer.LayerFileStatus_e.Modified) { Layer oldLayer = Layers.GetLayerByFilename(layer.LayerFilename); EditorManager.Actions.Add(new UpdateLayerAction(oldLayer, layer)); continue; } } EditorManager.Actions.EndGroup(); modifiedZones.MatchupLayerNames(Layers, null); // only call this for new zones! IScene.SendZoneChangedEvent(new ZoneChangedArgs(null, ZoneChangedArgs.Action.RebuildList)); }
// Initializes the set of layers used by the operation private void initializeLayers() { Layers = new LayerCollection(); // Create the basemap layer and add it to the map Layers.Add(new ArcGISTiledMapServiceLayer() { ServiceUri = "http://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer" }); // Symbol for ocean current (results) layer SimpleLineSymbol currentSymbol = new SimpleLineSymbol() { Color = Colors.Red, Width = 3, Style = SimpleLineStyle.DashDotDot }; // ocean currents layer GraphicsLayer oceanCurrentsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = currentSymbol } }; // Bind the ClippedCounties property to the GraphicsSource of the clipped counties layer Binding b = new Binding("Currents") { Source = this }; BindingOperations.SetBinding(oceanCurrentsLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer Layers.Add(oceanCurrentsLayer); // Symbol for tap points layer SimpleLineSymbol tapPointsOutline = new SimpleLineSymbol() { Color = Colors.Black }; SimpleMarkerSymbol tapPointsSymbol = new SimpleMarkerSymbol() { Color = Colors.White, Outline = tapPointsOutline }; // Tap points layer GraphicsLayer tapPointsLayer = new GraphicsLayer() { Renderer = new SimpleRenderer() { Symbol = tapPointsSymbol } }; // Bind the TapPoints property to the GraphicsSource of the tap points layer b = new Binding("TapPoints") { Source = this }; BindingOperations.SetBinding(tapPointsLayer, GraphicsLayer.GraphicsSourceProperty, b); // Add the layer to the map Layers.Add(tapPointsLayer); }
/** * <summary>Populates a PDF file with contents.</summary> */ private void Populate(Document document) { // Initialize a new page! Page page = new Page(document); document.Pages.Add(page); // Initialize the primitive composer (within the new page context)! PrimitiveComposer composer = new PrimitiveComposer(page); composer.SetFont(PdfType1Font.Load(document, PdfType1Font.FamilyEnum.Helvetica, true, false), 12); // Initialize the block composer (wrapping the primitive one)! BlockComposer blockComposer = new BlockComposer(composer); // Initialize the document layer configuration! LayerDefinition layerDefinition = document.Layer; document.ViewerPreferences.PageMode = ViewerPreferences.PageModeEnum.Layers; // Shows the layers tab on document opening. // Get the root collection of the layers displayed to the user! UILayers uiLayers = layerDefinition.UILayers; // Nested layers. Layer parentLayer; { parentLayer = new Layer(document, "Parent layer"); uiLayers.Add(parentLayer); var childLayers = parentLayer.Children; var childLayer1 = new Layer(document, "Child layer 1"); childLayers.Add(childLayer1); var childLayer2 = new Layer(document, "Child layer 2"); childLayers.Add(childLayer2); childLayer2.Locked = true; /* * NOTE: Graphical content can be controlled through layers in two ways: * 1) marking content within content streams (that is content within the page body); * 2) associating annotations and external objects (XObject) to the layers. */ XObject imageXObject = entities::Image.Get(GetResourcePath("images" + Path.DirectorySeparatorChar + "gnu.jpg")).ToXObject(document); imageXObject.Layer = childLayer1; // Associates the image to the layer. composer.ShowXObject(imageXObject, new SKPoint(200, 75)); composer.BeginLayer(parentLayer); // Opens a marked block associating its contents with the specified layer. composer.ShowText(parentLayer.Title, new SKPoint(50, 50)); composer.End(); // Closes the marked block. composer.BeginLayer(childLayer1); composer.ShowText(childLayer1.Title, new SKPoint(50, 75)); composer.End(); composer.BeginLayer(childLayer2); composer.ShowText(childLayer2.Title, new SKPoint(50, 100)); composer.End(); } // Simple layer collection (labeled collection of inclusive-state layers). Layer simpleLayer1; { var simpleLayerCollection = new LayerCollection(document, "Simple layer collection"); uiLayers.Add(simpleLayerCollection); simpleLayer1 = new Layer(document, "Simple layer 1"); simpleLayerCollection.Add(simpleLayer1); var simpleLayer2 = new Layer(document, "Simple layer 2 (Design)"); /* * NOTE: Intent limits layer use in determining visibility to specific use contexts. In this * case, we want to mark content as intended to represent a document designer's structural * organization of artwork, hence it's outside the interactive use by document consumers. */ simpleLayer2.Intents = new HashSet <PdfName> { IntentEnum.Design.Name() }; simpleLayerCollection.Add(simpleLayer2); var simpleLayer3 = new Layer(document, "Simple layer 3"); simpleLayerCollection.Add(simpleLayer3); blockComposer.Begin(SKRect.Create(50, 125, 200, 75), XAlignmentEnum.Left, YAlignmentEnum.Middle); composer.BeginLayer(simpleLayer1); blockComposer.ShowText(simpleLayer1.Title); composer.End(); blockComposer.ShowBreak(new SKSize(0, 10)); composer.BeginLayer(simpleLayer2); blockComposer.ShowText(simpleLayer2.Title); composer.End(); blockComposer.ShowBreak(new SKSize(0, 10)); composer.BeginLayer(simpleLayer3); blockComposer.ShowText(simpleLayer3.Title); composer.End(); blockComposer.End(); } // Radio layer collection (labeled collection of exclusive-state layers). Layer radioLayer2; { var radioLayerCollection = new LayerCollection(document, "Radio layer collection"); uiLayers.Add(radioLayerCollection); var radioLayer1 = new Layer(document, "Radio layer 1") { Visible = true }; radioLayerCollection.Add(radioLayer1); radioLayer2 = new Layer(document, "Radio layer 2") { Visible = false }; radioLayerCollection.Add(radioLayer2); var radioLayer3 = new Layer(document, "Radio layer 3") { Visible = false }; radioLayerCollection.Add(radioLayer3); // Register this option group in the layer configuration! var optionGroup = new OptionGroup(document) { radioLayer1, radioLayer2, radioLayer3 }; layerDefinition.OptionGroups.Add(optionGroup); blockComposer.Begin(SKRect.Create(50, 200, 200, 75), XAlignmentEnum.Left, YAlignmentEnum.Middle); composer.BeginLayer(radioLayer1); blockComposer.ShowText(radioLayer1.Title); composer.End(); blockComposer.ShowBreak(new SKSize(0, 10)); composer.BeginLayer(radioLayer2); blockComposer.ShowText(radioLayer2.Title); composer.End(); blockComposer.ShowBreak(new SKSize(0, 10)); composer.BeginLayer(radioLayer3); blockComposer.ShowText(radioLayer3.Title); composer.End(); blockComposer.End(); } // Layer state action. { var actionLayer = new Layer(document, "Action layer") { Printable = false }; composer.BeginLayer(actionLayer); composer.BeginLocalState(); composer.SetFillColor(colors::DeviceRGBColor.Get(SKColors.Blue)); composer.ShowText( "Layer state action:\n * deselect \"" + simpleLayer1.Title + "\"\n and \"" + radioLayer2.Title + "\"\n * toggle \"" + parentLayer.Title + "\"", new SKPoint(400, 200), XAlignmentEnum.Left, YAlignmentEnum.Middle, 0, new SetLayerState( document, new SetLayerState.LayerState(SetLayerState.StateModeEnum.Off, simpleLayer1, radioLayer2), new SetLayerState.LayerState(SetLayerState.StateModeEnum.Toggle, parentLayer) ) ); composer.End(); composer.End(); } // Zoom-restricted layer. { var zoomRestrictedLayer = new Layer(document, "Zoom-restricted layer") { ZoomRange = new Interval <double>(.75, 1.251) }; // NOTE: Change this interval to test other magnification ranges. composer.BeginLayer(zoomRestrictedLayer); new TextMarkup( page, composer.ShowText(zoomRestrictedLayer.Title + ": this text is only visible if zoom between 75% and 125%", new SKPoint(50, 290)), "This is a highlight annotation visible only if zoom is between 75% and 125%", TextMarkupType.Highlight ) { Layer = zoomRestrictedLayer /* Associates the annotation to the layer. */ }; composer.End(); } // Print-only layer. { var printOnlyLayer = new Layer(document, "Print-only layer") { Visible = false, Printable = true }; composer.BeginLayer(printOnlyLayer); composer.BeginLocalState(); composer.SetFillColor(colors::DeviceRGBColor.Get(SKColors.Red)); composer.ShowText(printOnlyLayer.Title, new SKPoint(25, 300), XAlignmentEnum.Left, YAlignmentEnum.Top, 90); composer.End(); composer.End(); } // Language-specific layer. { var languageLayer = new Layer(document, "Language-specific layer") { Language = new LanguageIdentifier("en-GB"), // NOTE: Change this to test other languages and locales. LanguagePreferred = true, // Matches any system locale (e.g. en-US, en-AU...) if layer language (en-GB) doesn't match exactly the system language. Printable = false }; blockComposer.Begin(SKRect.Create(50, 320, 500, 75), XAlignmentEnum.Left, YAlignmentEnum.Top); composer.BeginLayer(languageLayer); blockComposer.ShowText(languageLayer.Title + ": this text is visible only if current system language is english (\"en\", any locale (\"en-US\", \"en-GB\", \"en-NZ\", etc.)) and is hidden on print."); composer.End(); blockComposer.End(); } // User-specific layer. { var userLayer = new Layer(document, "User-specific layer") { Users = new List <string> { "Lizbeth", "Alice", "Stefano", "Johann" }, // NOTE: Change these entries to test other user names. UserType = Layer.UserTypeEnum.Individual }; blockComposer.Begin(SKRect.Create(blockComposer.BoundBox.Left, blockComposer.BoundBox.Bottom + 15, blockComposer.BoundBox.Width, 75), XAlignmentEnum.Left, YAlignmentEnum.Top); composer.BeginLayer(userLayer); blockComposer.ShowText(userLayer.Title + ": this text is visible only to " + String.Join(", ", userLayer.Users) + " (exact match)."); composer.End(); blockComposer.End(); } // Layer membership (composite layer visibility). { var layerMembership = new LayerMembership(document) { /* * NOTE: VisibilityExpression is a more flexible alternative to the combination of * VisibilityPolicy and VisibilityMembers. However, for compatibility purposes is preferable * to provide both of them (the latter combination will work as a fallback in case of older * viewer application). */ VisibilityExpression = new VisibilityExpression( document, VisibilityExpression.OperatorEnum.And, new VisibilityExpression( document, VisibilityExpression.OperatorEnum.Not, new VisibilityExpression( document, VisibilityExpression.OperatorEnum.Or, simpleLayer1, radioLayer2 ) ), parentLayer ), VisibilityPolicy = LayerMembership.VisibilityPolicyEnum.AnyOff, VisibilityMembers = new List <Layer> { simpleLayer1, radioLayer2, parentLayer } }; blockComposer.Begin(SKRect.Create(blockComposer.BoundBox.Left, blockComposer.BoundBox.Bottom + 15, blockComposer.BoundBox.Width, 75), XAlignmentEnum.Left, YAlignmentEnum.Top); composer.BeginLayer(layerMembership); blockComposer.ShowText(String.Format("Layer membership: the visibility of this text is computed combining multiple layer states into an expression (\"{0}\" and \"{1}\" must be OFF while \"{2}\" must be ON).", simpleLayer1.Title, radioLayer2.Title, parentLayer.Title)); composer.End(); blockComposer.End(); } composer.Flush(); }
// when layers are added/removed private void Layers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { LayerCollection layers = (LayerCollection)sender; // Put updating of measurable layers in a throttle timer, meaning that this logic will // only be invoked once if the CollectionChanged event fires multiple times within two // tenths of a second. This is necessary because changing to a basemap in a different // spatial reference results in clearing and rebuilding the layers collection. if (_updateMeasurableLayersThrottler == null) { _updateMeasurableLayersThrottler = new ThrottleTimer(20, () => { // Check whether all layers are initialized if (layers.Any(l => !l.IsInitialized)) { layers.LayersInitialized += Layers_LayersInitialized; // Wait for initialization } else { UpdateMeasurableLayers(); // Update measurable layers collection now } }); } _updateMeasurableLayersThrottler.Invoke(); // Check whether layers were added if (e.NewItems != null) { // Hook into visibility changed events for added layers foreach (Layer layer in e.NewItems) { layer.PropertyChanged += Layer_PropertyChanged; if (layer is ArcGISDynamicMapServiceLayer) { ISublayerVisibilitySupport subLayerSupport = layer as ISublayerVisibilitySupport; subLayerSupport.VisibilityChanged += SubLayerSupport_VisibilityChanged; } } } // Check whether layers were removed if (e.OldItems != null) { // Unhook from visibility changed events for removed layers foreach (Layer layer in e.OldItems) { layer.PropertyChanged -= Layer_PropertyChanged; if (layer is ArcGISDynamicMapServiceLayer) { ISublayerVisibilitySupport subLayerSupport = layer as ISublayerVisibilitySupport; subLayerSupport.VisibilityChanged -= SubLayerSupport_VisibilityChanged; } } } // If draw layer has been added to the map, check whether it is the top-most if (layers.Contains(DrawLayer) && layers.IndexOf(DrawLayer) != layers.Count - 1) { // Draw layer is not top-most. Move it to the top by removing and re-adding it. Wrap in // a begin invoke call so the collection is modified outside the CollectionChanged event. Map.Dispatcher.BeginInvoke(() => { layers.Remove(DrawLayer); layers.Add(DrawLayer); }); } }
public void AddBaseLayer(ILayer layer) { BaseLayers.Add(layer); layerCollection.Add(layer); OnBaseLayersChanged(EventArgs.Empty); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return null; var layer = value as Layer; var layersCollection = new LayerCollection(); layersCollection.Add(layer); return layersCollection; }
// Public - Event Handling public void MyMap_ExtentChanged(object sender, ExtentEventArgs args) { if (MyEsriMapLayers != null) { foreach (EsriMapLayer esriLayer in MyEsriMapLayers) { if (esriLayer.MyMap != (Map)sender) { LayerCollection lc = new LayerCollection(); foreach (Layer l in esriLayer.MyMap.Layers) lc.Add(l); //Layer l = esriLayer.MyMap.Layers[0]; esriLayer.MyMap.Layers.Clear(); esriLayer.MyMap.Extent = null; esriLayer.MyMap.Extent = ((Map)sender).Extent; esriLayer.MyMap.Layers = lc; } //esriLayer.MyMap.Extent = ((Map) sender).Extent; } } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return null; var layers = value as LayerCollection; var layersCollection = new LayerCollection(); foreach (var layer in layers.OfType<FeatureLayer>()) layersCollection.Add(layer); return layersCollection; }
private void ButtonSave_Click(object sender, RoutedEventArgs e) { if (checkValidity(out float size) && savePicture(size)) { Close(); } bool checkValidity(out float size) { if (!float.TryParse(_textBoxSize.Text, out size)) { MessageBox.Show("Please check your input. The input is invalid.", "Info"); size = default; return(!(e.Handled = true)); } return(true); } bool savePicture(float size) { var saveFileDialog = new SaveFileDialog { AddExtension = true, DefaultExt = "png", Filter = "PNG files|*.png|JPG files|*.jpg|BMP files|*.bmp|GIF files|*.gif|WMF files|*.wmf", Title = "Save picture..." }; if (!(saveFileDialog.ShowDialog() is true)) { return(!(e.Handled = true)); } var pc = new PointConverter(size, size); var layerCollection = new LayerCollection { new BackLayer(pc, _settings.BackgroundColor), new GridLineLayer( pc, _settings.GridLineWidth, _settings.GridLineColor), new BlockLineLayer( pc, _settings.BlockLineWidth, _settings.BlockLineColor), new ValueLayer( pc, _settings.ValueScale, _settings.CandidateScale, _settings.GivenColor, _settings.ModifiableColor, _settings.CandidateColor, _settings.GivenFontName, _settings.ModifiableFontName, _settings.CandidateFontName, _grid, _settings.ShowCandidates), }; if (_oldCollection[typeof(CustomViewLayer)] is CustomViewLayer customViewLayer) { layerCollection.Add(new CustomViewLayer(pc, customViewLayer)); } if (_oldCollection[typeof(ViewLayer)] is ViewLayer viewLayer) { layerCollection.Add(new ViewLayer(pc, viewLayer)); } Bitmap?bitmap = null; try { bitmap = new Bitmap((int)size, (int)size); int selectedIndex = saveFileDialog.FilterIndex; string fileName = saveFileDialog.FileName; if (selectedIndex >= -1 && selectedIndex <= 3) { // Normal picture formats. layerCollection.IntegrateTo(bitmap); var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); bitmap.Save( fileName, GetEncoderInfo( selectedIndex switch { -1 => Png, 0 => Png, 1 => Jpeg, 2 => Bmp, 3 => Gif, _ => throw Throwings.ImpossibleCase }) ?? throw new NullReferenceException("The return value is null."), encoderParameters); }
/// <summary> /// Returns a list of custom online published layers /// </summary> /// <returns></returns> public LayerCollection getCustomOnlinePublishedLayers() { LayerCollection customLayers = new LayerCollection(); foreach (Layer layer in layers) { string id = layer.ID; string sub = id.Substring(0, tiledServiceLayerIDBase.Length); if (sub.Equals(tiledServiceLayerIDBase)) { customLayers.Add(layer); } } return customLayers; }
public override bool LoadLayers(LayerCollection newLayers, ProgressStatus progress, FileInfo[] files) { bool bOK = true; float fPercentage = 0.0f; string layerDir = LayerDirectoryName; foreach (FileInfo fileInfo in files) { fPercentage += 100.0f / (float)files.Length; if (fileInfo == null || (fileInfo.Attributes & FileAttributes.Directory) != 0) // file info can be null continue; if (string.Compare(fileInfo.Extension, IScene.LayerFileExtension, true) != 0) continue; string layerFile = fileInfo.Name; if (!fileInfo.FullName.StartsWith(LayerDirectoryName)) // assume it is a layer reference layerFile = this.Project.MakeRelative(fileInfo.FullName); Layer layer = Layers.GetLayerByFilename(layerFile); Layer.LayerFileStatus_e newState = Layer.LayerFileStatus_e.NewLayer; if (layer != null) // already there { bool bModified = layer.LastModified != fileInfo.LastWriteTime; System.Diagnostics.Debug.Assert(!layer.OwnsLock || !bModified); if (bModified && !layer.OwnsLock) { newState = Layer.LayerFileStatus_e.Modified; } else { // don't add the non-modified layer to the list layer.FileStatus = Layer.LayerFileStatus_e.NotModified; continue; } } BinaryFormatter fmt = SerializationHelper.BINARY_FORMATTER; try { // open the layer in read-only mode FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); layer = (Layer)fmt.Deserialize(fs); fs.Close(); // make sure there is only one layer of type V3DLayer [#18824] if (layer is V3DLayer) { foreach (Layer other in newLayers) if (other is V3DLayer) throw new Exception("The Layer directory contains more than one Layer of type 'Main Layer'. E.g. '" + layer.LayerFilename + "' and '" + other.LayerFilename + "'.\n\nIgnoring '" + layer.LayerFilename + "'"); } } catch (Exception ex) { EditorManager.DumpException(ex); EditorManager.ShowMessageBox("An exception occurred while loading layer '" + fileInfo.Name + "'\n\nDetailed Message:\n" + ex.ToString(), "Layer loading error", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } if (fileInfo.FullName.StartsWith(layerDir)) layer.SetLayerFileNameInternal(fileInfo.Name); else { // this layer is a reference string name = Project.MakeRelative(fileInfo.FullName); layer.SetLayerFileNameInternal(name); layer.IsReference = true; } layer.UpdateLastModified(fileInfo); layer.FileStatus = newState; layer.UpdateReadOnlyState(fileInfo); newLayers.Add(layer); if (progress != null) progress.Percentage = fPercentage; } return bOK; }
// Clone a Layer private static Layer CloneLayer(Layer layer) { Layer toLayer; var featureLayer = layer as FeatureLayer; if (layer is GraphicsLayer && (featureLayer == null || featureLayer.Url == null || featureLayer.Mode != FeatureLayer.QueryMode.OnDemand)) { // Clone the layer and the graphics var fromLayer = layer as GraphicsLayer; var printLayer = new GraphicsLayer { Renderer = fromLayer.Renderer, Clusterer = fromLayer.Clusterer == null ? null : fromLayer.Clusterer.Clone(), ShowLegend = fromLayer.ShowLegend, RendererTakesPrecedence = fromLayer.RendererTakesPrecedence, ProjectionService = fromLayer.ProjectionService }; toLayer = printLayer; var graphicCollection = new GraphicCollection(); foreach (var graphic in fromLayer.Graphics) { var clone = new Graphic(); foreach (var kvp in graphic.Attributes) { if (kvp.Value is DependencyObject) { // If the attribute is a dependency object --> clone it var clonedkvp = new KeyValuePair <string, object>(kvp.Key, (kvp.Value as DependencyObject).Clone()); clone.Attributes.Add(clonedkvp); } else { clone.Attributes.Add(kvp); } } clone.Geometry = graphic.Geometry; clone.Symbol = graphic.Symbol; clone.Selected = graphic.Selected; clone.TimeExtent = graphic.TimeExtent; graphicCollection.Add(clone); } printLayer.Graphics = graphicCollection; toLayer.ID = layer.ID; toLayer.Opacity = layer.Opacity; toLayer.Visible = layer.Visible; toLayer.MaximumResolution = layer.MaximumResolution; toLayer.MinimumResolution = layer.MinimumResolution; } else { // Clone other layer types toLayer = layer.Clone(); if (layer is GroupLayerBase) { // Clone sublayers (not cloned in Clone() to avoid issue with graphicslayer) var childLayers = new LayerCollection(); foreach (Layer subLayer in (layer as GroupLayerBase).ChildLayers) { var toSubLayer = CloneLayer(subLayer); if (toSubLayer != null) { toSubLayer.InitializationFailed += (s, e) => { }; // to avoid crash if bad layer childLayers.Add(toSubLayer); } } ((GroupLayerBase)toLayer).ChildLayers = childLayers; } } return(toLayer); }
public bool LoadLayersFromXML(LayerCollection newLayers, ProgressStatus progress, FileInfo[] files) { bool bOK = true; float fPercentage = 0.0f; foreach (FileInfo fileInfo in files) { fPercentage += 100.0f / (float)files.Length; if (fileInfo == null || (fileInfo.Attributes & FileAttributes.Directory) != 0) // file info can be null continue; if (string.Compare(fileInfo.Extension, IScene.LayerFileExtensionXML, true) != 0) continue; try { string absfilename = fileInfo.FullName; string filename = fileInfo.Name; using (XmlTextReader xmlReader = new XmlTextReader(absfilename)) { XmlDocument doc = new XmlDocument(); doc.Load(xmlReader); if (doc.DocumentElement == null) throw new Exception("XML does not contain root node"); IEnumerator nodes = doc.DocumentElement.GetEnumerator(); while (nodes.MoveNext()) { XmlElement node = nodes.Current as XmlElement; if (node == null || node.Name != "layer") continue; string classname = node.GetAttribute("class"); string name = node.GetAttribute("name"); string uid = node.GetAttribute("uid"); if (string.IsNullOrEmpty(name)) name = Path.GetFileNameWithoutExtension(filename); Type t = EditorManager.ShapeFactory.GetTypeByName(classname, typeof(Layer), false); if (t == null) t = typeof(Layer); Layer layer = Activator.CreateInstance(t, new object[1] { name }) as Layer; if (layer == null) throw new Exception("Could not instantiate Layer"); layer.SetLayerFileNameInternal(filename); // same filename but will replace extension if (!string.IsNullOrEmpty(uid)) { layer.SetLayerIDInternal(Convert.ToUInt32(uid)); } newLayers.Add(layer); // apply property/value pairs to layer SerializationHelper.ApplyXMLProperties(node, layer, false); // parse for shapes IEnumerator propNodes = node.GetEnumerator(); while (propNodes.MoveNext()) { XmlElement propNode = propNodes.Current as XmlElement; if (propNode == null) continue; if (propNode.Name == "shapes") { // use prefab functionality to parse it PrefabDesc dummyPrefab = new PrefabDesc(null); ShapeCollection shapes = dummyPrefab.CreateInstances(propNode, true, true); if (shapes != null) { layer.Root.SetChildCollectionInternal(shapes); foreach (ShapeBase shape in shapes) { shape.SetParentInternal(layer.Root); shape.SetParentLayerInternal(layer); } } if (!string.IsNullOrEmpty(dummyPrefab.LastError)) { string msg = "An error occurred while parsing file: \n\n" + filename + "\n\nThe layer won't contain any shapes.\nDetailed message:\n" + dummyPrefab.LastError; EditorManager.ShowMessageBox(msg, "Error parsing layer file", MessageBoxButtons.OK, MessageBoxIcon.Error); } continue; } } } } } catch (Exception ex) { EditorManager.DumpException(ex, false); return false; } } return bOK; }
private void Layers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { bool featureLayerUpdated = (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset); if (e.OldItems != null) { var featureLayers = new List<FeatureLayer>(); foreach (object layer in e.OldItems) { if (layer is FeatureLayer && !string.IsNullOrEmpty((layer as FeatureLayer).ID)) featureLayers.Add(layer as FeatureLayer); } featureLayerUpdated = featureLayers.Count > 0; DetachLayerEventHandler(featureLayers); } if (e.NewItems != null) { var hookToInitialized = new LayerCollection(); var hookToPropertyChangedOnly = new LayerCollection(); foreach (object layer in e.NewItems) { if (layer is FeatureLayer && !string.IsNullOrEmpty((layer as FeatureLayer).ID)) { if (mapLayersInitialized && !(layer as FeatureLayer).IsInitialized) hookToInitialized.Add(layer as FeatureLayer); else hookToPropertyChangedOnly.Add(layer as FeatureLayer); } } featureLayerUpdated = hookToPropertyChangedOnly.Count > 0; AttachLayerEventHandler(GetLayers(LayerIDs, hookToInitialized), true); AttachLayerEventHandler(GetLayers(LayerIDs, hookToPropertyChangedOnly), false); } if (this.mapLayersInitialized && featureLayerUpdated) this.setTemplates(); }
void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e) { if (e.Error == null) { MyMap.Extent = e.Map.Extent; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) layerCollection.Add(layer); e.Map.Layers.Clear(); MyMap.Layers = layerCollection; } }
void webMap_GetMapCompleted(object sender, GetMapCompletedEventArgs e) { if (e.Error == null) { MyMap.Extent = e.Map.Extent; LayerCollection layerCollection = new LayerCollection(); foreach (Layer layer in e.Map.Layers) layerCollection.Add(layer); GraphicsLayer selectedGraphics = new GraphicsLayer() { RendererTakesPrecedence = false, ID = "MySelectionGraphicsLayer" }; layerCollection.Add(selectedGraphics); e.Map.Layers.Clear(); MyMap.Layers = layerCollection; } }
public Model() { LayerCollection.Add(new Layer()); activeLayer = LayerCollection[0]; }