コード例 #1
0
        private void ApplyRangeValueClick(object sender, RoutedEventArgs e)
        {
            ClassBreaksRenderer newClassBreaksRenderer = new ClassBreaksRenderer();
            newClassBreaksRenderer.Field = "POP00_SQMI";
            var Infos = new List<ClassBreakInfo>();
            Infos.Add(new ClassBreakInfo()
            {

                Minimum = 0,
                Maximum = 12,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 0)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 31.3,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 100, 255, 100)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 59.7,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 200)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 146.2,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 255)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 57173,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 0, 255)
                }
            });
            newClassBreaksRenderer.Infos = Infos;
            var layer = MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer;
            layer.LayerDrawingOptions.Add(new LayerDrawingOptions()
            {
                LayerID = 3,
                Renderer = newClassBreaksRenderer
            });
            layer.VisibleLayers = new int[] { 3 };
        }
        private void SetRenderers()
        {
            SimpleRenderer simpleRenderer = new SimpleRenderer()
            {
                Description = "Rivers",
                Label = "Rivers",
                Symbol = new SimpleLineSymbol() { Color = Colors.Blue, Style = SimpleLineStyle.Dash, Width = 2 }
            };
            (mapView1.Map.Layers["MyFeatureLayerSimple"] as FeatureLayer).Renderer = simpleRenderer;

            UniqueValueRenderer uvr = new UniqueValueRenderer();
            uvr.Fields = new ObservableCollection<string>(new string [] { "STATE_NAME" });
            uvr.Infos.Add(new UniqueValueInfo { Values = new ObservableCollection<object>(new object[] {"New Mexico" }), Symbol = new SimpleFillSymbol() { Color = Colors.Yellow } });
            uvr.Infos.Add(new UniqueValueInfo { Values = new ObservableCollection<object>(new object[] { "Texas" }), Symbol = new SimpleFillSymbol() { Color = Colors.PaleGreen } });
            uvr.Infos.Add(new UniqueValueInfo { Values = new ObservableCollection<object>(new object[] { "Arizona" }), Symbol = new SimpleFillSymbol() { Color = Colors.YellowGreen } });

            (mapView1.Map.Layers["MyFeatureLayerUnique"] as FeatureLayer).Renderer = uvr;


            ClassBreaksRenderer CBR = new ClassBreaksRenderer()
            {
                DefaultLabel = "All Other Values",
                DefaultSymbol = new SimpleMarkerSymbol() { Color = Colors.Black, Style = SimpleMarkerStyle.Cross, Size = 10 },
                Field = "POP1990",
                Minimum = 0
            };

            CBR.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 30000,
                Label = "0-30000",
                Description = "Pop between 0 and 30000",
                Symbol = new SimpleMarkerSymbol() { Color = Colors.Yellow, Size = 8, Style = SimpleMarkerStyle.Circle }
            });
            CBR.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 300000,
                Label = "30000-300000",
                Description = "Pop between 30000 and 300000",
                Symbol = new SimpleMarkerSymbol() { Color = Colors.Red, Size = 10, Style = SimpleMarkerStyle.Circle }
            });

            CBR.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 5000000,
                Label = "300000-5000000",
                Description = "Pop between 300000 and 5000000",
                Symbol = new SimpleMarkerSymbol() { Color = Colors.Orange, Size = 12, Style = SimpleMarkerStyle.Circle }
            });
            (mapView1.Map.Layers["MyFeatureLayerClassBreak"] as FeatureLayer).Renderer = CBR;
        }
コード例 #3
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static ClassBreaksRenderer MakeDOCRenderer()
        {
            double symbolSize = 10;

            ClassBreaksRenderer breaksRenderer = new ClassBreaksRenderer();
            breaksRenderer.Field = "Measurement";
            SimpleMarkerSymbol defaultSymbol = new SimpleMarkerSymbol();
            defaultSymbol.Size = symbolSize;
            defaultSymbol.Color = (SolidColorBrush)new BrushConverter().ConvertFromString("#f50404");
            defaultSymbol.Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle;
            breaksRenderer.DefaultSymbol = defaultSymbol;

            List<double> min = new List<double>
            {
                0,6,12,18,24,30,36,48,60
            };

            List<double> max = new List<double>
            {
                6,12,18,24,30,36,48,60,1000
            };
            List<string> colors = new List<string>
            {
                "#fa5903","#fc8b00","#fcc304","#f5f502","#c7f704","#95f703","#5bf600","#02f502","#39a801"
            };

            for (int i = 0; i < 9; i++)
            {
                ESRI.ArcGIS.Client.ClassBreakInfo classBreak = new ESRI.ArcGIS.Client.ClassBreakInfo();

                SimpleMarkerSymbol breakSymbol = new SimpleMarkerSymbol();
                breakSymbol.Size = symbolSize;
                breakSymbol.Color = (SolidColorBrush)new BrushConverter().ConvertFromString(colors[i]);
                breakSymbol.Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle;

                classBreak.Symbol = breakSymbol;
                classBreak.MinimumValue = min[i];
                classBreak.MaximumValue = max[i];

                breaksRenderer.Classes.Add(classBreak);

            }

            return breaksRenderer;
        }
コード例 #4
0
        private void ApplyRangeValueClick(object sender, RoutedEventArgs e)
        {
            ClassBreaksRenderer newClassBreaksRenderer = new ClassBreaksRenderer();

            newClassBreaksRenderer.Field = "POP00_SQMI";

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MinimumValue = 0,
                MaximumValue = 12,
                Symbol       = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 31.3,
                Symbol       = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 100, 255, 100))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 59.7,
                Symbol       = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 200))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 146.2,
                Symbol       = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 255))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 57173,
                Symbol       = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 0, 255))
                }
            });

            LayerDrawingOptions layerDrawOptions = new LayerDrawingOptions();

            layerDrawOptions.LayerID  = 3;
            layerDrawOptions.Renderer = newClassBreaksRenderer;

            (MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer).LayerDrawingOptions =
                new LayerDrawingOptionsCollection()
            {
                layerDrawOptions
            };
            (MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer).VisibleLayers = new int[] { 3 };
            // Changing VisibleLayers will refresh the layer, otherwise an explicit call to Refresh is needed.
            //(MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer).Refresh();
        }
コード例 #5
0
        // Creates the renderers in code
        private void initializeRenderers()
        {
            // Create simple renderer with one symbol for rivers layer
            SimpleRenderer simpleRenderer = new SimpleRenderer()
            {
                Description = "Rivers",
                Label = "Rivers",
                Symbol = new SimpleLineSymbol() { Color = Colors.Blue, Style = SimpleLineStyle.Dash, Width = 2 }
            };
            RiversRenderer = simpleRenderer;

            // Create a unique value renderer that defines different symbols for New Mexico, Texas, 
            // and Arizona
            UniqueValueRenderer uvr = new UniqueValueRenderer();
            uvr.Fields = new ObservableCollection<string>(new string[] { "STATE_NAME" });
            SimpleLineSymbol stateOutline = new SimpleLineSymbol() { Color = Colors.Black };
            uvr.Infos.Add(new UniqueValueInfo 
            { 
                Values = new ObservableCollection<object>(new object[] { "New Mexico" }), 
                Symbol = new SimpleFillSymbol() { Color = Colors.Yellow, Outline = stateOutline } 
            });
            uvr.Infos.Add(new UniqueValueInfo 
            { 
                Values = new ObservableCollection<object>(new object[] { "Texas" }),
                Symbol = new SimpleFillSymbol() { Color = Colors.Green, Outline = stateOutline }
            });
            uvr.Infos.Add(new UniqueValueInfo 
            { 
                Values = new ObservableCollection<object>(new object[] { "Arizona" }),
                Symbol = new SimpleFillSymbol() { Color = Colors.LightGray, Outline = stateOutline }
            });
            StatesRenderer = uvr;

            // Create a class breaks renderer to symbolize cities of different sizes
            ClassBreaksRenderer cbr = new ClassBreaksRenderer()
            {
                DefaultLabel = "All Other Values",
                DefaultSymbol = new SimpleMarkerSymbol() { Color = Colors.Black, 
                    Style = SimpleMarkerStyle.Cross, Size = 10 },
                Field = "POP1990",
                Minimum = 0
            };

            // Create and add symbols
            SimpleLineSymbol cityOutline = new SimpleLineSymbol() { Color = Colors.White };
            cbr.Infos.Add(new ClassBreakInfo()
            {
                Minimum = 100000,
                Maximum = 200000,
                Label = "100000 - 200000",
                Description = "Population between 100000 and 200000",
                Symbol = new SimpleMarkerSymbol() 
                { 
                    Color = Color.FromArgb(255, 0, 210, 0), 
                    Outline = cityOutline,
                    Size = 4, 
                    Style = SimpleMarkerStyle.Circle 
                }
            });
            cbr.Infos.Add(new ClassBreakInfo()
            {
                Minimum = 200001,
                Maximum = 1000000,
                Label = "200001 - 1000000",
                Description = "Population between 200001 and 1000000",
                Symbol = new SimpleMarkerSymbol() 
                { 
                    Color = Color.FromArgb(255, 0, 127, 0), 
                    Outline = cityOutline,
                    Size = 8, 
                    Style = SimpleMarkerStyle.Circle 
                }
            });

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Minimum = 1000001,
                Maximum = 10000000,
                Label = "1000001 - 10000000",
                Description = "Population between 1000001 and 10000000",
                Symbol = new SimpleMarkerSymbol() 
                { 
                    Color = Color.FromArgb(255, 0, 50, 0), 
                    Outline = cityOutline,
                    Size = 12, 
                    Style = SimpleMarkerStyle.Circle 
                }
            });
            CitiesRenderer = cbr;
        }
コード例 #6
0
        internal void Initialize()
        {
            // Only show this option when configuring the default symbol (not valid for class breaks)
            bool isConfiguringLayer = DataContext is Layer;

            if (ClusterPanel != null)
            {
                ClusterPanel.Visibility = isConfiguringLayer ? Visibility.Visible : Visibility.Collapsed;
                ClusterPanel.IsEnabled  = DataContext is ConfigurableHeatMapLayer ? false : true;
            }
            if (RenderAsHeatMapPanel != null)
            {
                RenderAsHeatMapPanel.Visibility = isConfiguringLayer ? Visibility.Visible : Visibility.Collapsed;
            }
            if (MarkerSymbolSelector != null)
            {
                MarkerSymbolSelector.IsEnabled = isConfiguringLayer ? true : false;
            }

            PictureMarkerSymbol symbol = DataContext as PictureMarkerSymbol;

            if (symbol != null)
            {
                if (CurrentSymbolImage != null)
                {
                    CurrentSymbolImage.Source = symbol.Source;
                }
                if (OpacitySlider != null)
                {
                    OpacitySlider.SetBinding(Slider.ValueProperty, new Binding()
                    {
                        Path   = new PropertyPath("Opacity"),
                        Source = this.DataContext
                    });
                    OpacitySlider.IsEnabled = DataContext is ConfigurableHeatMapLayer ? false : true;
                }
                if (MarkerSymbolSelector != null)
                {
                    MarkerSymbolSelector.IsEnabled = true;
                }
                if (CurrentSymbolImageOverlay != null)
                {
                    CurrentSymbolImageOverlay.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                GraphicsLayer layerInfo = DataContext as GraphicsLayer;
                if (layerInfo != null)
                {
                    ClassBreaksRenderer renderer = layerInfo.Renderer as ClassBreaksRenderer;
                    if (renderer == null)
                    {
                        return;
                    }
                    PictureMarkerSymbol pictureMarkerSymbol = renderer.DefaultSymbol as PictureMarkerSymbol;
                    if (pictureMarkerSymbol != null)
                    {
                        if (CurrentSymbolImage != null)
                        {
                            CurrentSymbolImage.Source = pictureMarkerSymbol.Source;
                        }
                    }

                    if (MarkerSymbolSelector != null)
                    {
                        MarkerSymbolSelector.IsEnabled = DataContext is ConfigurableHeatMapLayer ? false : true;
                    }
                    if (CurrentSymbolImageOverlay != null)
                    {
                        CurrentSymbolImageOverlay.Visibility = DataContext is ConfigurableHeatMapLayer ? Visibility.Visible : Visibility.Collapsed;
                    }
                    if (ClusterFeaturesCheckBox != null)
                    {
                        ClusterFeaturesCheckBox.IsChecked = layerInfo.Clusterer != null;
                    }
                    if (AdvancedClusterPropertiesButton != null)
                    {
                        AdvancedClusterPropertiesButton.IsEnabled = layerInfo.Clusterer != null;
                    }
                }
            }
        }
コード例 #7
0
        // Creates the renderers in code
        private void initializeRenderers()
        {
            // Create simple renderer with one symbol for rivers layer
            SimpleRenderer simpleRenderer = new SimpleRenderer()
            {
                Description = "Rivers",
                Label       = "Rivers",
                Symbol      = new SimpleLineSymbol()
                {
                    Color = Colors.Blue, Style = SimpleLineStyle.Dash, Width = 2
                }
            };

            RiversRenderer = simpleRenderer;

            // Create a unique value renderer that defines different symbols for New Mexico, Texas,
            // and Arizona
            UniqueValueRenderer uvr = new UniqueValueRenderer();

            uvr.Fields = new ObservableCollection <string>(new string[] { "STATE_NAME" });
            SimpleLineSymbol stateOutline = new SimpleLineSymbol()
            {
                Color = Colors.Black
            };

            uvr.Infos.Add(new UniqueValueInfo
            {
                Values = new ObservableCollection <object>(new object[] { "New Mexico" }),
                Symbol = new SimpleFillSymbol()
                {
                    Color = Colors.Yellow, Outline = stateOutline
                }
            });
            uvr.Infos.Add(new UniqueValueInfo
            {
                Values = new ObservableCollection <object>(new object[] { "Texas" }),
                Symbol = new SimpleFillSymbol()
                {
                    Color = Colors.Green, Outline = stateOutline
                }
            });
            uvr.Infos.Add(new UniqueValueInfo
            {
                Values = new ObservableCollection <object>(new object[] { "Arizona" }),
                Symbol = new SimpleFillSymbol()
                {
                    Color = Colors.LightGray, Outline = stateOutline
                }
            });
            StatesRenderer = uvr;

            // Create a class breaks renderer to symbolize cities of different sizes
            ClassBreaksRenderer cbr = new ClassBreaksRenderer()
            {
                DefaultLabel  = "All Other Values",
                DefaultSymbol = new SimpleMarkerSymbol()
                {
                    Color = Colors.Black,
                    Style = SimpleMarkerStyle.Cross, Size = 10
                },
                Field   = "POP1990",
                Minimum = 0
            };

            // Create and add symbols
            SimpleLineSymbol cityOutline = new SimpleLineSymbol()
            {
                Color = Colors.White
            };

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Minimum     = 100000,
                Maximum     = 200000,
                Label       = "100000 - 200000",
                Description = "Population between 100000 and 200000",
                Symbol      = new SimpleMarkerSymbol()
                {
                    Color   = Color.FromArgb(255, 0, 210, 0),
                    Outline = cityOutline,
                    Size    = 4,
                    Style   = SimpleMarkerStyle.Circle
                }
            });
            cbr.Infos.Add(new ClassBreakInfo()
            {
                Minimum     = 200001,
                Maximum     = 1000000,
                Label       = "200001 - 1000000",
                Description = "Population between 200001 and 1000000",
                Symbol      = new SimpleMarkerSymbol()
                {
                    Color   = Color.FromArgb(255, 0, 127, 0),
                    Outline = cityOutline,
                    Size    = 8,
                    Style   = SimpleMarkerStyle.Circle
                }
            });

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Minimum     = 1000001,
                Maximum     = 10000000,
                Label       = "1000001 - 10000000",
                Description = "Population between 1000001 and 10000000",
                Symbol      = new SimpleMarkerSymbol()
                {
                    Color   = Color.FromArgb(255, 0, 50, 0),
                    Outline = cityOutline,
                    Size    = 12,
                    Style   = SimpleMarkerStyle.Circle
                }
            });
            CitiesRenderer = cbr;
        }
 private void setLayerInfoColor()
 {
     if (ColorRampListBox == null)
     {
         return;
     }
     if (ColorRampListBox.Items.Count > 0)
     {
         GraphicsLayer layerInfo = DataContext as GraphicsLayer;
         if (layerInfo != null)
         {
             ClassBreaksRenderer classBreaksRenderer = layerInfo.Renderer as ClassBreaksRenderer;
             if (classBreaksRenderer != null)
             {
                 // TODO:- evaluate whether this condition is valid and apply
                 // && !layerInfo.ClassBreaks.IsUsingCustomFillSymbolColors
                 if (classBreaksRenderer.Classes.Count > 1)
                 {
                     // Compare the color of the boundary classbreaks
                     // with the start and end color gradients
                     // and set the selected item
                     ClassBreakInfo first = classBreaksRenderer.Classes[0];
                     ClassBreakInfo last  = classBreaksRenderer.Classes[classBreaksRenderer.Classes.Count - 1];
                     if (first.Symbol is SimpleFillSymbol && last.Symbol is SimpleFillSymbol)
                     {
                         SimpleFillSymbol firstSymbol = first.Symbol as SimpleFillSymbol;
                         SimpleFillSymbol lastSymbol  = last.Symbol as SimpleFillSymbol;
                         Color            firstColor  = (firstSymbol.Fill as SolidColorBrush).Color;
                         Color            lastColor   = (lastSymbol.Fill as SolidColorBrush).Color;
                         setSelectedColorInRamp(firstColor, lastColor);
                     }
                     else if (first.Symbol is SimpleLineSymbol && last.Symbol is SimpleLineSymbol)
                     {
                         SimpleLineSymbol firstSymbol = first.Symbol as SimpleLineSymbol;
                         SimpleLineSymbol lastSymbol  = last.Symbol as SimpleLineSymbol;
                         Color            firstColor  = (firstSymbol.Color as SolidColorBrush).Color;
                         Color            lastColor   = (lastSymbol.Color as SolidColorBrush).Color;
                         setSelectedColorInRamp(firstColor, lastColor);
                     }
                 }
                 else
                 {
                     // default to the first one
                     ListBoxItem item = ColorRampListBox.Items[0] as ListBoxItem;
                     if (_selectedRectangle != null)
                     {
                         // un-select the previous one
                         _selectedRectangle.StrokeThickness = 1;
                     }
                     Rectangle rect = item.Content as Rectangle;
                     if (rect != null)
                     {
                         // select the current one
                         _selectedRectangle = rect;
                         _selectedRectangle.StrokeThickness = 2;
                     }
                     ColorRampListBox.SelectedIndex = 0;
                 }
             }
         }
     }
 }
コード例 #9
0
        private void SetRangeValues()
        {
            if (this.Layer == null)
            {
                return;
            }

            // if necessary, update ColorList based on current number of classes.
            int _classCount = (int)ClassCountCombo.SelectedItem;

            if (_lastGeneratedClassCount != _classCount)
            {
                CreateColorList();
            }

            // Field on which to generate a classification scheme.
            ThematicItem thematicItem = ThematicItemList[FieldCombo.SelectedIndex];

            // Store a list of values to classify
            List <double> valueList = new List <double>();

            // Get range, min, max, etc. from features
            for (int i = 0; i < _featureSet.Features.Count; i++)
            {
                Graphic graphicFeature = _featureSet.Features[i];

                double graphicValue = Convert.ToDouble(graphicFeature.Attributes[thematicItem.Name]);

                if (i == 0)
                {
                    thematicItem.Min = graphicValue;
                    thematicItem.Max = graphicValue;
                }
                else
                {
                    if (graphicValue < thematicItem.Min)
                    {
                        thematicItem.Min = graphicValue;
                    }
                    if (graphicValue > thematicItem.Max)
                    {
                        thematicItem.Max = graphicValue;
                    }
                }

                valueList.Add(graphicValue);
            }

            // Set up range start values
            thematicItem.RangeStarts = new List <double>();

            double totalRange = thematicItem.Max - thematicItem.Min;
            double portion    = totalRange / _classCount;

            thematicItem.RangeStarts.Add(thematicItem.Min);
            double startRangeValue = thematicItem.Min;

            // Equal Interval
            if (ClassTypeCombo.SelectedIndex == 1)
            {
                for (int i = 1; i < _classCount; i++)
                {
                    startRangeValue += portion;
                    thematicItem.RangeStarts.Add(startRangeValue);
                }
            }
            // Quantile
            else
            {
                // Enumerator of all values in ascending order
                IEnumerable <double> valueEnumerator =
                    from aValue in valueList
                    orderby aValue                     //"ascending" is default
                    select aValue;

                int increment = Convert.ToInt32(Math.Ceiling(_featureSet.Features.Count / _classCount));
                for (int i = increment; i < valueList.Count; i += increment)
                {
                    double value = valueEnumerator.ElementAt(i);
                    thematicItem.RangeStarts.Add(value);
                }
            }

            // Create graphic features and set symbol using the class range which contains the value
            List <SolidColorBrush> brushList = ColorList[ColorBlendCombo.SelectedIndex];

            if (_featureSet != null && _featureSet.Features.Count > 0)
            {
                ClassBreaksRenderer renderer = new ClassBreaksRenderer()
                {
                    Attribute = thematicItem.Name
                };
                for (int i = 1; i < thematicItem.RangeStarts.Count; i++)
                {
                    renderer.Classes.Add(new ClassBreakInfo()
                    {
                        MinimumValue = thematicItem.RangeStarts[i - 1],
                        MaximumValue = thematicItem.RangeStarts[i],
                        Symbol       = new SimpleFillSymbol()
                        {
                            Fill            = brushList[i],
                            BorderThickness = 0
                        }
                    });
                }
                renderer.Classes[0].MinimumValue = double.MinValue;
                renderer.Classes[renderer.Classes.Count - 1].MaximumValue = double.MaxValue;
                Layer.Renderer = renderer;
                Layer.Refresh();
            }
        }
コード例 #10
0
        public void Render_Layers()
        {
            IMxDocument pMxDoc;

            pMxDoc = (IMxDocument)ArcMap.Application.Document;
            IMap pMap;

            pMap = pMxDoc.FocusMap;
            string strChoice = null;

            //** Giving the user a choice of 3 predefined maps
            strChoice = Interaction.InputBox("1 - U.S. States, " + Environment.NewLine + "2 - Major Cities, " + Environment.NewLine + "3 - State Polygon Area Rank", "Please choose a map.");
            if (string.IsNullOrEmpty(strChoice))
            {
                return;
            }
            IWorkspaceFactory pWFactory;

            pWFactory = new ShapefileWorkspaceFactory();
            IWorkspace pWorkspace;

            pWorkspace = pWFactory.OpenFromFile("C:\\GEOG489\\Lesson1-2", 0);
            IFeatureWorkspace pFeatureWorkspace;

            pFeatureWorkspace = (IFeatureWorkspace)pWorkspace;
            IFeatureLayer pFLayer;

            pFLayer = new FeatureLayer();
            IGeoFeatureLayer pGeoFLayer;

            pGeoFLayer = (IGeoFeatureLayer)pFLayer;
            IFeatureClass pFClass;

            ITable                   pTable;
            IClassify                pClasses;
            ITableHistogram          pTableHist;
            IHistogram               pHist;
            IClassBreaksRenderer     pCBR;
            IClassBreaksUIProperties pUIProperties;
            ILegendInfo              pLegendInfo;

            object Frequencies = null;
            object Values      = null;


            if (strChoice == "1")
            {
                //** User gets a Unique Value rendering of U.S. States by sub-region
                pFClass = pFeatureWorkspace.OpenFeatureClass("us_boundaries.shp");

                pFLayer.FeatureClass = pFClass;
                pFLayer.Name         = "U.S. States";
                pMap.AddLayer(pFLayer);

                IUniqueValueRenderer pUVRender;
                pUVRender = new UniqueValueRenderer();

                //** Setting default symbol for features that don't have a value in
                //** the classification field
                ISimpleFillSymbol pSymDefault;
                pSymDefault               = new SimpleFillSymbol();
                pSymDefault.Style         = ESRI.ArcGIS.Display.esriSimpleFillStyle.esriSFSSolid;
                pSymDefault.Outline.Width = 0.4;

                //** These properties should be set prior to adding values
                pUVRender.FieldCount = 1;
                //** Can classify based on up to 3 fields
                pUVRender.Field[0] = "NAME";
                //** Name of the 1st (only) field
                pUVRender.DefaultSymbol    = (ISymbol)pSymDefault;
                pUVRender.UseDefaultSymbol = true;
                IQueryFilter pQFilter;
                pQFilter = new QueryFilter();
                //** empty QueryFilter same as selecting all recs
                IFeatureCursor pFCursor;
                pFCursor = pFClass.Search(pQFilter, false);
                //** getting all features

                //** Make the color ramp we will use for the symbols in the renderer.
                //** Colors should be random for Unique Value, as opposed to light-to-dark.
                //** Make settings for hue, saturation, value, and seed to have random
                //** colors generated within certain limits.
                IRandomColorRamp pRamp;
                pRamp = new RandomColorRamp();
                pRamp.MinSaturation = 25;
                pRamp.MaxSaturation = 45;
                pRamp.MinValue      = 85;
                pRamp.MaxValue      = 100;
                pRamp.StartHue      = 205;
                pRamp.EndHue        = 320;
                pRamp.UseSeed       = true;
                pRamp.Seed          = 25;

                IFeature pFeature;
                int      n = 0;
                int      i = 0;

                n = pFClass.FeatureCount(pQFilter);
                //** Getting total count of state features

                //** Loop through the features
                while (i != n)
                {
                    ISimpleFillSymbol pSymX;
                    pSymX = new SimpleFillSymbol();

                    //** Move to the next feature and assign the value in the Sub_region field to a var
                    pFeature = pFCursor.NextFeature();
                    string strVal = null;
                    strVal = pFeature.Value[2].ToString();
                    //** NAME Field is at this index in fields collection

                    //** Test to see if we've already added this value
                    //** to the renderer, if not, then add it.
                    bool blnAdded = false;
                    blnAdded = false;

                    int x = 0;
                    //** First time through, ValueCount = 0
                    for (x = 0; x <= (pUVRender.ValueCount - 1); x++)
                    {
                        if (pUVRender.Value[x] == strVal)
                        {
                            blnAdded = true;
                            break;
                        }
                    }

                    //** Value not yet encountered, must add it
                    if (blnAdded == false)
                    {
                        pUVRender.AddValue(strVal, "Predominant Term", (ISymbol)pSymDefault);
                        pUVRender.Label[strVal]  = strVal;
                        pUVRender.Symbol[strVal] = (ISymbol)pSymX;
                        //** All values get same symbol at first,
                        //** colors assigned later
                    }
                    i = i + 1;
                }

                //** Can size the color ramp and assign the colors, now that the
                //** number of unique values is known.

                pRamp.Size = pUVRender.ValueCount;
                bool blnRamp;
                pRamp.CreateRamp(out blnRamp);

                //** Create an enum of colors from the color ramp and initialize it
                IEnumColors pColors;
                pColors = pRamp.Colors;
                pColors.Reset();

                int y = 0;

                //** Loop through each unique value, setting its symbol's color
                for (y = 0; y <= (pUVRender.ValueCount - 1); y++)
                {
                    string strRendVal = null;
                    strRendVal = pUVRender.Value[y];
                    if (!string.IsNullOrEmpty(strRendVal))
                    {
                        ISimpleFillSymbol pSym;
                        pSym       = (ISimpleFillSymbol)pUVRender.Symbol[strRendVal];
                        pSym.Color = pColors.Next();
                        pUVRender.Symbol[strRendVal] = (ISymbol)pSym;
                    }
                }

                //** If you didn't use a color ramp that was predefined
                //** in a style, use "Custom" here, otherwise
                //** use the name of the color ramp you chose.
                pUVRender.ColorScheme  = "Custom";
                pUVRender.FieldType[0] = true;
                //** Set to True since Sub_region is a string

                pGeoFLayer.Renderer = (IFeatureRenderer)pUVRender;

                //** Make sure the symbology tab shows the correct info.
                IRendererPropertyPage pRendPropPage;
                pRendPropPage = (IRendererPropertyPage) new UniqueValuePropertyPage();
                pGeoFLayer.RendererPropertyPageClassID = pRendPropPage.ClassID;
            }
            else if (strChoice == "2")
            {
                //** User gets a graduated symbol map of U.S. Cities
                pFClass = pFeatureWorkspace.OpenFeatureClass("us_cities.shp");

                pFLayer.FeatureClass = pFClass;
                pFLayer.Name         = "Major U.S. Cities";
                pGeoFLayer           = (IGeoFeatureLayer)pFLayer;
                pMap.AddLayer(pFLayer);
                //** Switching to the ITable interface; FeatureClass is a type of Table
                pTable = (ITable)pFClass;

                //** Creating a new quantile classification
                pClasses = (IClassify) new Quantile();

                //** Must create a TableHistogram to generate classes
                //** Need both ITableHistogram and IHistogram interfaces
                pTableHist = (ITableHistogram) new TableHistogram();

                pHist = (IHistogram)pTableHist;


                //** Set the table and field for the histogram, then use GetHistogram to
                //** get arrays of values and corresponding frequencies
                pTableHist.Field = "POPCLASS";
                pTableHist.Table = pTable;
                pHist.GetHistogram(out Values, out Frequencies);

                //** Assign the arrays of values and frequencies to the quantile classification
                //** then break the data into 5 classes
                pClasses.SetHistogramData(Values, Frequencies);
                pClasses.Classify(4);

                double[] classBreaks = new double[4];
                classBreaks = (double[])pClasses.ClassBreaks;

                //** Ready to render the data
                pCBR = new ClassBreaksRenderer();

                pCBR.BreakCount = 4;

                pCBR.Field        = "POPCLASS";
                pCBR.MinimumBreak = classBreaks[0];
                //** ClassBreak(0) is min value of 1st class

                int j = 0;

                //** Loop thru each class, setting the renderers breaks
                //** The renderer's breaks are 0-based, quantile's breaks are 1-based
                for (j = 0; j <= (pCBR.BreakCount - 1); j++)
                {
                    pCBR.Break[j] = classBreaks[j + 1];
                    pCBR.Label[j] = classBreaks[j] + " - " + classBreaks[j + 1];
                }
                //** Ready for symbols
                ISimpleMarkerSymbol pCitySym;

                //** Setting the smallest symbol size
                double dblFromSize = 0;
                dblFromSize = 4;

                //** Setting the largest symbol size
                double dblToSize = 0;
                dblToSize = 16;

                //** Calculating the change in size between classes based on the min size,
                //** max size, and # of classes
                double dblStep = 0;
                dblStep = (dblToSize - dblFromSize) / (pCBR.BreakCount - 1);

                //** Setting the foreground color of the symbols
                IRgbColor pColor;
                pColor = new RgbColor();

                pColor.Red   = 179;
                pColor.Green = 235;
                pColor.Blue  = 255;

                //** Setting the outline color of the symbols
                //** No color settings means black outline (r=0, g=0, b=0)
                IRgbColor pOlColor;
                pOlColor = new RgbColor();

                int k = 0;

                //** Setting symbol for each class
                for (k = 0; k <= pCBR.BreakCount - 1; k++)
                {
                    pCitySym              = new SimpleMarkerSymbol();
                    pCitySym.Color        = pColor;
                    pCitySym.Outline      = true;
                    pCitySym.OutlineColor = pOlColor;
                    pCitySym.OutlineSize  = 1;
                    pCitySym.Size         = dblFromSize + (dblStep * Convert.ToDouble(k));
                    pCBR.Symbol[k]        = (ISymbol)pCitySym;
                }
                //** Assigning the ClassBreaksRenderer to the layer
                pGeoFLayer.Renderer       = (IFeatureRenderer)pCBR;
                pUIProperties             = (IClassBreaksUIProperties)pCBR;
                pUIProperties.LowBreak[0] = pCBR.MinimumBreak;

                int m = 0;
                for (m = 1; m <= pCBR.BreakCount - 1; m++)
                {
                    pUIProperties.LowBreak[m] = classBreaks[m];
                }
                //** Creating a heading for the legend in the Table of Contents
                pLegendInfo = (ILegendInfo)pCBR;
                //qi
                pLegendInfo.LegendGroup[0].Heading = "Population Class";
                pLegendInfo.SymbolsAreGraduated    = false;
            }
            else if (strChoice == "3")
            {
                //** User gets a graduated color map of state population normalized by area
                pFClass = pFeatureWorkspace.OpenFeatureClass("us_boundaries.shp");

                pFLayer.FeatureClass = pFClass;
                pFLayer.Name         = "State Polygon Area Rank";
                pGeoFLayer           = (IGeoFeatureLayer)pFLayer;
                pMap.AddLayer(pFLayer);
                //** Very similar to previous example

                pTable   = (ITable)pFClass;
                pClasses = (IClassify) new Quantile();

                pTableHist = (ITableHistogram) new TableHistogram();
                pHist      = (IHistogram)pTableHist;

                pTableHist.Field = "Shape_Area";
                pTableHist.Table = pTable;
                //pTableHist.NormField = "Rank" '** Setting the normalization field before getting histogram
                pHist.GetHistogram(out Values, out Frequencies);

                pClasses.SetHistogramData(Values, Frequencies);
                pClasses.Classify(5);

                double[] classBreaks = new double[4];
                classBreaks = (double[])pClasses.ClassBreaks;

                pCBR = new ClassBreaksRenderer();

                //** Making normalization settings for the renderer
                //Dim pNorm As IDataNormalization
                //pNorm = pCBR
                //pNorm.NormalizationField = "Rank"
                //pNorm.NormalizationType = esriDataNormalization.esriNormalizeByField

                pCBR.BreakCount   = 5;
                pCBR.Field        = "Shape_Area";
                pCBR.MinimumBreak = classBreaks[0];

                int t = 0;

                pUIProperties             = (IClassBreaksUIProperties)pCBR;
                pUIProperties.LowBreak[0] = pCBR.MinimumBreak;

                for (t = 0; t <= Information.UBound(classBreaks) - 1; t++)
                {
                    pCBR.Break[t] = classBreaks[t + 1];

                    //** Want to round the class break values in the class labels
                    //** Use the NumericFormat class to set up a 1-decimal format
                    INumericFormat pNumericFormat;
                    pNumericFormat = (INumericFormat) new NumericFormat();
                    pNumericFormat.RoundingOption = ESRI.ArcGIS.esriSystem.esriRoundingOptionEnum.esriRoundNumberOfDecimals;
                    pNumericFormat.RoundingValue  = 1;

                    INumberFormat pNumberFormat;
                    pNumberFormat = (INumberFormat)pNumericFormat;

                    string strRndVal1 = null;
                    string strRndVal2 = null;

                    //** Using ValueToString method to convert the numbers into the desired format
                    strRndVal1 = pNumberFormat.ValueToString(classBreaks[t]);
                    strRndVal2 = pNumberFormat.ValueToString(classBreaks[t + 1]);

                    pCBR.Label[t] = strRndVal1 + " - " + strRndVal2;
                }

                pGeoFLayer.Renderer = (IFeatureRenderer)pCBR;

                for (t = 1; t <= 4; t++)
                {
                    pUIProperties.LowBreak[t] = classBreaks[t];
                }
                //** Ready to set colors
                //** Want to use AlgorithmicColorRamp to ramp from one color to another
                IEnumColors           pColorEnum;
                IAlgorithmicColorRamp pAColorRamp;
                IRgbColor             pFromColor;
                IRgbColor             pToColor;

                //** Setting up the algorithmic color ramp
                pFromColor     = new RgbColor();
                pFromColor.RGB = Information.RGB(242, 233, 250);
                // lavender
                pToColor     = new RgbColor();
                pToColor.RGB = Information.RGB(56, 45, 121);
                // deep purple
                pAColorRamp = new AlgorithmicColorRamp();

                pAColorRamp.Algorithm = ESRI.ArcGIS.Display.esriColorRampAlgorithm.esriHSVAlgorithm;
                pAColorRamp.Size      = 5;
                //** # of classes
                pAColorRamp.FromColor = pFromColor;
                pAColorRamp.ToColor   = pToColor;
                bool blnRamp;
                pAColorRamp.CreateRamp(out blnRamp);
                pColorEnum = pAColorRamp.Colors;
                pColorEnum.Reset();

                int s = 0;

                //** Loop thru the classes, creating a new symbol, assigning the next color
                //** created by the ramp, and assigning the symbol to the renderer.
                for (s = 0; s <= 4; s++)
                {
                    ISimpleFillSymbol pSFSym;
                    pSFSym         = new SimpleFillSymbol();
                    pSFSym.Color   = pColorEnum.Next();
                    pCBR.Symbol[s] = (ISymbol)pSFSym;
                }

                //** Creating a heading for the legend in the Table of Contents
                pLegendInfo = (ILegendInfo)pCBR;
                //qi
                pLegendInfo.LegendGroup[0].Heading = "Area (Degrees)";
                pLegendInfo.SymbolsAreGraduated    = false;
            }
            //** Refreshing the Table of Contents
            pMxDoc.ActiveView.ContentsChanged();
            pMxDoc.UpdateContents();

            //** Re-drawing the map
            pMxDoc.ActiveView.Refresh();
        }
        private void createClassBreaksRendererSymbolsConfigControl(ClassBreaksRenderer classBreaksRenderer)
        {
            if (RendererSymbolSetContainerControl != null)
            {
                ClassBreaksRendererSymbolsConfigControl symbolsConfigControl = new ClassBreaksRendererSymbolsConfigControl()
                {
                    ClassBreaksRenderer = classBreaksRenderer,
                    SymbolConfigProvider = SymbolConfigProvider,
                    GeometryType = GeometryType,
                };

                Binding b = new Binding("Foreground") { Source = this };
                symbolsConfigControl.SetBinding(ClassBreaksRendererSymbolsConfigControl.ForegroundProperty, b);

                symbolsConfigControl.ClassBreakRendererModified += new EventHandler<SelectedClassBreakModificationEventArgs>(symbolsConfigControl_ClassBreakRendererModified);
                symbolsConfigControl.CurrentClassBreakChanged += new EventHandler<CurrentClassBreakChangedEventArgs>(symbolsConfigControl_CurrentClassBreakChanged);
                symbolsConfigControl.DefaultClassBreakBeingConfigured += new EventHandler<DefaultClassBreakBeingConfiguredEventArgs>(symbolsConfigControl_DefaultClassBreakBeingConfigured);
                RendererSymbolSetContainerControl.Content = symbolsConfigControl;
            }
        }
コード例 #12
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            //Choropleth mapping : Exactly same with the function in frmChoroplethwithOverlay HK102915
            string strLayerName = cboSourceLayer.Text;

            if (cboSourceLayer.Text == "" || cboValueField.Text == "" || cboUField.Text == "")
            {
                MessageBox.Show("Assign proper layer and field");
                return;
            }

            int    intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName);
            ILayer pLayer    = mForm.axMapControl1.get_Layer(intLIndex);

            IFeatureLayer pFLayer = pLayer as IFeatureLayer;
            IFeatureClass pFClass = pFLayer.FeatureClass;

            //Create Rendering of Mean Value at Target Layer
            int    intGCBreakeCount = Convert.ToInt32(nudGCNClasses.Value);
            string strGCRenderField = cboValueField.Text;

            IGeoFeatureLayer pGeofeatureLayer;

            pGeofeatureLayer = (IGeoFeatureLayer)pFLayer;

            ITable       pTable = (ITable)pFClass;
            IClassifyGEN pClassifyGEN;

            switch (cboGCClassify.Text)
            {
            case "Equal Interval":
                pClassifyGEN = new EqualIntervalClass();
                break;

            case "Geometrical Interval":
                pClassifyGEN = new GeometricalInterval();
                break;

            case "Natural Breaks":
                pClassifyGEN = new NaturalBreaksClass();
                break;

            case "Quantile":
                pClassifyGEN = new QuantileClass();
                break;

            case "StandardDeviation":
                pClassifyGEN = new StandardDeviationClass();
                break;

            default:
                pClassifyGEN = new NaturalBreaksClass();
                break;
            }

            //Need to be changed 1/29/15
            ITableHistogram pTableHistogram = new TableHistogramClass();

            pTableHistogram.Field = strGCRenderField;
            pTableHistogram.Table = pTable;
            IHistogram pHistogram = (IHistogram)pTableHistogram;

            object xVals, frqs;

            pHistogram.GetHistogram(out xVals, out frqs);
            pClassifyGEN.Classify(xVals, frqs, intGCBreakeCount);

            ClassBreaksRenderer pRender = new ClassBreaksRenderer();

            double[] cb = (double[])pClassifyGEN.ClassBreaks;
            pRender.Field        = strGCRenderField;
            pRender.BreakCount   = intGCBreakeCount;
            pRender.MinimumBreak = cb[0];

            //' create our color ramp
            IAlgorithmicColorRamp pColorRamp = new AlgorithmicColorRampClass();

            pColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm;
            IRgbColor pColor1 = new RgbColor();
            IRgbColor pColor2 = new RgbColor();

            //Can Change the color in here!
            pColor1.Red   = picSymolfrom.BackColor.R;
            pColor1.Green = picSymolfrom.BackColor.G;
            pColor1.Blue  = picSymolfrom.BackColor.B;

            Boolean blnOK = true;

            pColor2.Red          = picSymbolTo.BackColor.R;
            pColor2.Green        = picSymbolTo.BackColor.G;
            pColor2.Blue         = picSymbolTo.BackColor.B;
            pColorRamp.FromColor = pColor1;
            pColorRamp.ToColor   = pColor2;
            pColorRamp.Size      = intGCBreakeCount;
            pColorRamp.CreateRamp(out blnOK);

            IEnumColors pEnumColors = pColorRamp.Colors;

            pEnumColors.Reset();

            IRgbColor pColorOutline = new RgbColor();

            //Can Change the color in here!
            pColorOutline.Red   = picGCLineColor.BackColor.R;
            pColorOutline.Green = picGCLineColor.BackColor.G;
            pColorOutline.Blue  = picGCLineColor.BackColor.B;
            double dblGCOutlineSize = Convert.ToDouble(nudGCLinewidth.Value);

            ICartographicLineSymbol pOutLines = new CartographicLineSymbol();

            pOutLines.Width = dblGCOutlineSize;
            pOutLines.Color = (IColor)pColorOutline;

            //' use this interface to set dialog properties
            IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pRender;

            pUIProperties.ColorRamp = "Custom";

            ISimpleFillSymbol pSimpleFillSym;

            //' be careful, indices are different for the diff lists
            for (int j = 0; j < intGCBreakeCount; j++)
            {
                pRender.Break[j]          = cb[j + 1];
                pRender.Label[j]          = Math.Round(cb[j], 2).ToString() + " - " + Math.Round(cb[j + 1], 2).ToString();
                pUIProperties.LowBreak[j] = cb[j];
                pSimpleFillSym            = new SimpleFillSymbolClass();
                pSimpleFillSym.Color      = pEnumColors.Next();
                pSimpleFillSym.Outline    = pOutLines;
                pRender.Symbol[j]         = (ISymbol)pSimpleFillSym;
            }
            pGeofeatureLayer.Renderer = (IFeatureRenderer)pRender;


            //////////////////The Robustness
            int    intRoundingDigits   = 2;
            int    intUncernBreakCount = Convert.ToInt32(nudTeNClasses.Value);
            string strUncerFieldName   = cboUField.Text;

            int intUncernIdx = pFClass.FindField(strUncerFieldName);
            int intValueIdx  = pFClass.FindField(strGCRenderField);

            //Calculate Robustness
            //Add fld
            int    intTempfldIdx  = 0;
            string strTempfldName = txtFldName.Text;

            if (chkRobustness.Checked)
            {
                if (pFClass.FindField(strTempfldName) == -1)
                {
                    AddField(pFClass, strTempfldName);
                }
                intTempfldIdx = pFClass.FindField(strTempfldName);
            }

            Chart pChart = new Chart();

            IFeature pFeat = null;
            //IFeatureCursor pFCursor = pFClass.Search(null, false);
            IFeatureCursor pFCursor = null;

            if (chkRobustness.Checked)
            {
                pFCursor = pFClass.Update(null, false);
            }
            else
            {
                pFCursor = pFClass.Search(null, false);
            }

            pFeat = pFCursor.NextFeature();
            double[] arrRobustness = new double[pFClass.FeatureCount(null)];

            int i = 0;

            while (pFeat != null)
            {
                for (int j = 0; j < (cb.Length - 1); j++)
                {
                    double dblValue = Convert.ToDouble(pFeat.get_Value(intValueIdx));
                    double dblStd   = Convert.ToDouble(pFeat.get_Value(intUncernIdx));
                    if (j == 0)
                    {
                        if (dblValue >= cb[j] && dblValue <= cb[j + 1])
                        {
                            double dblUpperZvalue  = (cb[j + 1] - dblValue) / dblStd;
                            double dblUpperConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblUpperZvalue);
                            double dblLowerZvalue  = (cb[j] - dblValue) / dblStd;
                            double dblLowerConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblLowerZvalue);
                            arrRobustness[i] = dblUpperConfLev - dblLowerConfLev;
                            if (chkRobustness.Checked)
                            {
                                pFeat.set_Value(intTempfldIdx, arrRobustness[i]);
                            }
                        }
                    }
                    else
                    {
                        if (dblValue > cb[j] && dblValue <= cb[j + 1])
                        {
                            double dblUpperZvalue  = (cb[j + 1] - dblValue) / dblStd;
                            double dblUpperConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblUpperZvalue);
                            double dblLowerZvalue  = (cb[j] - dblValue) / dblStd;
                            double dblLowerConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblLowerZvalue);
                            arrRobustness[i] = dblUpperConfLev - dblLowerConfLev;
                            if (chkRobustness.Checked)
                            {
                                pFeat.set_Value(intTempfldIdx, arrRobustness[i]);
                            }
                        }
                    }
                }
                if (chkRobustness.Checked)
                {
                    pFCursor.UpdateFeature(pFeat);
                }

                i++;
                pFeat = pFCursor.NextFeature();
            }

            //Define the intervals (the last class is fixed to 1)
            if (intUncernBreakCount == 1)
            {
                return;
            }

            double[] arrRobustBrks     = new double[intUncernBreakCount + 1];
            double   dblRBrksIntervals = Math.Round(1 / Convert.ToDouble(intUncernBreakCount - 1), intRoundingDigits);

            arrRobustBrks[0] = 0;
            for (int j = 1; j < intUncernBreakCount; j++)
            {
                arrRobustBrks[j] = dblRBrksIntervals * j;
            }
            arrRobustBrks[intUncernBreakCount] = 1;



            IFeatureLayer pflUncern = new FeatureLayerClass();

            pflUncern.FeatureClass = pFClass;
            pflUncern.Name         = "Robustness";
            pflUncern.Visible      = true;

            IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern;

            pFCursor = pGFLUncern.Search(null, true);
            RobustnessRenderer pRobustnessRenderer = new RobustnessRenderer();

            pRobustnessRenderer.arrRobustBrks       = arrRobustBrks;
            pRobustnessRenderer.arrRobustness       = arrRobustness;
            pRobustnessRenderer.dblAngle            = Convert.ToDouble(nudAngleFrom.Value);
            pRobustnessRenderer.dblFromSep          = Convert.ToDouble(nudSeperationFrom.Value);
            pRobustnessRenderer.dblLinewidth        = Convert.ToDouble(nudTeLinewidth.Value);
            pRobustnessRenderer.dblToSep            = Convert.ToDouble(nudSeperationTo.Value);
            pRobustnessRenderer.intUncernBreakCount = intUncernBreakCount;
            pRobustnessRenderer.pLineColor          = pSnippet.getRGB(picTeLineColor.BackColor.R, picTeLineColor.BackColor.G, picTeLineColor.BackColor.B);
            IQueryFilter pQFilter = new QueryFilterClass();


            pRobustnessRenderer.PrepareFilter(pFClass, pQFilter);
            pRobustnessRenderer.Draw(pFCursor, esriDrawPhase.esriDPSelection, pActiveView.ScreenDisplay, null);
            pRobustnessRenderer.CreateLegend();
            pGFLUncern.Renderer = pRobustnessRenderer;

            pActiveView.FocusMap.AddLayer(pGFLUncern as ILayer);

            mForm.axMapControl1.ActiveView.Refresh();
            mForm.axTOCControl1.Update();
        }
コード例 #13
0
ファイル: Traffic.cs プロジェクト: Yanwei-Tim/BigMap.TaiDa
        private FeatureLayer flRoad;         //道路
        public Traffic()
        {
            try
            {
                flTrafficLight = MapLayers.GetFeatureLayerByID(PublicParams.fLayerTrafficLight);
                flRoad         = MapLayers.GetFeatureLayerByID(PublicParams.fLayerRoad);
                if (flTrafficLight == null || flRoad == null)
                {
                    return;
                }
            }
            catch (Exception)
            {
                LogHelper.WriteLog("Traffic初始化错误!");
                return;
            }

            flTrafficLight.OutFields = new OutFields {
                "*"
            };
            flRoad.OutFields = new OutFields {
                "*"
            };

            ClassBreaksRenderer cbrTrafficLight = new ClassBreaksRenderer();//红绿灯

            cbrTrafficLight.Field = "DLD_STATUS";
            ClassBreakInfo cbiRed = new ClassBreakInfo()
            {
                MinimumValue = 0, MaximumValue = 0, Symbol = PublicParams.symbolRedLight
            };
            ClassBreakInfo cbiYellow = new ClassBreakInfo()
            {
                MinimumValue = 1, MaximumValue = 1, Symbol = PublicParams.symbolYellowLight
            };
            ClassBreakInfo cbiGreen = new ClassBreakInfo()
            {
                MinimumValue = 2, MaximumValue = 2, Symbol = PublicParams.symbolGreenLight
            };

            cbrTrafficLight.Classes.Add(cbiRed); cbrTrafficLight.Classes.Add(cbiYellow); cbrTrafficLight.Classes.Add(cbiGreen);
            flTrafficLight.Renderer = cbrTrafficLight;

            ClassBreaksRenderer cbrRoad = new ClassBreaksRenderer();//道路

            cbrRoad.Field = "DL_COUNT";
            ClassBreakInfo cbiFree = new ClassBreakInfo()
            {
                MinimumValue = 0, MaximumValue = 100, Symbol = PublicParams.roadFreeSymbol
            };
            ClassBreakInfo cbiNormal = new ClassBreakInfo()
            {
                MinimumValue = 101, MaximumValue = 200, Symbol = PublicParams.roadNormalSymbol
            };
            ClassBreakInfo cbiBusy = new ClassBreakInfo()
            {
                MinimumValue = 201, MaximumValue = 1000, Symbol = PublicParams.roadBusySymbol
            };

            cbrRoad.Classes.Add(cbiFree); cbrRoad.Classes.Add(cbiNormal); cbrRoad.Classes.Add(cbiBusy);
            flRoad.Renderer = cbrRoad;



            Task taskInitTrafficLight = new Task(InitTrafficLight);

            taskInitTrafficLight.Start();

            Task taskInitRoad = new Task(InitRoad);

            taskInitRoad.Start();
        }
コード例 #14
0
        // Renderer
        internal static Dictionary <string, object> ToDictionary(this IRenderer renderer)
        {
            Dictionary <string, object> dictionary = new Dictionary <string, object>();

            if (renderer is SimpleRenderer)
            {
                dictionary.Add("type", "simple");
                SimpleRenderer simpleRenderer = (SimpleRenderer)renderer;
                if (!string.IsNullOrEmpty(simpleRenderer.Label))
                {
                    dictionary.Add("label", simpleRenderer.Label);
                }
                if (!string.IsNullOrEmpty(simpleRenderer.Description))
                {
                    dictionary.Add("description", simpleRenderer.Description);
                }
                if (simpleRenderer.Symbol is IJsonSerializable)
                {
                    dictionary.Add("symbol", ((IJsonSerializable)simpleRenderer.Symbol).ToJson());
                }
            }
            else if (renderer is UniqueValueRenderer)
            {
                dictionary.Add("type", "uniqueValue");

                UniqueValueRenderer uvRenderer = (UniqueValueRenderer)renderer;
                if (!string.IsNullOrEmpty(uvRenderer.Field))
                {
                    dictionary.Add("field1", uvRenderer.Field);
                }
                if (!string.IsNullOrEmpty(uvRenderer.DefaultLabel))
                {
                    dictionary.Add("defaultLabel", uvRenderer.DefaultLabel);
                }

                if (uvRenderer.DefaultSymbol is IJsonSerializable)
                {
                    dictionary.Add("defaultSymbol", ((IJsonSerializable)uvRenderer.DefaultSymbol).ToJson());
                }

                List <Dictionary <string, object> > uniqueValueInfos = new List <Dictionary <string, object> >();
                foreach (UniqueValueInfo info in uvRenderer.Infos)
                {
                    Dictionary <string, object> uniqueValueInfo = info.ToDictionary();
                    if (info.Value != null)
                    {
                        uniqueValueInfo.Add("value", info.Value);
                    }

                    uniqueValueInfos.Add(uniqueValueInfo);
                }
                dictionary.Add("uniqueValueInfos", uniqueValueInfos);
            }
            else if (renderer is UniqueValueMultipleFieldsRenderer)
            {
                dictionary.Add("type", "uniqueValue");

                UniqueValueMultipleFieldsRenderer multiValRenderer = (UniqueValueMultipleFieldsRenderer)renderer;
                if (multiValRenderer.Fields != null)
                {
                    if (multiValRenderer.Fields.Length > 0)
                    {
                        dictionary.Add("field1", multiValRenderer.Fields[0]);
                    }
                    if (multiValRenderer.Fields.Length > 1)
                    {
                        dictionary.Add("field2", multiValRenderer.Fields[1]);
                    }
                    if (multiValRenderer.Fields.Length > 2)
                    {
                        dictionary.Add("field3", multiValRenderer.Fields[2]);
                    }
                }
                if (!string.IsNullOrEmpty(multiValRenderer.FieldDelimiter))
                {
                    dictionary.Add("fieldDelimiter", multiValRenderer.FieldDelimiter);
                }
                if (!string.IsNullOrEmpty(multiValRenderer.DefaultLabel))
                {
                    dictionary.Add("defaultLabel", multiValRenderer.DefaultLabel);
                }

                if (multiValRenderer.DefaultSymbol is IJsonSerializable)
                {
                    dictionary.Add("defaultSymbol", ((IJsonSerializable)multiValRenderer.DefaultSymbol).ToJson());
                }

                List <Dictionary <string, object> > uniqueValueInfos = new List <Dictionary <string, object> >();
                foreach (UniqueValueMultipleFieldsInfo info in multiValRenderer.Infos)
                {
                    Dictionary <string, object> uniqueValueInfo = info.ToDictionary();
                    if (info.Values != null && !string.IsNullOrEmpty(multiValRenderer.FieldDelimiter))
                    {
                        uniqueValueInfo.Add("value", string.Join(multiValRenderer.FieldDelimiter, info.Values));
                    }

                    uniqueValueInfos.Add(uniqueValueInfo);
                }
                dictionary.Add("uniqueValueInfos", uniqueValueInfos);
            }
            else if (renderer is ClassBreaksRenderer)
            {
                dictionary.Add("type", "classBreaks");

                ClassBreaksRenderer cbRenderer = (ClassBreaksRenderer)renderer;
                if (!string.IsNullOrEmpty(cbRenderer.NormalizationField))
                {
                    dictionary.Add("normalizationField", cbRenderer.NormalizationField);
                }

                // CHECK TOSTRING VALUE
                dictionary.Add("normalizationType", "esriNormalizeBy" + cbRenderer.NormalizationType.ToString());

                dictionary.Add("normalizationTotal", cbRenderer.NormalizationTotal);

                if (!string.IsNullOrEmpty(cbRenderer.Field))
                {
                    dictionary.Add("field", cbRenderer.Field);
                }

                if (cbRenderer.DefaultSymbol is IJsonSerializable)
                {
                    dictionary.Add("defaultSymbol", ((IJsonSerializable)cbRenderer.DefaultSymbol).ToJson());
                }

                List <Dictionary <string, object> > classBreakInfos = new List <Dictionary <string, object> >();
                double overallMinValue = double.MaxValue;
                foreach (ClassBreakInfo info in cbRenderer.Classes)
                {
                    Dictionary <string, object> classBreakInfo = info.ToDictionary();
                    classBreakInfo.Add("classMinValue", info.MinimumValue);
                    classBreakInfo.Add("classMaxValue", info.MaximumValue);
                    if (info.MinimumValue < overallMinValue)
                    {
                        overallMinValue = info.MinimumValue;
                    }

                    classBreakInfos.Add(classBreakInfo);
                }
                dictionary.Add("minValue", overallMinValue);
                dictionary.Add("classBreakInfos", classBreakInfos);
            }

            return(dictionary);
        }
コード例 #15
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            try
            {
                clsSnippet  pSnippet     = new clsSnippet();
                IActiveView pActiveView  = ArcMap.Document.ActiveView;
                string      strLayerName = cboSourceLayer.Text;
                if (cboSourceLayer.Text == "" || cboValueField.Text == "" || cboUField.Text == "")
                {
                    MessageBox.Show("Assign proper layer and field");
                    return;
                }

                int    intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName);
                ILayer pLayer    = pActiveView.FocusMap.get_Layer(intLIndex);

                IFeatureLayer pFLayer = pLayer as IFeatureLayer;
                IFeatureClass pFClass = pFLayer.FeatureClass;

                //Create Rendering of Mean Value at Target Layer
                int    intGCBreakeCount = Convert.ToInt32(nudGCNClasses.Value);
                string strGCRenderField = cboValueField.Text;

                IGeoFeatureLayer pGeofeatureLayer;
                if (chkNewLayer.Checked == true)
                {
                    IFeatureLayer pflOutput = new FeatureLayerClass();
                    pflOutput.FeatureClass = pFClass;
                    pflOutput.Name         = txtNewLayer.Text;
                    pflOutput.Visible      = true;

                    pGeofeatureLayer = (IGeoFeatureLayer)pflOutput;
                }
                else
                {
                    pGeofeatureLayer = (IGeoFeatureLayer)pFLayer;
                }

                ITable       pTable = (ITable)pFClass;
                IClassifyGEN pClassifyGEN;
                switch (cboGCClassify.Text)
                {
                case "Equal Interval":
                    pClassifyGEN = new EqualIntervalClass();
                    break;

                case "Geometrical Interval":
                    pClassifyGEN = new GeometricalInterval();
                    break;

                case "Natural Breaks":
                    pClassifyGEN = new NaturalBreaksClass();
                    break;

                case "Quantile":
                    pClassifyGEN = new QuantileClass();
                    break;

                case "StandardDeviation":
                    pClassifyGEN = new StandardDeviationClass();
                    break;

                default:
                    pClassifyGEN = new NaturalBreaksClass();
                    break;
                }

                //Need to be changed 1/29/15
                ITableHistogram pTableHistogram = new BasicTableHistogramClass();
                pTableHistogram.Field = strGCRenderField;
                pTableHistogram.Table = pTable;
                IBasicHistogram pHistogram = (IBasicHistogram)pTableHistogram;

                object xVals, frqs;
                pHistogram.GetHistogram(out xVals, out frqs);
                pClassifyGEN.Classify(xVals, frqs, intGCBreakeCount);

                ClassBreaksRenderer pRender = new ClassBreaksRenderer();
                double[]            cb      = (double[])pClassifyGEN.ClassBreaks;
                pRender.Field        = strGCRenderField;
                pRender.BreakCount   = intGCBreakeCount;
                pRender.MinimumBreak = cb[0];

                //' create our color ramp
                IAlgorithmicColorRamp pColorRamp = new AlgorithmicColorRampClass();
                pColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm;
                IRgbColor pColor1 = new RgbColor();
                IRgbColor pColor2 = new RgbColor();

                //Can Change the color in here!
                pColor1.Red   = picSymolfrom.BackColor.R;
                pColor1.Green = picSymolfrom.BackColor.G;
                pColor1.Blue  = picSymolfrom.BackColor.B;

                Boolean blnOK = true;
                pColor2.Red          = picSymbolTo.BackColor.R;
                pColor2.Green        = picSymbolTo.BackColor.G;
                pColor2.Blue         = picSymbolTo.BackColor.B;
                pColorRamp.FromColor = pColor1;
                pColorRamp.ToColor   = pColor2;
                pColorRamp.Size      = intGCBreakeCount;
                pColorRamp.CreateRamp(out blnOK);

                IEnumColors pEnumColors = pColorRamp.Colors;
                pEnumColors.Reset();

                IRgbColor pColorOutline = new RgbColor();
                //Can Change the color in here!
                pColorOutline.Red   = picGCLineColor.BackColor.R;
                pColorOutline.Green = picGCLineColor.BackColor.G;
                pColorOutline.Blue  = picGCLineColor.BackColor.B;
                double dblGCOutlineSize = Convert.ToDouble(nudGCLinewidth.Value);

                ICartographicLineSymbol pOutLines = new CartographicLineSymbol();
                pOutLines.Width = dblGCOutlineSize;
                pOutLines.Color = (IColor)pColorOutline;

                //' use this interface to set dialog properties
                IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pRender;
                pUIProperties.ColorRamp = "Custom";

                ISimpleFillSymbol pSimpleFillSym;
                //' be careful, indices are different for the diff lists
                for (int j = 0; j < intGCBreakeCount; j++)
                {
                    pRender.Break[j]          = cb[j + 1];
                    pRender.Label[j]          = Math.Round(cb[j], 2).ToString() + " - " + Math.Round(cb[j + 1], 2).ToString();
                    pUIProperties.LowBreak[j] = cb[j];
                    pSimpleFillSym            = new SimpleFillSymbolClass();
                    pSimpleFillSym.Color      = pEnumColors.Next();
                    pSimpleFillSym.Outline    = pOutLines;
                    pRender.Symbol[j]         = (ISymbol)pSimpleFillSym;
                }
                pGeofeatureLayer.Renderer = (IFeatureRenderer)pRender;
                if (chkNewLayer.Checked == true)
                {
                    pActiveView.FocusMap.AddLayer(pGeofeatureLayer);
                }



                ////* Uncertainty Part *////
                //Declare variables in if parts

                if (tcUncern.SelectedIndex == 0) //Graduated Color
                {
                    int    intUncernBreakCount = Convert.ToInt32(nudCoNClasses.Value);
                    string strUncerFieldName   = cboUField.Text;

                    IFeatureLayer pflUncern = new FeatureLayerClass();
                    pflUncern.FeatureClass = pFClass;
                    pflUncern.Name         = cboSourceLayer.Text + " Uncertainty";
                    pflUncern.Visible      = true;

                    IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern;
                    switch (cboTeClassify.Text)
                    {
                    case "Equal Interval":
                        pClassifyGEN = new EqualIntervalClass();
                        break;

                    case "Geometrical Interval":
                        pClassifyGEN = new GeometricalInterval();
                        break;

                    case "Natural Breaks":
                        pClassifyGEN = new NaturalBreaksClass();
                        break;

                    case "Quantile":
                        pClassifyGEN = new QuantileClass();
                        break;

                    case "StandardDeviation":
                        pClassifyGEN = new StandardDeviationClass();
                        break;

                    default:
                        pClassifyGEN = new NaturalBreaksClass();
                        break;
                    }
                    //Need to be changed 1/29/15
                    pTableHistogram       = new BasicTableHistogramClass();
                    pTableHistogram.Field = strUncerFieldName;
                    pTableHistogram.Table = pTable;
                    pHistogram            = (IBasicHistogram)pTableHistogram;

                    pHistogram.GetHistogram(out xVals, out frqs);
                    pClassifyGEN.Classify(xVals, frqs, intUncernBreakCount);

                    pRender              = new ClassBreaksRenderer();
                    cb                   = (double[])pClassifyGEN.ClassBreaks;
                    pRender.Field        = strUncerFieldName;
                    pRender.BreakCount   = intUncernBreakCount;
                    pRender.MinimumBreak = cb[0];

                    IClassBreaksUIProperties pUIColProperties = (IClassBreaksUIProperties)pRender;
                    pUIColProperties.ColorRamp = "Custom";

                    pColorRamp           = new AlgorithmicColorRampClass();
                    pColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm;
                    pColor1 = new RgbColor();
                    pColor2 = new RgbColor();

                    //Can Change the color in here!
                    pColor1 = pSnippet.getRGB(picCoColorFrom.BackColor.R, picCoColorFrom.BackColor.G, picCoColorFrom.BackColor.B);
                    pColor2 = pSnippet.getRGB(picCoColorTo.BackColor.R, picCoColorTo.BackColor.G, picCoColorTo.BackColor.B);
                    if (pColor1 == null || pColor2 == null)
                    {
                        return;
                    }

                    blnOK = true;
                    pColorRamp.FromColor = pColor1;
                    pColorRamp.ToColor   = pColor2;
                    pColorRamp.Size      = intUncernBreakCount;
                    pColorRamp.CreateRamp(out blnOK);

                    pEnumColors = pColorRamp.Colors;
                    pEnumColors.Reset();

                    pColorOutline = pSnippet.getRGB(picCoLineColor.BackColor.R, picCoLineColor.BackColor.G, picCoLineColor.BackColor.B);
                    if (pColorOutline == null)
                    {
                        return;
                    }

                    double dblCoOutlineSize = Convert.ToDouble(nudCoLinewidth.Value);

                    pOutLines       = new CartographicLineSymbol();
                    pOutLines.Width = dblCoOutlineSize;
                    pOutLines.Color = (IColor)pColorOutline;

                    //' use this interface to set dialog properties
                    pUIColProperties           = (IClassBreaksUIProperties)pRender;
                    pUIColProperties.ColorRamp = "Custom";

                    ISimpleMarkerSymbol pSimpleMarkerSym;
                    double dblCoSymSize = Convert.ToDouble(nudCoSymbolSize.Value);
                    //' be careful, indices are different for the diff lists
                    for (int j = 0; j < intUncernBreakCount; j++)
                    {
                        pRender.Break[j]              = cb[j + 1];
                        pRender.Label[j]              = Math.Round(cb[j], 2).ToString() + " - " + Math.Round(cb[j + 1], 2).ToString();
                        pUIColProperties.LowBreak[j]  = cb[j];
                        pSimpleMarkerSym              = new SimpleMarkerSymbolClass();
                        pSimpleMarkerSym.Size         = dblCoSymSize;
                        pSimpleMarkerSym.Color        = pEnumColors.Next();
                        pSimpleMarkerSym.Outline      = true;
                        pSimpleMarkerSym.OutlineColor = pColorOutline;
                        pSimpleMarkerSym.OutlineSize  = dblCoOutlineSize;
                        pRender.Symbol[j]             = (ISymbol)pSimpleMarkerSym;
                    }

                    pGFLUncern.Renderer = (IFeatureRenderer)pRender;
                    pActiveView.FocusMap.AddLayer(pGFLUncern);
                }
                else if (tcUncern.SelectedIndex == 1) //Texture
                {
                    //Create Rendering of Uncertainty at Target Layer
                    int    intUncernBreakCount = Convert.ToInt32(nudTeNClasses.Value);
                    string strUncerFieldName   = cboUField.Text;

                    IFeatureLayer pflUncern = new FeatureLayerClass();
                    pflUncern.FeatureClass = pFClass;
                    pflUncern.Name         = cboSourceLayer.Text + " Uncertainty";
                    pflUncern.Visible      = true;

                    IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern;
                    switch (cboTeClassify.Text)
                    {
                    case "Equal Interval":
                        pClassifyGEN = new EqualIntervalClass();
                        break;

                    case "Geometrical Interval":
                        pClassifyGEN = new GeometricalInterval();
                        break;

                    case "Natural Breaks":
                        pClassifyGEN = new NaturalBreaksClass();
                        break;

                    case "Quantile":
                        pClassifyGEN = new QuantileClass();
                        break;

                    case "StandardDeviation":
                        pClassifyGEN = new StandardDeviationClass();
                        break;

                    default:
                        pClassifyGEN = new NaturalBreaksClass();
                        break;
                    }
                    //Need to be changed 1/29/15
                    pTableHistogram       = new BasicTableHistogramClass();
                    pTableHistogram.Field = strUncerFieldName;
                    pTableHistogram.Table = pTable;
                    pHistogram            = (IBasicHistogram)pTableHistogram;

                    pHistogram.GetHistogram(out xVals, out frqs);
                    pClassifyGEN.Classify(xVals, frqs, intUncernBreakCount);

                    pRender              = new ClassBreaksRenderer();
                    cb                   = (double[])pClassifyGEN.ClassBreaks;
                    pRender.Field        = strUncerFieldName;
                    pRender.BreakCount   = intUncernBreakCount;
                    pRender.MinimumBreak = cb[0];

                    IClassBreaksUIProperties pUITexProperties = (IClassBreaksUIProperties)pRender;
                    pUITexProperties.ColorRamp = "Custom";

                    ILineFillSymbol pLineFillSym    = new LineFillSymbolClass();
                    double          dblFromSep      = Convert.ToDouble(nudSeperationFrom.Value);
                    double          dblToSep        = Convert.ToDouble(nudSeperationTo.Value);
                    double          dblInstantSep   = (dblFromSep - dblToSep) / Convert.ToDouble(intUncernBreakCount - 1);
                    double          dblFromAngle    = Convert.ToDouble(nudAngleFrom.Value);
                    double          dblToAngle      = Convert.ToDouble(nudAngleFrom.Value); // Remove the angle part (04/16)
                    double          dblInstantAngle = (dblToAngle - dblFromAngle) / Convert.ToDouble(intUncernBreakCount - 1);
                    double          dblLinewidth    = Convert.ToDouble(nudTeLinewidth.Value);
                    IRgbColor       pLineColor      = new RgbColor();
                    pLineColor.Red   = picTeLineColor.BackColor.R;
                    pLineColor.Green = picTeLineColor.BackColor.G;
                    pLineColor.Blue  = picTeLineColor.BackColor.B;

                    //' be careful, indices are different for the diff lists
                    for (int j = 0; j < intUncernBreakCount; j++)
                    {
                        pRender.Break[j]             = cb[j + 1];
                        pRender.Label[j]             = Math.Round(cb[j], 5).ToString() + " - " + Math.Round(cb[j + 1], 5).ToString();
                        pUITexProperties.LowBreak[j] = cb[j];
                        pLineFillSym                  = new LineFillSymbolClass();
                        pLineFillSym.Angle            = dblFromAngle + (dblInstantAngle * Convert.ToDouble(j));
                        pLineFillSym.Color            = pLineColor;
                        pLineFillSym.Separation       = dblFromSep - (dblInstantSep * Convert.ToDouble(j));
                        pLineFillSym.LineSymbol.Width = dblLinewidth;
                        pRender.Symbol[j]             = (ISymbol)pLineFillSym;
                    }
                    pGFLUncern.Renderer = (IFeatureRenderer)pRender;
                    pActiveView.FocusMap.AddLayer(pGFLUncern);
                }
                else if (tcUncern.SelectedIndex == 2) //For Proportional Symbols
                {
                    string strUncerFieldName = cboUField.Text;
                    double dblMinPtSize      = Convert.ToDouble(nudProSymbolSize.Value);
                    double dblLineWidth      = Convert.ToDouble(nudProLinewidth.Value);

                    IFeatureLayer pflUncern = new FeatureLayerClass();
                    pflUncern.FeatureClass = pFClass;
                    pflUncern.Name         = cboSourceLayer.Text + " Uncertainty";
                    pflUncern.Visible      = true;

                    //Find Fields
                    int intUncernIdx = pTable.FindField(strUncerFieldName);

                    //Find Min value
                    //Set to initial value for min
                    IField          pUncernField = pTable.Fields.get_Field(intUncernIdx);
                    ICursor         pCursor      = pTable.Search(null, false);
                    IDataStatistics pDataStat    = new DataStatisticsClass();
                    pDataStat.Field  = pUncernField.Name;
                    pDataStat.Cursor = pCursor;
                    IStatisticsResults pStatResults = pDataStat.Statistics;
                    double             dblMinValue  = pStatResults.Minimum;
                    double             dblMaxValue  = pStatResults.Maximum;
                    pCursor.Flush();


                    IRgbColor pSymbolRgb = pSnippet.getRGB(picProSymbolColor.BackColor.R, picProSymbolColor.BackColor.G, picProSymbolColor.BackColor.B);
                    if (pSymbolRgb == null)
                    {
                        return;
                    }

                    IRgbColor pLineRgb = pSnippet.getRGB(picProiLineColor.BackColor.R, picProiLineColor.BackColor.G, picProiLineColor.BackColor.B);
                    if (pLineRgb == null)
                    {
                        return;
                    }

                    ISimpleMarkerSymbol pSMarkerSym = new SimpleMarkerSymbolClass();
                    pSMarkerSym.Style        = esriSimpleMarkerStyle.esriSMSCircle;
                    pSMarkerSym.Size         = dblMinPtSize;
                    pSMarkerSym.OutlineSize  = dblLineWidth;
                    pSMarkerSym.Outline      = true;
                    pSMarkerSym.OutlineColor = (IColor)pLineRgb;
                    pSMarkerSym.Color        = (IColor)pSymbolRgb;

                    IGeoFeatureLayer            pGFLUncern    = (IGeoFeatureLayer)pflUncern;
                    IProportionalSymbolRenderer pUncernRender = new ProportionalSymbolRendererClass();
                    pUncernRender.LegendSymbolCount = 2; //Need to be changed 0219
                    pUncernRender.Field             = strUncerFieldName;
                    pUncernRender.MaxDataValue      = dblMaxValue;
                    pUncernRender.MinDataValue      = dblMinValue;
                    pUncernRender.MinSymbol         = (ISymbol)pSMarkerSym;
                    pUncernRender.ValueUnit         = esriUnits.esriUnknownUnits;
                    pUncernRender.BackgroundSymbol  = null;
                    pUncernRender.CreateLegendSymbols();

                    pGFLUncern.Renderer = (IFeatureRenderer)pUncernRender;
                    pActiveView.FocusMap.AddLayer(pGFLUncern);
                }
                else if (tcUncern.SelectedIndex == 3) // Bar
                {
                    string strUncerFieldName = cboUField.Text;
                    double dblMaxLength      = Convert.ToDouble(nudMaxBarHeight.Value);
                    double dblBarWidth       = Convert.ToDouble(nudBarWidth.Value);

                    IFeatureLayer pflUncern = new FeatureLayerClass();
                    pflUncern.FeatureClass = pFClass;
                    pflUncern.Name         = cboSourceLayer.Text + " Uncertainty";
                    pflUncern.Visible      = true;

                    int             intUncernIdx = pTable.FindField(strUncerFieldName);
                    IField          pUncernField = pTable.Fields.get_Field(intUncernIdx);
                    ICursor         pCursor      = pTable.Search(null, false);
                    IDataStatistics pDataStat    = new DataStatisticsClass();
                    pDataStat.Field  = pUncernField.Name;
                    pDataStat.Cursor = pCursor;
                    IStatisticsResults pStatResults = pDataStat.Statistics;
                    double             dblMaxValue  = pStatResults.Maximum;
                    pCursor.Flush();


                    IChartRenderer  chartRenderer  = new ChartRendererClass();
                    IRendererFields rendererFields = chartRenderer as IRendererFields;
                    rendererFields.AddField(strUncerFieldName);

                    IBarChartSymbol barChartSymbol = new BarChartSymbolClass();
                    barChartSymbol.Width = dblBarWidth;
                    IMarkerSymbol markerSymbol = barChartSymbol as IMarkerSymbol;
                    markerSymbol.Size = dblMaxLength;
                    IChartSymbol chartSymbol = barChartSymbol as IChartSymbol;
                    chartSymbol.MaxValue = dblMaxValue;
                    ISymbolArray symbolArray = barChartSymbol as ISymbolArray;
                    IFillSymbol  fillSymbol  = new SimpleFillSymbolClass();
                    fillSymbol.Color = pSnippet.getRGB(picBarSymCol.BackColor.R, picBarSymCol.BackColor.G, picBarSymCol.BackColor.B);
                    if (fillSymbol.Color == null)
                    {
                        return;
                    }
                    symbolArray.AddSymbol(fillSymbol as ISymbol);

                    if (chk3D.Checked)
                    {
                        I3DChartSymbol p3DChartSymbol = barChartSymbol as I3DChartSymbol;
                        p3DChartSymbol.Display3D = true;
                        p3DChartSymbol.Thickness = 3;
                    }
                    chartRenderer.ChartSymbol = barChartSymbol as IChartSymbol;
                    SimpleFillSymbol pBaseFillSym = new SimpleFillSymbolClass();
                    //pBaseFillSym.Color = pSnippet.getRGB(picBarSymCol.BackColor.R, picBarSymCol.BackColor.G, picBarSymCol.BackColor.B);
                    //chartRenderer.BaseSymbol = pBaseFillSym as ISymbol;
                    chartRenderer.UseOverposter = false;
                    chartRenderer.CreateLegend();
                    IGeoFeatureLayer pGFLUncern = (IGeoFeatureLayer)pflUncern;
                    pGFLUncern.Renderer = (IFeatureRenderer)chartRenderer;
                    pActiveView.FocusMap.AddLayer(pGFLUncern);
                }
                #region illumination
                //This function is not applied in this version. 032317 HK
                //}
                //    else if (tcUncern.SelectedIndex == 4) //illumination
                //    {
                //        frmProgress pfrmProgress = new frmProgress();
                //        pfrmProgress.lblStatus.Text = "Processing:";
                //        pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                //        pfrmProgress.Show();

                //        string strUncerFieldName = cboUField.Text;

                //        IGeoDataset geoDataset_output = createRasterfromPolygon(pFClass, strUncerFieldName, pFLayer, 100);

                //        double altitude = Convert.ToDouble(nudAltitude.Value);
                //        double azimuth = Convert.ToDouble(nudAzimuth.Value);
                //        object zFactor = Convert.ToDouble(nudZFactor.Value);


                //        ISurfaceOp2 pSurfOP = new RasterSurfaceOpClass();
                //        IRaster pOutputDS = (IRaster)pSurfOP.HillShade(geoDataset_output, azimuth, altitude, true, ref zFactor);

                //        ((IDataset)geoDataset_output).Delete();
                //        // Create a raster for viewing
                //        ESRI.ArcGIS.Carto.IRasterLayer rasterLayer = new ESRI.ArcGIS.Carto.RasterLayerClass();
                //        rasterLayer.CreateFromRaster(pOutputDS);

                //        //Calculate hillshade value at slope 0 to set as background value
                //        double dblRadian = (Math.PI / 180) * (90 - altitude);
                //        double dblBackValue = Math.Truncate(255 * Math.Cos(dblRadian));

                //        IRasterStretch pRasterStretch = new RasterStretchColorRampRendererClass();
                //        IColor pColor = new RgbColorClass();
                //        pColor.NullColor = true;
                //        pColor.Transparency = 0;
                //        pRasterStretch.Background = true;
                //        pRasterStretch.BackgroundColor = pColor;
                //        pRasterStretch.set_BackgroundValues(ref dblBackValue);

                //        rasterLayer.Name = "Uncertainty of " + strGCRenderField;
                //        rasterLayer.Renderer = pRasterStretch as IRasterRenderer;
                //        rasterLayer.Renderer.Update();

                //        //Apply Transparency
                //        ILayerEffects pLayerEffect = (ILayerEffects)rasterLayer;
                //        pLayerEffect.Transparency = Convert.ToInt16(nudTransparent.Value);

                //        pfrmProgress.Close();
                //        // Add the raster to the map
                //        pActiveView.FocusMap.AddLayer(rasterLayer);

                //    }

                //    mForm.axMapControl1.ActiveView.Refresh();
                //    mForm.axTOCControl1.Update();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unexpected Error");
                return;
            }
        }
コード例 #16
0
        private void PerformPostLayerInitializationActions(Layer layer, bool initializationSuccess)
        {
            GraphicsLayer gLayer = layer as GraphicsLayer;

            if (gLayer != null)
            {
                GeometryType           geometryType = Core.LayerExtensions.GetGeometryType(gLayer);
                Collection <FieldInfo> layerFields  = Core.LayerExtensions.GetFields(gLayer);
                FeatureLayer           featureLayer = layer as FeatureLayer;
                if (layerFields.Count == 0 &&
                    featureLayer != null && featureLayer.LayerInfo != null && featureLayer.LayerInfo.Fields != null)
                {
                    foreach (ESRI.ArcGIS.Client.Field field in featureLayer.LayerInfo.Fields)
                    {
                        if (FieldHelper.IsFieldFilteredOut(field.Type))
                        {
                            continue;
                        }
                        ESRI.ArcGIS.Mapping.Core.FieldInfo fieldInfo = ESRI.ArcGIS.Mapping.Core.FieldInfo.FieldInfoFromField(featureLayer, field);
                        layerFields.Add(fieldInfo);
                    }
                }
                if (gLayer.Graphics != null)
                {
                    #region Get geometry type, start getting symbology
                    if (geometryType == GeometryType.Unknown && gLayer.Graphics.Count > 0)
                    {
                        geometryType = LayerUtils.GetGeometryTypeFromGraphic(gLayer.Graphics.ElementAtOrDefault(0));
                        Core.LayerExtensions.SetGeometryType(gLayer, geometryType);

                        if ((gLayer.Renderer == null || gLayer.Renderer is HiddenRenderer) && !Symbology.DefaultSymbols.ContainsKey(geometryType))
                        {
                            if (geometryType == GeometryType.Unknown)
                            {
                                gLayer.SetValue(ESRI.ArcGIS.Client.Extensibility.LayerExtensions.ErrorMessageProperty, "Layer has unspecified geometry type.");
                            }
                            else
                            {
                                Core.LayerExtensions.SetRunLayerPostInitializationActions(gLayer, true);
                                SymbolConfigProvider.GetDefaultLinearGradientBrush(gLayer, ColorRampType.ClassBreaks);
                            }
                            return;
                        }
                    }
                    #endregion

                    #region Project graphics if necessary
                    if (graphicsRequireReprojection(gLayer.Graphics))
                    {
                        GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(
                            new ConfigurationStoreHelper().GetGeometryServiceUrl(ConfigurationStore)
                            );
                        helper.ProjectGraphicsCompleted += (sender, args) =>
                        {
                            GraphicsLayer targetLayer = args.UserState as GraphicsLayer;
                            if (targetLayer != null)
                            {
                                targetLayer.Graphics.Clear();
                                foreach (Graphic graphic in args.Graphics)
                                {
                                    targetLayer.Graphics.Add(graphic);
                                }
                            }
                        };
                        helper.ProjectGraphics(gLayer.Graphics, Map.SpatialReference, gLayer);
                    }
                    #endregion

                    #region Get field information
                    if (layerFields.Count == 0) // fields not determined yet
                    {
                        determineFieldsFromGraphic(layerFields, gLayer.Graphics.ElementAtOrDefault(0));
                    }
                    #endregion
                }

                #region Get renderer from feature layer's layer info, if necessary
                if (gLayer.Renderer == null || gLayer.Renderer is HiddenRenderer)
                {
                    FeatureLayer lay = gLayer as FeatureLayer;
                    if (lay != null && lay.LayerInfo != null && lay.LayerInfo.Renderer != null)
                    {
                        lay.Renderer = lay.LayerInfo.Renderer;
                    }
                }
                #endregion

                #region Change PictureMarkerSymbol to ImageFillSymbol
                if (gLayer.Renderer != null && (geometryType == GeometryType.Point || geometryType == GeometryType.MultiPoint))
                {
                    SimpleRenderer sr = gLayer.Renderer as SimpleRenderer;
                    ESRI.ArcGIS.Client.FeatureService.Symbols.PictureMarkerSymbol pms = null;
                    if (sr != null)
                    {
                        pms = sr.Symbol as ESRI.ArcGIS.Client.FeatureService.Symbols.PictureMarkerSymbol;
                        if (pms != null)
                        {
                            sr.Symbol = SymbolJsonHelper.ToImageFillSymbol(pms);
                        }
                    }
                    else
                    {
                        ClassBreaksRenderer cbr = gLayer.Renderer as ClassBreaksRenderer;
                        if (cbr != null)
                        {
                            foreach (ClassBreakInfo info in cbr.Classes)
                            {
                                pms = info.Symbol as ESRI.ArcGIS.Client.FeatureService.Symbols.PictureMarkerSymbol;
                                if (pms != null)
                                {
                                    info.Symbol = SymbolJsonHelper.ToImageFillSymbol(pms);
                                }
                            }
                        }
                        else
                        {
                            UniqueValueRenderer uvr = gLayer.Renderer as UniqueValueRenderer;
                            if (uvr != null)
                            {
                                foreach (UniqueValueInfo info in uvr.Infos)
                                {
                                    pms = info.Symbol as ESRI.ArcGIS.Client.FeatureService.Symbols.PictureMarkerSymbol;
                                    if (pms != null)
                                    {
                                        info.Symbol = SymbolJsonHelper.ToImageFillSymbol(pms);
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion

                if (gLayer.Renderer == null || gLayer.Renderer is HiddenRenderer)
                {
                    ApplyDefaultRenderer(gLayer, geometryType);
                }

                ApplyDefaultGradientBrush(gLayer);
            }
            else if ((layer is ArcGISDynamicMapServiceLayer || layer is ArcGISTiledMapServiceLayer) &&
                     !((bool)layer.GetValue(ESRI.ArcGIS.Client.WebMap.Document.IsBaseMapProperty)))
            {
                //get layer infos - used later for figuring out domain/subtypes, etc
                if ((layer.GetValue(ESRI.ArcGIS.Mapping.Core.LayerExtensions.LayerInfosProperty) as Collection <LayerInformation>)
                    == null)
                {
                    getLayerInfos(layer);
                }
            }
            bool doSelect = false;
            layer.SetValue(ESRI.ArcGIS.Client.Extensibility.LayerExtensions.InitialUpdateCompletedProperty, true);
            if (!initializationSuccess)
            {
                layer.SetValue(ESRI.ArcGIS.Client.Extensibility.LayerExtensions.InitialUpdateFailedProperty, true);
            }
            else
            {
                bool hasId = !string.IsNullOrEmpty(layer.ID) || !string.IsNullOrEmpty(layer.GetValue(ESRI.ArcGIS.Client.Extensibility.MapApplication.LayerNameProperty) as  string);
                // Certain layers get added when the map draw mode is changed (An empty graphics layer is added)
                // We don't want to auto-select this layer
                if (hasId || !(layer is GraphicsLayer))
                {
                    doSelect = true;
                }
            }

            if (doSelect)
            {
                SetSelectedLayer(new LayerEventArgs()
                {
                    Layer = layer
                });
            }

            SubscribeToLayerInitializationEvents(layer, false);
        }
コード例 #17
0
        public void SetShapeRangeValues(DashboardHelper dashboardHelper, string shapeKey, string dataKey, string valueField, List <SolidColorBrush> brushList, int classCount, string missingText, string legendText, bool?showPolyLabels = false)
        {
            try
            {
                _classCount      = classCount;
                _dashboardHelper = dashboardHelper;
                _shapeKey        = shapeKey;
                _dataKey         = dataKey;
                _valueField      = valueField;
                _missingText     = missingText;
                _legendText      = legendText;
                _showPolyLabels  = (bool)showPolyLabels;

                if (brushList != null)
                {
                    _colors = brushList;
                }

                DataTable loadedData = GetLoadedData(dashboardHelper, dataKey, ref valueField);

                if (_valueField == "{Record Count}")
                {
                    _valueField = "freq";
                }

                GraphicsLayer graphicsLayer = GetGraphicsLayer() as GraphicsLayer;

                _thematicItem = GetThematicItem(classCount, loadedData, graphicsLayer);

                if (this.UseQuantiles == false && RangeStarts_FromControls != null && RangeStarts_FromControls.Count > 0)
                {
                    _thematicItem.RangeStarts = RangeStarts_FromControls;
                    PopulateRangeValues();
                }
                else
                {
                    PopulateRangeValues();
                }

                GraphicCollection textGraphics = new GraphicCollection();

                if (graphicsLayer.Graphics != null && graphicsLayer.Graphics.Count > 0)
                {
                    for (int i = graphicsLayer.Graphics.Count - 1; i > -1; i--)
                    {
                        if (graphicsLayer.Graphics[i].Symbol is TextSymbol)
                        {
                            graphicsLayer.Graphics.RemoveAt(i);
                        }
                    }
                }

                bool usePoleOfInaccessibility = true;

                if (graphicsLayer.Graphics != null && graphicsLayer.Graphics.Count > 0)
                {
                    for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                    {
                        Graphic graphicFeature = graphicsLayer.Graphics[i];

                        if (graphicFeature.Symbol is TextSymbol)
                        {
                            continue;
                        }
                        if (graphicFeature.Attributes.Count == 0)
                        {
                            continue;
                        }

                        string filterExpression = "";

                        if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        {
                            filterExpression += "[";
                        }

                        filterExpression += dataKey;

                        if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        {
                            filterExpression += "]";
                        }

                        filterExpression += " = '" + GetShapeValue(graphicFeature, shapeKey) + "'";

                        double graphicValue = Double.PositiveInfinity;
                        try
                        {
                            DataRow[] postFilterExpression = loadedData.Select(filterExpression);

                            if (postFilterExpression.Length > 0)
                            {
                                graphicValue = Convert.ToDouble(postFilterExpression[0][_valueField]);
                            }
                        }
                        catch (Exception)
                        {
                            graphicValue = Double.PositiveInfinity;
                        }

                        int brushIndex = GetRangeIndex(graphicValue, _thematicItem.RangeStarts);

                        if (brushList != null)
                        {
                            Color color = ((SolidColorBrush)brushList[brushIndex]).Color;
                            Brush fill  = new SolidColorBrush(Color.FromArgb(Opacity, color.R, color.G, color.B));

                            if (graphicValue == Double.PositiveInfinity)
                            {
                                color = ((SolidColorBrush)brushList[brushList.Count - 1]).Color;
                                fill  = new SolidColorBrush(Color.FromArgb(Opacity, color.R, color.G, color.B));
                            }

                            SimpleFillSymbol symbol = new SimpleFillSymbol();

                            symbol.Fill            = fill;
                            symbol.BorderBrush     = new SolidColorBrush(Colors.Black);
                            symbol.BorderThickness = 1;

                            graphicFeature.Symbol = symbol;
                        }

                        if (ShowPolyLabels)
                        {
                            TextSymbol textSymbol = new TextSymbol();
                            textSymbol.Foreground = new SolidColorBrush(Colors.Black);
                            textSymbol.FontSize   = 11;

                            if (graphicFeature.Attributes[shapeKey] != null)
                            {
                                string sShapekey     = graphicFeature.Attributes[shapeKey].ToString().Trim();
                                int    indexShapeKey = sShapekey.LastIndexOfAny(new char[] { ' ', '-' });
                                int    iShapeKeyLen  = sShapekey.Length;

                                //  Break up label if possible and put on new line.  Adjust offsets as needed.
                                if (indexShapeKey != -1) //& iShapeKeyLen > 10)
                                {
                                    textSymbol.Text    = sShapekey.Substring(0, indexShapeKey) + "\r\n    " + sShapekey.Substring(indexShapeKey + 1, (iShapeKeyLen - (indexShapeKey + 1)));
                                    textSymbol.OffsetX = iShapeKeyLen / 0.8;
                                    textSymbol.OffsetY = 6;
                                }
                                else
                                {
                                    textSymbol.Text    = sShapekey;
                                    textSymbol.OffsetX = iShapeKeyLen / 0.4;
                                    textSymbol.OffsetY = 3;
                                }
                                //Console.WriteLine(textSymbol.Text);
                                //textSymbol.OffsetX = textSymbol.Text.Length / 0.4;
                                textSymbol.OffsetY = textSymbol.FontSize / 2.0;

                                Envelope extentEnvelope = graphicFeature.Geometry.Extent;
                                MapPoint pole           = extentEnvelope.GetCenter();

                                ObservableCollection <ESRI.ArcGIS.Client.Geometry.PointCollection> rings = new ObservableCollection <ESRI.ArcGIS.Client.Geometry.PointCollection>();

                                //if (graphicFeature.Attributes[shapeKey].ToString().Trim() == "Richmond Hill") usePoleOfInaccessibility = true;

                                if (usePoleOfInaccessibility)
                                {
                                    if (graphicFeature.Geometry is ESRI.ArcGIS.Client.Geometry.Polygon)
                                    {
                                        rings = ((ESRI.ArcGIS.Client.Geometry.Polygon)graphicFeature.Geometry).Rings;
                                        Tuple <double, double> coords;

                                        bool showDebugCells = true;

                                        if (showDebugCells)
                                        {
                                            double precision = 0.1;
                                            double denom     = 64.0;

                                            precision = extentEnvelope.Width / denom < precision? extentEnvelope.Width / denom : precision;
                                            precision = extentEnvelope.Height / denom < precision ? extentEnvelope.Height / denom : precision;

                                            coords = PolyLabel.PoleOfInaccessibility(rings, precision, graphicsLayer: graphicsLayer);

                                            //Envelope extent = graphicFeature.Geometry.Extent;
                                            //Cell extentCell = new Cell(extent.XMin, extent.YMin, extent.Width / 2, rings);
                                            //PolyLabel.AddDebugGraphic(extentCell, graphicsLayer);
                                        }
                                        else
                                        {
                                            coords = PolyLabel.PoleOfInaccessibility(rings);
                                        }

                                        pole.X = coords.Item1;
                                        pole.Y = coords.Item2;
                                    }

                                    //usePoleOfInaccessibility = false;
                                }

                                Graphic textGraphic = new Graphic();

                                textGraphic.Symbol   = textSymbol;
                                textGraphic.Geometry = pole;

                                textGraphics.Add(textGraphic);
                            }
                        }

                        TextBlock t = new TextBlock();
                        t.Background = Brushes.White;

                        if (graphicValue == Double.PositiveInfinity)
                        {
                            t.Text = GetShapeValue(graphicFeature, shapeKey) + " " + DashboardSharedStrings.DASHBOARD_MAP_NO_DATA;
                        }
                        else
                        {
                            t.Text = GetShapeValue(graphicFeature, shapeKey) + " : " + graphicValue.ToString();
                        }

                        t.FontSize = 14;

                        Border border = new Border();
                        border.BorderThickness = new Thickness(1);
                        Panel panel = new StackPanel();
                        panel.Children.Add(t);
                        border.Child = panel;

                        graphicFeature.MapTip = border;

                        if (graphicFeature.Attributes.Keys.Contains("EpiInfoValCol"))
                        {
                            graphicFeature.Attributes["EpiInfoValCol"] = graphicValue;
                        }
                        else
                        {
                            graphicFeature.Attributes.Add("EpiInfoValCol", graphicValue);
                        }
                    }

                    graphicsLayer.Graphics.AddRange(textGraphics);

                    if (graphicsLayer is FeatureLayer)
                    {
                        ClassBreaksRenderer renderer = new ClassBreaksRenderer();
                        renderer.Field = "EpiInfoValCol";

                        Color color = ((SolidColorBrush)brushList[brushList.Count - 1]).Color;
                        Brush fill  = new SolidColorBrush(Color.FromArgb(Opacity, color.R, color.G, color.B));

                        renderer.DefaultSymbol = new SimpleFillSymbol()
                        {
                            Fill            = fill,
                            BorderBrush     = new SolidColorBrush(Colors.Black),
                            BorderThickness = 1
                        };

                        for (int i = 0; i < _thematicItem.RangeStarts.Count; i++)
                        {
                            ClassBreakInfo classBreakInfo = new ClassBreakInfo();
                            classBreakInfo.MinimumValue = double.Parse(RangeValues[i, 0]);
                            classBreakInfo.MaximumValue = double.Parse(RangeValues[i, 1]);

                            color = ((SolidColorBrush)brushList[i]).Color;
                            fill  = new SolidColorBrush(Color.FromArgb(Opacity, color.R, color.G, color.B));

                            classBreakInfo.Symbol = new SimpleFillSymbol()
                            {
                                Fill            = fill,
                                BorderBrush     = new SolidColorBrush(Colors.Black),
                                BorderThickness = 1
                            };

                            renderer.Classes.Add(classBreakInfo);
                        }

                        graphicsLayer.Renderer = renderer;
                    }
                }

                SetLegendSection(brushList, classCount, missingText, _thematicItem);
            }
            catch
            {
            }
        }
コード例 #18
0
ファイル: HistoClass.cs プロジェクト: nohe427/MyAddins
        private void RenderFeatures(ILayer layer)
        {
            //Set up renderer
            IClassBreaksRenderer classBreaksRenderer = new ClassBreaksRenderer();
            classBreaksRenderer.Field = "HistoField";
            classBreaksRenderer.BreakCount = 5;

            //Set up table histogram properties
            object douleArrayValues;
            object frequencyArray;
            IFeatureClass featureClass = ((IFeatureLayer) layer).FeatureClass;
            ITable table = (ITable) featureClass;
            ITableHistogram tableHistogram = (ITableHistogram) new BasicTableHistogram();
            tableHistogram.Table = table;
            tableHistogram.Field = "HistoField";
            ((IDataSampling)classBreaksRenderer).SamplingMethod = esriDataSampling.esriAllRecords;
            tableHistogram.Sampling = (IDataSampling)classBreaksRenderer;
            ((IBasicHistogram) tableHistogram).GetHistogram(out douleArrayValues, out frequencyArray);
            IClassifyGEN classifyGen = new NaturalBreaks();
            classifyGen.Classify(douleArrayValues, frequencyArray, classBreaksRenderer.BreakCount);
            Double[] x = classifyGen.ClassBreaks as Double[];
            Random random = new Random();
            for (var i = 1; i < x.Length; i++)
            {
                classBreaksRenderer.Break[i-1] = x[i];
                classBreaksRenderer.Description[i-1] = "TEST";
                classBreaksRenderer.Label[i-1] = x.GetValue(i).ToString();
                IMarkerSymbol markerSymbol = new SimpleMarkerSymbol();
                Color colorToUse = GetAColor(random.Next(0,174));
                IRgbColor rgbColor = new RgbColorClass();
                rgbColor.Blue = colorToUse.B;
                rgbColor.Red = colorToUse.R;
                rgbColor.Green = colorToUse.G;
                markerSymbol.Color = rgbColor;
                markerSymbol.Size = 5;
                classBreaksRenderer.Symbol[i - 1] = (ISymbol)markerSymbol;
            }

            ((IGeoFeatureLayer) layer).Renderer = ((IFeatureRenderer)classBreaksRenderer);
        }
コード例 #19
0
ファイル: Datamanagement.cs プロジェクト: gistop/aegis
        void ClassBreaksRenderer(IFeatureLayer featureLayer)
        {
            IClassBreaksRenderer classBreaksRenderer = new ClassBreaksRenderer();
            classBreaksRenderer.Field = "AREA";
            // 必须设置分类数量。
            classBreaksRenderer.BreakCount = 4;
            classBreaksRenderer.set_Break(0, 744366000);
            classBreaksRenderer.set_Break(1, 2049800000);
            classBreaksRenderer.set_Break(2, 3801580000);

            // 设置填充样式。
            IFillSymbol fillSymbol = new SimpleFillSymbol();
            fillSymbol.Color = new RgbColor() { Red = 255, Green = 0, Blue = 0 };
            classBreaksRenderer.set_Symbol(0, (ISymbol)fillSymbol);
            fillSymbol = new SimpleFillSymbol();
            fillSymbol.Color = new RgbColor() { Red = 0, Green = 255, Blue = 0 };
            classBreaksRenderer.set_Symbol(1, (ISymbol)fillSymbol);
            fillSymbol = new SimpleFillSymbol();
            fillSymbol.Color = new RgbColor() { Red = 0, Green = 0, Blue = 255 };
            classBreaksRenderer.set_Symbol(2, (ISymbol)fillSymbol);

            // 图层设置渲染。
            var featureRenderer = (IFeatureRenderer)classBreaksRenderer;
            var geoFeatureLayer = (IGeoFeatureLayer)featureLayer;
            geoFeatureLayer.Renderer = featureRenderer;
        }
コード例 #20
0
        private void bindUIToLayer()
        {
            GraphicsLayer graphicsLayer = Layer as GraphicsLayer;

            if (graphicsLayer == null)
            {
                return;
            }

            #region Renderer Takes Precedence
            bindingToLayer = true;
            if (GraphicSymbolsTakePrecedence != null)
            {
                GraphicSymbolsTakePrecedence.IsChecked = !graphicsLayer.RendererTakesPrecedence;
            }
            bindingToLayer = false;
            #endregion

            GeometryType = ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetGeometryType(graphicsLayer);

            ClassBreaksRenderer classBreaksRenderer = graphicsLayer.Renderer as ClassBreaksRenderer;
            if (classBreaksRenderer != null)
            {
                if (RendererOptionsContainerControl != null)
                {
                    ClassBreaksRendererOptionsConfigControl optionsConfigControl = new ClassBreaksRendererOptionsConfigControl()
                    {
                        ClassBreaksRenderer  = classBreaksRenderer,
                        SymbolConfigProvider = SymbolConfigProvider,
                        GeometryType         = GeometryType,
                    };

                    Binding b = new Binding("Foreground")
                    {
                        Source = this
                    };
                    optionsConfigControl.SetBinding(ClassBreaksRendererOptionsConfigControl.ForegroundProperty, b);

                    optionsConfigControl.RendererColorSchemeChanged += new EventHandler <GradientBrushChangedEventArgs>(optionsConfigControl_RendererColorSchemeChanged);
                    optionsConfigControl.RendererClassBreaksChanged += new EventHandler <RendererClassBreaksCountChangedEventArgs>(optionsConfigControl_RendererClassBreaksChanged);
                    RendererOptionsContainerControl.Content          = optionsConfigControl;
                }

                if (RendererOptionsContainerBorder != null)
                {
                    RendererOptionsContainerBorder.Visibility = Visibility.Visible;
                }

                if (CurrentSymbolLabel != null)
                {
                    CurrentSymbolLabel.Visibility = Visibility.Visible;
                }

                createClassBreaksRendererSymbolsConfigControl(classBreaksRenderer);
            }
            else
            {
                UniqueValueRenderer uniqueValueRenderer = graphicsLayer.Renderer as UniqueValueRenderer;
                if (uniqueValueRenderer != null)
                {
                    if (RendererOptionsContainerControl != null)
                    {
                        UniqueValueRendererOptionsConfigControl optionsConfigControl = new UniqueValueRendererOptionsConfigControl()
                        {
                            UniqueValueRenderer  = uniqueValueRenderer,
                            SymbolConfigProvider = SymbolConfigProvider,
                            GeometryType         = GeometryType,
                        };

                        Binding b = new Binding("Foreground")
                        {
                            Source = this
                        };
                        optionsConfigControl.SetBinding(UniqueValueRendererOptionsConfigControl.ForegroundProperty, b);

                        optionsConfigControl.RendererColorSchemeChanged += new EventHandler <GradientBrushChangedEventArgs>(optionsConfigControl_RendererColorSchemeChanged);
                        optionsConfigControl.NewUniqueValueAdded        += new EventHandler <NewUniqueValueInfoEventArgs>(optionsConfigControl_NewUniqueValueCreated);
                        optionsConfigControl.DeleteUniqueValueClicked   += new EventHandler(optionsConfigControl_DeleteUniqueValueClicked);
                        RendererOptionsContainerControl.Content          = optionsConfigControl;
                    }

                    if (RendererSymbolSetContainerControl != null)
                    {
                        UniqueValueRendererSymbolsConfigControl symbolsConfigControl = new UniqueValueRendererSymbolsConfigControl()
                        {
                            UniqueValueRenderer  = uniqueValueRenderer,
                            SymbolConfigProvider = SymbolConfigProvider,
                            GeometryType         = GeometryType,
                        };

                        Binding b = new Binding("Foreground")
                        {
                            Source = this
                        };
                        symbolsConfigControl.SetBinding(UniqueValueRendererSymbolsConfigControl.ForegroundProperty, b);

                        symbolsConfigControl.UniqueValueRendererModified      += new EventHandler <SelectedUniqueValueModificationEventArgs>(symbolsConfigControl_UniqueValueRendererModified);
                        symbolsConfigControl.CurrentUniqueValueChanged        += new EventHandler <CurrentUniqueValueChangedEventArgs>(symbolsConfigControl_CurrentUniqueValueChanged);
                        symbolsConfigControl.DefaultClassBreakBeingConfigured += new EventHandler <DefaultClassBreakBeingConfiguredEventArgs>(symbolsConfigControl_DefaultClassBreakBeingConfigured);
                        RendererSymbolSetContainerControl.Content              = symbolsConfigControl;
                    }

                    if (RendererOptionsContainerBorder != null)
                    {
                        RendererOptionsContainerBorder.Visibility = Visibility.Visible;
                    }

                    if (CurrentSymbolLabel != null)
                    {
                        CurrentSymbolLabel.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                    // No renderer / simple renderer ... clear out the control
                    if (RendererOptionsContainerControl != null)
                    {
                        RendererOptionsContainerControl.Content = null;
                    }

                    if (RendererSymbolSetContainerControl != null)
                    {
                        ESRI.ArcGIS.Client.Symbols.Symbol defaultSymbol       = graphicsLayer.GetDefaultSymbol();
                        DefaultSymbolConfigControl        defaultSymbolConfig = new DefaultSymbolConfigControl()
                        {
                            Symbol = defaultSymbol,
                            SymbolConfigProvider = SymbolConfigProvider,
                            GeometryType         = GeometryType,
                        };

                        Binding b = new Binding("Foreground")
                        {
                            Source = this
                        };
                        defaultSymbolConfig.SetBinding(DefaultSymbolConfigControl.ForegroundProperty, b);

                        defaultSymbolConfig.DefaultSymbolModified += new EventHandler <SymbolSelectedEventArgs>(defaultSymbolConfig_DefaultSymbolModified);
                        RendererSymbolSetContainerControl.Content  = defaultSymbolConfig;
                        if (SymbolConfigControl != null)
                        {
                            SymbolConfigControl.Symbol = defaultSymbol;
                        }
                    }

                    if (CurrentSymbolLabel != null)
                    {
                        CurrentSymbolLabel.Visibility = Visibility.Collapsed;
                    }

                    if (RendererOptionsContainerBorder != null)
                    {
                        RendererOptionsContainerBorder.Visibility = Visibility.Collapsed;
                    }
                }
            }
        }
コード例 #21
0
ファイル: frmLocalSAM.cs プロジェクト: sishui198/SAAR
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                //Checking
                if (cboFieldName.Text == "")
                {
                    MessageBox.Show("Please select target field");
                    return;
                }

                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                int nFeature = m_pFClass.FeatureCount(null);

                IFeatureCursor pFCursor = m_pFLayer.Search(null, true);
                IFeature       pFeature = pFCursor.NextFeature();

                //Get index for independent and dependent variables
                //Get variable index
                string strVarNM  = (string)cboFieldName.SelectedItem;
                int    intVarIdx = m_pFClass.FindField(strVarNM);

                //Store Variable at Array
                double[] arrVar = new double[nFeature];

                int i = 0;

                while (pFeature != null)
                {
                    arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx));
                    i++;
                    pFeature = pFCursor.NextFeature();
                }

                //Plot command for R
                StringBuilder plotCommmand = new StringBuilder();

                if (!m_blnCreateSWM)
                {
                    //Get the file path and name to create spatial weight matrix
                    string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer);

                    if (strNameR == null)
                    {
                        return;
                    }

                    //Create spatial weight matrix in R
                    if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
                    }
                    else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')");
                    }
                    else
                    {
                        MessageBox.Show("This geometry type is not supported");
                        pfrmProgress.Close();
                        this.Close();
                    }


                    int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress);
                    if (intSuccess == 0)
                    {
                        return;
                    }
                }

                NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar);
                m_pEngine.SetSymbol(strVarNM, vecVar);

                if (cboSAM.Text == "Local Moran")
                {
                    #region Local Moran
                    plotCommmand.Append("localmoran(" + strVarNM + ", sample.listw, alternative = 'two.sided', ");

                    //select multiple correction method (only Bonferroni.. 100915 HK)
                    if (cboAdjustment.Text == "None")
                    {
                        plotCommmand.Append(", zero.policy=TRUE)");
                    }
                    else if (cboAdjustment.Text == "Bonferroni correction")
                    {
                        plotCommmand.Append("p.adjust.method='bonferroni', zero.policy=TRUE)");
                    }

                    NumericMatrix nmResults = m_pEngine.Evaluate(plotCommmand.ToString()).AsNumericMatrix();

                    string strFlgFldNam = lvFields.Items[3].SubItems[1].Text;
                    //Save Output on SHP
                    //Add Target fields to store results in the shapefile
                    for (int j = 0; j < 4; j++)
                    {
                        IField     newField  = new FieldClass();
                        IFieldEdit fieldEdit = (IFieldEdit)newField;
                        fieldEdit.Name_2 = lvFields.Items[j].SubItems[1].Text;
                        if (j == 3)
                        {
                            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                        }
                        else
                        {
                            fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                        }
                        m_pFClass.AddField(newField);
                    }


                    //Update Field
                    pFCursor = m_pFClass.Update(null, false);
                    pFeature = pFCursor.NextFeature();

                    int intStatFldIdx = m_pFClass.FindField(lvFields.Items[0].SubItems[1].Text);
                    int intZFldIdx    = m_pFClass.FindField(lvFields.Items[1].SubItems[1].Text);
                    int intPrFldIdx   = m_pFClass.FindField(lvFields.Items[2].SubItems[1].Text);
                    int intFlgFldIdx  = m_pFClass.FindField(strFlgFldNam);

                    double dblValue = 0, dblPvalue = 0, dblZvalue = 0;
                    double dblValueMean = arrVar.Average();
                    double dblPrCri     = Convert.ToDouble(nudConfLevel.Value);

                    int featureIdx = 0;
                    while (pFeature != null)
                    {
                        dblValue  = arrVar[featureIdx] - dblValueMean;
                        dblZvalue = nmResults[featureIdx, 3];
                        dblPvalue = nmResults[featureIdx, 4];
                        pFeature.set_Value(intStatFldIdx, (object)nmResults[featureIdx, 0]);
                        pFeature.set_Value(intZFldIdx, dblZvalue);
                        pFeature.set_Value(intPrFldIdx, dblPvalue);

                        if (dblPvalue < dblPrCri)
                        {
                            if (dblZvalue > 0)
                            {
                                if (dblValue > 0)
                                {
                                    pFeature.set_Value(intFlgFldIdx, "HH");
                                }
                                else
                                {
                                    pFeature.set_Value(intFlgFldIdx, "LL");
                                }
                            }
                            else
                            {
                                if (dblValue > 0)
                                {
                                    pFeature.set_Value(intFlgFldIdx, "HL");
                                }
                                else
                                {
                                    pFeature.set_Value(intFlgFldIdx, "LH");
                                }
                            }
                        }
                        //else
                        //    pFeature.set_Value(intFlgFldIdx, "");
                        pFCursor.UpdateFeature(pFeature);

                        pFeature = pFCursor.NextFeature();
                        featureIdx++;
                    }

                    pfrmProgress.Close();
                    if (chkMap.Checked)
                    {
                        double[,] adblMinMaxForLabel = new double[2, 4];
                        ITable pTable = (ITable)m_pFClass;

                        IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                        pUniqueValueRenderer.FieldCount = 1;
                        pUniqueValueRenderer.set_Field(0, strFlgFldNam);
                        IDataStatistics    pDataStat;
                        IStatisticsResults pStatResults;

                        ICursor pCursor;

                        if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            ISimpleFillSymbol pSymbol;
                            IQueryFilter      pQFilter = new QueryFilterClass();
                            pQFilter.WhereClause = strFlgFldNam + " = 'HH'";

                            int intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 0] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 0] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(255, 80, 80);
                            pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol);
                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")");
                            }



                            pQFilter.WhereClause = strFlgFldNam + " = 'LL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 1] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 1] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(50, 157, 194);
                            pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'HL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 2] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 2] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(244, 199, 0);
                            pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'LH'";
                            intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 3] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 3] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(173, 255, 179);
                            pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")");
                            }



                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(200, 200, 200);
                            //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol);
                            //pUniqueValueRenderer.set_Label("", "Not significant");
                            pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol;
                            pUniqueValueRenderer.DefaultLabel  = "Not significant";

                            pUniqueValueRenderer.UseDefaultSymbol = true;
                        }
                        else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            ISimpleMarkerSymbol pSymbol;
                            IQueryFilter        pQFilter = new QueryFilterClass();
                            pQFilter.WhereClause = strFlgFldNam + " = 'HH'";

                            int intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 0] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 0] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(255, 80, 80);
                            pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol);
                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")");
                            }



                            pQFilter.WhereClause = strFlgFldNam + " = 'LL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 1] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 1] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(50, 157, 194);
                            pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'HL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 2] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 2] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(244, 199, 0);
                            pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'LH'";
                            intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 3] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 3] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(173, 255, 179);
                            pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")");
                            }



                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(200, 200, 200);
                            //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol);
                            //pUniqueValueRenderer.set_Label("", "Not significant");
                            pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol;
                            pUniqueValueRenderer.DefaultLabel  = "Not significant";

                            pUniqueValueRenderer.UseDefaultSymbol = true;
                        }



                        IFeatureLayer pNewFLayer = new FeatureLayerClass();
                        pNewFLayer.FeatureClass = m_pFClass;
                        pNewFLayer.Name         = cboSAM.Text + " of " + m_pFLayer.Name;
                        IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                        pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                        m_pActiveView.FocusMap.AddLayer(pGFLayer);
                        m_pActiveView.Refresh();
                        m_pForm.axTOCControl1.Update();
                    }
                    else
                    {
                        MessageBox.Show("Complete. The results are stored in the shape file");
                    }
                    #endregion
                }
                else if (cboSAM.Text == "Gi*")
                {
                    #region Gi*
                    m_pEngine.Evaluate("sample.lg <- localG(" + strVarNM + ", sample.listw, zero.policy=TRUE)");
                    m_pEngine.Evaluate("sample.p <- 2*pnorm(-abs(sample.lg))");

                    if (cboAdjustment.Text == "Bonferroni correction")
                    {
                        m_pEngine.Evaluate("sample.p <- p.adjust(sample.p, method = 'bonferroni', n = length(sample.p))");
                    }

                    double[] dblGValues = m_pEngine.Evaluate("sample.lg").AsNumeric().ToArray();
                    double[] dblPvalues = m_pEngine.Evaluate("sample.p").AsNumeric().ToArray();

                    //Save Output on SHP
                    //Add Target fields to store results in the shapefile
                    for (int j = 0; j < 2; j++)
                    {
                        IField     newField  = new FieldClass();
                        IFieldEdit fieldEdit = (IFieldEdit)newField;
                        fieldEdit.Name_2 = lvFields.Items[j].SubItems[1].Text;
                        fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                        m_pFClass.AddField(newField);
                    }

                    //Update Field
                    pFCursor = m_pFClass.Update(null, false);
                    pFeature = pFCursor.NextFeature();

                    int intStatFldIdx = m_pFClass.FindField(lvFields.Items[0].SubItems[1].Text);
                    int intPrFldIdx   = m_pFClass.FindField(lvFields.Items[1].SubItems[1].Text);

                    int featureIdx = 0;
                    while (pFeature != null)
                    {
                        pFeature.set_Value(intStatFldIdx, dblGValues[featureIdx]);
                        pFeature.set_Value(intPrFldIdx, dblPvalues[featureIdx]);

                        pFCursor.UpdateFeature(pFeature);

                        pFeature = pFCursor.NextFeature();
                        featureIdx++;
                    }
                    pFCursor.Flush();

                    pfrmProgress.Close();

                    if (chkMap.Checked)
                    {
                        string strStaticFldName = lvFields.Items[0].SubItems[1].Text;

                        m_pEngine.Evaluate("p.vals <- c(0.1, 0.05, 0.01)");
                        if (cboAdjustment.Text == "Bonferroni correction")
                        {
                            m_pEngine.Evaluate("sample.n <- length(sample.p)");
                            m_pEngine.Evaluate("p.vals <- p.vals/sample.n");
                        }
                        m_pEngine.Evaluate("zc <- qnorm(1 - (p.vals/2))");
                        double[] dblZBrks = m_pEngine.Evaluate("sort(cbind(zc, -zc))").AsNumeric().ToArray();

                        pFCursor = m_pFClass.Search(null, false);
                        IDataStatistics pDataStat = new DataStatisticsClass();
                        pDataStat.Field  = strStaticFldName;
                        pDataStat.Cursor = (ICursor)pFCursor;
                        IStatisticsResults pStatResults = pDataStat.Statistics;
                        double             dblMax       = pStatResults.Maximum;
                        double             dblMin       = pStatResults.Minimum;
                        int      intBreaksCount         = dblZBrks.Length + 2;
                        double[] cb = new double[intBreaksCount];

                        //Assign Min and Max values for class breaks
                        if (dblMin < dblZBrks[0])
                        {
                            cb[0] = dblMin;
                        }
                        else
                        {
                            cb[0] = dblZBrks[0] - 1; //Manually Assigned minimum value
                        }
                        if (dblMax > dblZBrks[dblZBrks.Length - 1])
                        {
                            cb[intBreaksCount - 1] = dblMax;
                        }
                        else
                        {
                            cb[intBreaksCount - 1] = dblZBrks[dblZBrks.Length - 1] + 1;//Manually Assigned minimum value
                        }
                        for (int k = 0; k < intBreaksCount - 2; k++)
                        {
                            cb[k + 1] = dblZBrks[k];
                        }

                        IClassBreaksRenderer pCBRenderer = new ClassBreaksRenderer();
                        pCBRenderer.Field        = strStaticFldName;
                        pCBRenderer.BreakCount   = intBreaksCount - 1;
                        pCBRenderer.MinimumBreak = cb[0];

                        //' use this interface to set dialog properties
                        IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pCBRenderer;
                        pUIProperties.ColorRamp = "Custom";
                        if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            ISimpleFillSymbol pSimpleFillSym;

                            int[,] arrColors = CreateColorRamp();

                            //Add Probability Value Manually
                            string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" };
                            //' be careful, indices are different for the diff lists
                            for (int j = 0; j < intBreaksCount - 1; j++)
                            {
                                pCBRenderer.Break[j] = cb[j + 1];
                                if (j == 0)
                                {
                                    pCBRenderer.Label[j] = " <= " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                else if (j == intBreaksCount - 2)
                                {
                                    pCBRenderer.Label[j] = " > " + Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1];
                                }
                                else
                                {
                                    pCBRenderer.Label[j] = Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1] + " ~ " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                pUIProperties.LowBreak[j] = cb[j];
                                pSimpleFillSym            = new SimpleFillSymbolClass();
                                IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]);
                                pSimpleFillSym.Color  = (IColor)pRGBColor;
                                pCBRenderer.Symbol[j] = (ISymbol)pSimpleFillSym;
                            }
                        }
                        else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            ISimpleMarkerSymbol pSimpleMarkerSym;

                            int[,] arrColors = CreateColorRamp();

                            //Add Probability Value Manually
                            string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" };
                            //' be careful, indices are different for the diff lists
                            for (int j = 0; j < intBreaksCount - 1; j++)
                            {
                                pCBRenderer.Break[j] = cb[j + 1];
                                if (j == 0)
                                {
                                    pCBRenderer.Label[j] = " <= " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                else if (j == intBreaksCount - 2)
                                {
                                    pCBRenderer.Label[j] = " > " + Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1];
                                }
                                else
                                {
                                    pCBRenderer.Label[j] = Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1] + " ~ " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                pUIProperties.LowBreak[j] = cb[j];
                                pSimpleMarkerSym          = new SimpleMarkerSymbolClass();
                                IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]);
                                pSimpleMarkerSym.Color = (IColor)pRGBColor;
                                pCBRenderer.Symbol[j]  = (ISymbol)pSimpleMarkerSym;
                            }
                        }


                        IFeatureLayer pNewFLayer = new FeatureLayerClass();
                        pNewFLayer.FeatureClass = m_pFClass;
                        pNewFLayer.Name         = cboSAM.Text + " of " + m_pFLayer.Name;
                        IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                        pGFLayer.Renderer = (IFeatureRenderer)pCBRenderer;
                        m_pActiveView.FocusMap.AddLayer(pGFLayer);
                        m_pActiveView.Refresh();
                        m_pForm.axTOCControl1.Update();
                    }
                    else
                    {
                        MessageBox.Show("Complete. The results are stored in the shape file");
                    }
                    #endregion
                }

                this.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
コード例 #22
0
        private void CorrectRendererNodes(LegendItemViewModel model)
        {
            LayerItemViewModel mod = model as LayerItemViewModel;

            if (mod != null)
            {
                if (MapContentsControlHelper.IsTopMostLayerType(mod.LayerType))
                {
                    GraphicsLayer lay = mod.Layer as GraphicsLayer;
                    if (lay == null)
                    {
                        return;
                    }

                    ClassBreaksRenderer classBreaksrenderer = lay.Renderer as ClassBreaksRenderer;
                    if (classBreaksrenderer != null)
                    {
                        if (mod.LegendItems != null && mod.LegendItems.Count > 0 &&
                            string.IsNullOrWhiteSpace(mod.LegendItems[0].Label))
                        {
                            mod.LegendItems[0].Label = Resources.Strings.DefaultLegentItemViewModelLabel;
                        }
                    }
                    else
                    {
                        UniqueValueRenderer uniqueRenderer = lay.Renderer as UniqueValueRenderer;
                        if (uniqueRenderer != null && string.IsNullOrWhiteSpace(uniqueRenderer.DefaultLabel))
                        {
                            uniqueRenderer.DefaultLabel = Resources.Strings.DefaultLegentItemViewModelLabel;
                        }
                    }

                    //TODO:
                    //TODO: This code adds a new node for the renderer attribute field, but currently there is no
                    //TODO: way for us to set a different template as LayerItemViewModel.Template is read-only.
                    //TODO
                    //string attribute = null;
                    //ClassBreaksRenderer classBreaksrenderer = lay.Renderer as ClassBreaksRenderer;
                    //if (classBreaksrenderer != null)
                    //{
                    //    attribute = classBreaksrenderer.Attribute;
                    //}
                    //else
                    //{
                    //    UniqueValueRenderer uniqueRenderer = lay.Renderer as UniqueValueRenderer;
                    //    if (uniqueRenderer != null)
                    //        attribute = uniqueRenderer.Attribute;
                    //}
                    //if (renModel.LegendItems != null && renModel.LegendItems.Count > 0)
                    //{
                    //    if (string.IsNullOrWhiteSpace(renModel.LegendItems[0].Label))
                    //        renModel.LegendItems[0].Label = Resources.Strings.DefaultLegentItemViewModelLabel;
                    //}
                    //if (string.IsNullOrWhiteSpace(attribute))
                    //    return;
                    //LayerItemViewModel renModel = new LayerItemViewModel(mod.Layer);
                    //renModel.Label = attribute;
                    //renModel.LayerItems = mod.LayerItems;
                    //renModel.LegendItems = mod.LegendItems;
                    //renModel.Tag = AssociatedObject.DataContext;
                    //renModel.LayerType = "Renderer Layer";

                    //mod.LayerItems = null;
                    //mod.LegendItems = null;

                    //mod.LayerItems = new System.Collections.ObjectModel.ObservableCollection<LayerItemViewModel>();
                    //mod.LayerItems.Add(renModel);
                }
            }
        }
コード例 #23
0
ファイル: frmBivariateLISA.cs プロジェクト: sishui198/SAAR
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

            pfrmProgress.lblStatus.Text    = "Processing:";
            pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
            pfrmProgress.Show();

            REngine pEngine = m_pForm.pEngine;

            int nFeature = m_pFClass.FeatureCount(null);

            IFeatureCursor pFCursor = m_pFClass.Search(null, true);
            IFeature       pFeature = pFCursor.NextFeature();

            //Get index for independent and dependent variables
            //Get variable index
            string strVarNM1  = (string)cboFldnm1.SelectedItem;
            string strVarNM2  = (string)cboFldnm2.SelectedItem;
            int    intVarIdx1 = m_pFClass.FindField(strVarNM1);
            int    intVarIdx2 = m_pFClass.FindField(strVarNM2);

            //Store Variable at Array
            double[] arrVar1 = new double[nFeature];
            double[] arrVar2 = new double[nFeature];

            int i = 0;

            while (pFeature != null)
            {
                arrVar1[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx1));
                arrVar2[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx2));
                i++;
                pFeature = pFCursor.NextFeature();
            }

            pFCursor.Flush();

            //Plot command for R
            StringBuilder plotCommmand = new StringBuilder();

            string strStartPath = m_pForm.strPath;
            string pathr        = strStartPath.Replace(@"\", @"/");

            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_LARRY.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_neighbor.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_SASbi.R')");

            //Get the file path and name to create spatial weight matrix
            string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer);

            if (strNameR == null)
            {
                return;
            }

            //Create spatial weight matrix in R
            pEngine.Evaluate("library(spdep); library(maptools)");
            pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
            //pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=FALSE)");
            pEngine.Evaluate("sample.nb <- poly2nb(sample.shp)");

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

            pEngine.SetSymbol("sample.v1", vecVar1);
            NumericVector vecVar2 = pEngine.CreateNumericVector(arrVar2);

            pEngine.SetSymbol("sample.v2", vecVar2);

            //string strRSigLv = nudRsigLv.Value.ToString();
            //string strLSigLv = nudLsigLv.Value.ToString();
            //string strLSig = cboLocalL.Text;
            //string strRsig = cboLocalPearson.Text;
            //string strRowStd = cboRowStandardization.Text;
            //string strMaxRanges = nudMaxRange.Value.ToString();
            //string strHigherOrder = cboHigherOrder.Text;
            string strNonZero = null;

            if (chkDiagZero.Checked)
            {
                strNonZero = "FALSE";
            }
            else
            {
                strNonZero = "TRUE";
            }

            double[] dblLoclLisa = null;

            if (cboMeasure.Text == "Lee's L")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.LISA.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', diag.zero = " + strNonZero + ")");
                dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$local.L)").AsNumeric().ToArray();
            }
            else if (cboMeasure.Text == "Local Pearson")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.LISA.pearson(sample.v1, sample.v2, 1:length(sample.nb))");

                if (cboMapOption.Text == "Local Pearson")
                {
                    dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$local.pearson)").AsNumeric().ToArray();
                }
                else if (cboMapOption.Text == "z-score of variable 1")
                {
                    dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$z.x)").AsNumeric().ToArray();
                }
                else if (cboMapOption.Text == "z-score of variable 2")
                {
                    dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$z.y)").AsNumeric().ToArray();
                }
            }

            //Save Output on SHP
            //Add Target fields to store results in the shapefile // Keep loop
            for (int j = 0; j < 1; j++)
            {
                string strfldName = lvFields.Items[j].SubItems[1].Text;
                if (m_pFClass.FindField(strfldName) == -1)
                {
                    IField     newField  = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)newField;
                    fieldEdit.Name_2 = strfldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                    m_pFClass.AddField(newField);
                }
            }

            //Update Field
            pFCursor = m_pFClass.Update(null, false);
            pFeature = pFCursor.NextFeature();

            string strLocalLISAFldName = lvFields.Items[0].SubItems[1].Text;
            int    intSpQuadFldIdx     = m_pFClass.FindField(strLocalLISAFldName);

            int featureIdx = 0;

            while (pFeature != null)
            {
                pFeature.set_Value(intSpQuadFldIdx, dblLoclLisa[featureIdx]);

                pFCursor.UpdateFeature(pFeature);

                pFeature = pFCursor.NextFeature();
                featureIdx++;
            }
            pFCursor.Flush();

            if (chkMap.Checked)
            {
                ITable pTable = (ITable)m_pFClass;

                pFCursor = m_pFClass.Search(null, false);
                IDataStatistics pDataStat = new DataStatisticsClass();
                pDataStat.Field  = strLocalLISAFldName;
                pDataStat.Cursor = (ICursor)pFCursor;

                IStatisticsResults pStatResults = pDataStat.Statistics;
                double             dblMax       = pStatResults.Maximum;
                double             dblMin       = pStatResults.Minimum;

                int      intBreaksCount = m_pBiLISASym.Length + 1;
                double[] cb             = new double[intBreaksCount];

                //Assign Min and Max values for class breaks
                cb[0] = dblMin;
                cb[intBreaksCount - 1] = dblMax;

                for (int k = 0; k < intBreaksCount - 2; k++)
                {
                    cb[k + 1] = m_pBiLISASym[k].UValue;
                }

                IClassBreaksRenderer pCBRenderer = new ClassBreaksRenderer();
                pCBRenderer.Field        = strLocalLISAFldName;
                pCBRenderer.BreakCount   = intBreaksCount - 1;
                pCBRenderer.MinimumBreak = cb[0];

                //' use this interface to set dialog properties
                IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pCBRenderer;
                pUIProperties.ColorRamp = "Custom";
                ISimpleFillSymbol pSimpleFillSym;

                //int[,] arrColors = CreateColorRamp();

                ////Add Probability Value Manually
                //string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" };

                //' be careful, indices are different for the diff lists
                for (int j = 0; j < intBreaksCount - 1; j++)
                {
                    pCBRenderer.Break[j] = cb[j + 1];
                    pCBRenderer.Label[j] = m_pBiLISASym[j].Label;

                    pUIProperties.LowBreak[j] = cb[j];
                    pSimpleFillSym            = new SimpleFillSymbolClass();
                    IRgbColor pRGBColor = m_pSnippet.getRGB(m_pBiLISASym[j].R, m_pBiLISASym[j].G, m_pBiLISASym[j].B);
                    pSimpleFillSym.Color  = (IColor)pRGBColor;
                    pCBRenderer.Symbol[j] = (ISymbol)pSimpleFillSym;
                }

                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = m_pFClass;
                pNewFLayer.Name         = lvFields.Items[0].SubItems[0].Text + " of " + m_pFLayer.Name;
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pCBRenderer;
                m_pActiveView.FocusMap.AddLayer(pGFLayer);
                m_pActiveView.Refresh();
                m_pForm.axTOCControl1.Update();

                pfrmProgress.Close();
            }
            else
            {
                MessageBox.Show("Complete. The results are stored in the shape file");
            }
        }
コード例 #24
0
        public static void ApplyColorRampGradientBrushToRenderer(this GraphicsLayer graphicsLayer, LinearGradientBrush brush)
        {
            // must have atleast 2 stops
            if (brush == null || brush.GradientStops.Count < 2)
            {
                return;
            }

            if (graphicsLayer == null)
            {
                return;
            }

            ESRI.ArcGIS.Mapping.Core.LayerExtensions.SetGradientBrush(graphicsLayer, brush);
            ClassBreaksRenderer classBreaskRenderer = graphicsLayer.Renderer as ClassBreaksRenderer;

            if (classBreaskRenderer != null)
            {
                if (classBreaskRenderer.Classes.Count < 2)
                {
                    return;
                }

                List <Symbol> symbols = new List <Symbol>();
                foreach (ClassBreakInfo classBreak in classBreaskRenderer.Classes)
                {
                    symbols.Add(classBreak.Symbol);
                }
                applyLinearGradientBrushToSymbolSet(symbols, brush, classBreaskRenderer.DefaultSymbol);

                // Some changes to ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleSymbols do not trigger the legendchanged event. Fix this by triggering the event by cloning the symbol.
                bool refresh = false;
                foreach (ClassBreakInfo classBreak in classBreaskRenderer.Classes)
                {
                    if (classBreak.Symbol is ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleMarkerSymbol || classBreak.Symbol is ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleLineSymbol || classBreak.Symbol is ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleFillSymbol)
                    {
                        classBreak.Symbol = classBreak.Symbol.CloneSymbol();
                        refresh           = true;
                    }
                }
                if (refresh)
                {
                    graphicsLayer.Refresh();          //Only the first time a gradientbrush is applied the layer refreshes itself, so fix this by refreshing manually.
                }
            }
            else
            {
                UniqueValueRenderer uniqueValueRenderer = graphicsLayer.Renderer as UniqueValueRenderer;
                if (uniqueValueRenderer != null)
                {
                    List <Symbol> symbols = new List <Symbol>();
                    foreach (UniqueValueInfo uniqueValue in uniqueValueRenderer.Infos)
                    {
                        symbols.Add(uniqueValue.Symbol);
                    }
                    applyLinearGradientBrushToSymbolSet(symbols, brush, uniqueValueRenderer.DefaultSymbol);

                    // Some changes to ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleSymbols do not trigger the legendchanged event. Fix this by triggering the event by cloning the symbol.
                    bool refresh = false;
                    foreach (UniqueValueInfo uniqueValue in uniqueValueRenderer.Infos)
                    {
                        if (uniqueValue.Symbol is ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleMarkerSymbol || uniqueValue.Symbol is ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleLineSymbol || uniqueValue.Symbol is ESRI.ArcGIS.Client.FeatureService.Symbols.SimpleFillSymbol)
                        {
                            uniqueValue.Symbol = uniqueValue.Symbol.CloneSymbol();
                            refresh            = true;
                        }
                    }
                    if (refresh)
                    {
                        graphicsLayer.Refresh();          //Only the first time a gradientbrush is applied the layer refreshes itself, so fix this by refreshing manually.
                    }
                }
            }
        }
コード例 #25
0
        private void DrawCCMaps()
        {
            m_intClassNumber = Convert.ToInt32(nudGCNClasses.Value);
            IFeatureClass pFClass = pFLayer.FeatureClass;

            //Determine Class Breaks for variable
            int intValueFldIdx = pFClass.FindField(strVarFldName);

            ITable       pTable       = (ITable)pFClass;
            IClassifyGEN pClassifyGEN = null;

            switch (cboGCClassify.Text)
            {
            case "Equal Interval":
                pClassifyGEN = new EqualIntervalClass();
                break;

            case "Geometrical Interval":
                pClassifyGEN = new GeometricalInterval();
                break;

            case "Natural Breaks":
                pClassifyGEN = new NaturalBreaksClass();
                break;

            case "Quantile":
                pClassifyGEN = new QuantileClass();
                break;

            case "StandardDeviation":
                pClassifyGEN = new StandardDeviationClass();
                break;

            default:
                pClassifyGEN = new NaturalBreaksClass();
                break;
            }


            ITableHistogram pTableHistogram = new BasicTableHistogramClass();

            pTableHistogram.Field = strVarFldName;
            pTableHistogram.Table = pTable;
            //IHistogram pHistogram = (IHistogram)pTableHistogram2;
            IBasicHistogram pHistogram = (IBasicHistogram)pTableHistogram;

            ////Not working in ArcGIS 10.5 022417 HK
            //ITableHistogram pTableHistogram = new TableHistogramClass();
            //pTableHistogram.Field = strVarFldName;
            //pTableHistogram.Table = pTable;
            //IHistogram pHistogram = (IHistogram)pTableHistogram;

            object xVals, frqs;

            pHistogram.GetHistogram(out xVals, out frqs);
            pClassifyGEN.Classify(xVals, frqs, m_intClassNumber);
            double[] cb = (double[])pClassifyGEN.ClassBreaks;

            //Class Determinations for vertical and horizontal axis

            if (m_VerticalBreaks == null)
            {
                pClassifyGEN          = new QuantileClass(); //Using Quatile
                pTableHistogram       = new BasicTableHistogramClass();
                pTableHistogram.Field = strVerConFldName;
                pTableHistogram.Table = pTable;
                pHistogram            = (IBasicHistogram)pTableHistogram;

                pHistogram.GetHistogram(out xVals, out frqs);
                pClassifyGEN.Classify(xVals, frqs, intVerCnt);
                m_VerticalBreaks = (double[])pClassifyGEN.ClassBreaks;
            }

            if (m_HorizontalBreaks == null)
            {
                pClassifyGEN          = new QuantileClass(); //Using Quatile
                pTableHistogram       = new BasicTableHistogramClass();
                pTableHistogram.Field = strHorConFldName;
                pTableHistogram.Table = pTable;
                pHistogram            = (IBasicHistogram)pTableHistogram;

                pHistogram.GetHistogram(out xVals, out frqs);
                pClassifyGEN.Classify(xVals, frqs, intHorCnt);
                m_HorizontalBreaks = (double[])pClassifyGEN.ClassBreaks;
            }

            //Create Renderer
            IClassBreaksRenderer pRender = new ClassBreaksRenderer();

            pRender.Field        = strVarFldName;
            pRender.BreakCount   = m_intClassNumber;
            pRender.MinimumBreak = cb[0];

            string strColorRamp = cboColorRamp.Text;

            IEnumColors pEnumColors = MultiPartColorRamp(strColorRamp, "CIE Lab", m_intClassNumber);

            pEnumColors.Reset();

            int[,] arrColors = new int[m_intClassNumber, 3];

            for (int k = 0; k < m_intClassNumber; k++)
            {
                IColor    pColor    = pEnumColors.Next();
                IRgbColor pRGBColor = new RgbColorClass();
                pRGBColor.RGB = pColor.RGB;

                arrColors[k, 0] = pRGBColor.Red;
                arrColors[k, 1] = pRGBColor.Green;
                arrColors[k, 2] = pRGBColor.Blue;
            }

            pEnumColors.Reset();
            IRgbColor pColorOutline = new RgbColor();

            //Can Change the color in here!
            pColorOutline = m_pSnippet.getRGB(picOutlineColor.BackColor.R, picOutlineColor.BackColor.G, picOutlineColor.BackColor.B);

            double dblGCOutlineSize = Convert.ToDouble(nudOutlinewidth.Value);

            ICartographicLineSymbol pOutLines = new CartographicLineSymbol();

            pOutLines.Width = dblGCOutlineSize;
            pOutLines.Color = (IColor)pColorOutline;

            //' use this interface to set dialog properties
            IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pRender;

            pUIProperties.ColorRamp = "Custom";
            ISimpleFillSymbol pSimpleFillSym;

            pEnumColors.Reset();

            double dblAdding = Math.Pow(0.1, m_intRounding);

            for (int j = 0; j < m_intClassNumber; j++)
            {
                pRender.Break[j] = cb[j + 1];

                if (j == 0)
                {
                    pRender.Label[j] = Math.Round(cb[j], m_intRounding).ToString("N" + m_intRounding.ToString()) + " - " + Math.Round(cb[j + 1], 2).ToString("N" + m_intRounding.ToString());
                }
                else
                {
                    pRender.Label[j] = Math.Round(cb[j] + dblAdding, m_intRounding).ToString("N" + m_intRounding.ToString()) + " - " + Math.Round(cb[j + 1], 2).ToString("N" + m_intRounding.ToString());
                }

                pUIProperties.LowBreak[j] = cb[j];

                pSimpleFillSym = new SimpleFillSymbolClass();
                IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]);
                pSimpleFillSym.Color   = (IColor)pRGBColor;
                pSimpleFillSym.Outline = pOutLines;
                pRender.Symbol[j]      = (ISymbol)pSimpleFillSym;
            }

            //Background Layer
            ISimpleRenderer   pSimpleRender = new SimpleRendererClass();
            ISimpleFillSymbol pBGSymbol     = new SimpleFillSymbolClass();

            pBGSymbol.Color = (IColor)m_pSnippet.getRGB(picBGColor.BackColor.R, picBGColor.BackColor.G, picBGColor.BackColor.B);

            ICartographicLineSymbol pBGOutLines = new CartographicLineSymbol();

            pBGOutLines.Width = 0;
            pBGOutLines.Color = m_pSnippet.getRGB(255, 255, 255);
            pBGSymbol.Outline = pBGOutLines;

            pSimpleRender.Symbol = (ISymbol)pBGSymbol;

            IFeatureLayer pflBG = new FeatureLayerClass();

            pflBG.FeatureClass = pFClass;

            IGeoFeatureLayer pGeoBG = (IGeoFeatureLayer)pflBG;

            pGeoBG.Renderer   = (IFeatureRenderer)pSimpleRender;
            pGeoBG.Selectable = false;

            //Feature Count for each map
            m_intsFeatureCnts = new int[intVerCnt * intHorCnt];

            int l = 0;

            for (int i = 0; i < intVerCnt; i++)
            {
                for (int j = 0; j < intHorCnt; j++)
                {
                    IFeatureLayer pflOutput = new FeatureLayerClass();
                    pflOutput.FeatureClass = pFClass;

                    IGeoFeatureLayer pGeofeatureLayer = (IGeoFeatureLayer)pflOutput;

                    pGeofeatureLayer.Renderer = (IFeatureRenderer)pRender;

                    IFeatureLayerDefinition2 pFDefinition = (IFeatureLayerDefinition2)pGeofeatureLayer;
                    string strWhereClause = null;

                    if (i == 0 && j == 0)
                    {
                        strWhereClause = strVerConFldName + " >= " + m_VerticalBreaks[i].ToString() + " AND " +
                                         strVerConFldName + " <= " + m_VerticalBreaks[i + 1].ToString() + " AND " +
                                         strHorConFldName + " >= " + m_HorizontalBreaks[j].ToString() + " AND " +
                                         strHorConFldName + " <= " + m_HorizontalBreaks[j + 1].ToString();
                    }
                    else if (i != 0 && j == 0)
                    {
                        strWhereClause = strVerConFldName + " > " + m_VerticalBreaks[i].ToString() + " AND " +
                                         strVerConFldName + " <= " + m_VerticalBreaks[i + 1].ToString() + " AND " +
                                         strHorConFldName + " >= " + m_HorizontalBreaks[j].ToString() + " AND " +
                                         strHorConFldName + " <= " + m_HorizontalBreaks[j + 1].ToString();
                    }
                    else if (i == 0 && j != 0)
                    {
                        strWhereClause = strVerConFldName + " >= " + m_VerticalBreaks[i].ToString() + " AND " +
                                         strVerConFldName + " <= " + m_VerticalBreaks[i + 1].ToString() + " AND " +
                                         strHorConFldName + " > " + m_HorizontalBreaks[j].ToString() + " AND " +
                                         strHorConFldName + " <= " + m_HorizontalBreaks[j + 1].ToString();
                    }
                    else
                    {
                        strWhereClause = strVerConFldName + " > " + m_VerticalBreaks[i].ToString() + " AND " +
                                         strVerConFldName + " <= " + m_VerticalBreaks[i + 1].ToString() + " AND " +
                                         strHorConFldName + " > " + m_HorizontalBreaks[j].ToString() + " AND " +
                                         strHorConFldName + " <= " + m_HorizontalBreaks[j + 1].ToString();
                    }

                    pFDefinition.DefinitionExpression = strWhereClause;

                    IQueryFilter pQfilter = new QueryFilterClass();
                    pQfilter.WhereClause = strWhereClause;

                    m_intsFeatureCnts[l] = pGeofeatureLayer.FeatureClass.FeatureCount(pQfilter);
                    m_axMapControls[l].ActiveView.FocusMap.ClearLayers();
                    m_axMapControls[l].ActiveView.FocusMap.AddLayer(pGeoBG);
                    m_axMapControls[l].ActiveView.FocusMap.AddLayer(pGeofeatureLayer);
                    m_axMapControls[l].ActiveView.Extent = m_axMapControls[l].ActiveView.FullExtent;
                    m_axMapControls[l].ActiveView.Refresh();
                    l++;
                }
            }

            lblVariable.Text = "Selected Variable: " + strVarFldName;
            UpdateRange(lvSymbol, m_intClassNumber, cb, arrColors, m_intRounding);

            if (m_blnAddBoxes)
            {
                UpdateTextBoxes();
            }
            else
            {
                AddTextBoxes();
            }

            UpdateLabels();
            UpdateHorVerLabels();
        }
コード例 #26
0
        private static IRenderer createNewDefaultClassBreaksRenderer(GraphicsLayer graphicsLayer, FieldInfo attributeField, double min, double max, int numOfClassBreaks, LinearGradientBrush defaultColorRampGradientBrush, IEnumerable <Symbol> existingSymbolSet)
        {
            Symbol defaultSymbol         = graphicsLayer.GetDefaultSymbolClone();
            ClassBreaksRenderer renderer = new ClassBreaksRenderer()
            {
                Field         = attributeField != null ? attributeField.Name : null,
                DefaultSymbol = defaultSymbol,
            };
            List <Symbol> symbols = new List <Symbol>();

            if (numOfClassBreaks < 2) // classbreaks renderer must have atleast 2 classbreaks
            {
                numOfClassBreaks = 2;
            }
            double rangeSize           = Math.Round((max - min) / numOfClassBreaks, 2);
            double rangeDelta          = 1.0; // delta between 2 class ranges // we choose an integral size
            double lastRangeDeltaIncr  = 1.0; // SL core api requires the last classbreak to be greater than max value of dataset
            bool   fractionalIncrement = false;

            if (Math.Round(max, 0) != max)// we are dealing with a non-integeral values, so our delta's are in fractional increments
            {
                fractionalIncrement = true;
                rangeDelta          = 0.01;
                lastRangeDeltaIncr  = 0.01;
            }

            double startValue = min;

            for (int i = 0; i < numOfClassBreaks; i++)
            {
                Symbol symbol = null;
                if (existingSymbolSet != null)
                {
                    symbol = existingSymbolSet.ElementAtOrDefault(i);
                }
                if (symbol == null)
                {
                    symbol = graphicsLayer.GetDefaultSymbolClone();
                }
                double         endValue   = (startValue + rangeSize) - rangeDelta;
                ClassBreakInfo classBreak = new ClassBreakInfo()
                {
                    MinimumValue = fractionalIncrement ? startValue : Math.Floor(startValue),
                    MaximumValue = fractionalIncrement ? endValue : Math.Floor(endValue),
                    Symbol       = symbol,
                };
                if (i == numOfClassBreaks - 1) // last class break
                {
                    classBreak.MaximumValue = max + lastRangeDeltaIncr;
                    if (max > 1000000)                  // SL has a limitation on values greater than a million http://msdn.microsoft.com/en-us/library/bb412393.aspx
                    {
                        classBreak.MaximumValue += 2.0; // the +2 is to workaround Silverlights limitation of single precision values
                    }
                }
                symbols.Add(symbol);
                renderer.Classes.Add(classBreak);
                startValue += rangeSize;
            }
            if (defaultColorRampGradientBrush != null)
            {
                if (existingSymbolSet == null) // apply the gradient brush, only if symbols have not been pre-defined
                {
                    applyLinearGradientBrushToSymbolSet(symbols, defaultColorRampGradientBrush, defaultSymbol);
                }
            }
            return(renderer);
        }
コード例 #27
0
        private void OnSymbolSelected(SymbolSelectedEventArgs e)
        {
            if (CurrentSymbolImage != null)
            {
                CurrentSymbolImage.Source = new BitmapImage
                {
                    UriSource = new Uri(e.SelectedImage.RelativeUrl, UriKind.Relative)
                };
            }

            PictureMarkerSymbol Symbol = new PictureMarkerSymbol()
            {
                Source = new BitmapImage()
                {
                    UriSource = new Uri(e.SelectedImage.RelativeUrl, UriKind.Relative)
                },
                OffsetX = e.SelectedImage.CenterX,
                OffsetY = e.SelectedImage.CenterY,
                Width   = e.SelectedImage.Width,
                Height  = e.SelectedImage.Height,
                Opacity = OpacitySlider.Value,
                // TODO
                //CursorName = DataContext is TableLayerInfo ? Cursors.Hand.ToString() : Cursors.Arrow.ToString()
            };

            GraphicsLayer layer = DataContext as GraphicsLayer;

            if (layer != null)
            {
                // TODO:- verify if we still need this
                //LayerInfo layerInfo = DataContext as LayerInfo;
                //// refresh the graphics layer
                //GraphicsLayer lyr = ApplicationInstance.Instance.FindLayerForLayerInfo(layerInfo) as GraphicsLayer;
                //if (lyr != null)
                //{
                //    ensureCustomClassBreakRendererIsSet(lyr, layerInfo);
                //    CustomClassBreakRenderer cb = lyr.Renderer as CustomClassBreakRenderer;
                //    if (cb != null)
                //    {
                //        ImageFillSymbol imageFillSymbol = cb.DefaultSymbol as ImageFillSymbol;
                //        if (imageFillSymbol != null)
                //        {
                //            imageFillSymbol.Fill = new ImageBrush
                //            {
                //                ImageSource = new BitmapImage
                //                {
                //                    UriSource = new Uri(e.SelectedImage.RelativeUrl, UriKind.Relative)
                //                }
                //            };
                //            imageFillSymbol.CursorName = DataContext is TableLayerInfo ? Cursors.Hand.ToString() : Cursors.Arrow.ToString();

                //        }
                //    }
                //}

                // update the model
                ClassBreaksRenderer renderer = layer.Renderer as ClassBreaksRenderer;
                if (renderer != null)
                {
                    renderer.DefaultSymbol = Symbol;
                }
            }
            else
            {
                if (SymbolSelected != null)
                {
                    SymbolSelected(this, e);
                }
            }
        }
コード例 #28
0
        void buildAttributeNamesList(GraphicsLayer graphicsLayer, string rendererType)
        {
            if (graphicsLayer == null)
            {
                return;
            }

            Collection <FieldInfo> fields = graphicsLayer.GetValue(ESRI.ArcGIS.Mapping.Core.LayerExtensions.FieldsProperty) as Collection <FieldInfo>;

            if (fields != null)
            {
                if (rendererType == Constants.ClassBreaksRenderer)
                {
                    IEnumerable <FieldInfo> numericFields   = fields.Where <FieldInfo>(f => f.FieldType == FieldType.Integer || f.FieldType == FieldType.DecimalNumber || f.FieldType == FieldType.Currency);
                    FieldInfo           selectedField       = null;
                    ClassBreaksRenderer classBreaksRenderer = graphicsLayer.Renderer as ClassBreaksRenderer;
                    if (classBreaksRenderer != null)
                    {
                        foreach (FieldInfo fieldInfo in numericFields)
                        {
                            if (string.Compare(fieldInfo.Name, classBreaksRenderer.Field) == 0)
                            {
                                selectedField = fieldInfo;
                                break;
                            }
                        }
                    }
                    AttributeName.ItemsSource = numericFields;
                    if (null != selectedField)
                    {
                        _ignoreAttributeChangedEvent = true;
                        AttributeName.SelectedItem   = selectedField;
                        _ignoreAttributeChangedEvent = false;
                    }
                }
                else
                {
                    if (rendererType == Constants.UniqueValueRenderer)
                    {
                        FieldInfo selectedField = null;
                        IEnumerable <FieldInfo> allowedFields       = fields.Where <FieldInfo>(f => f.FieldType != FieldType.Attachment);
                        UniqueValueRenderer     uniqueValueRenderer = graphicsLayer.Renderer as UniqueValueRenderer;
                        if (uniqueValueRenderer != null)
                        {
                            foreach (FieldInfo fieldInfo in allowedFields)
                            {
                                if (string.Compare(fieldInfo.Name, uniqueValueRenderer.Field) == 0)
                                {
                                    selectedField = fieldInfo;
                                    break;
                                }
                            }
                        }
                        AttributeName.ItemsSource = allowedFields;
                        if (null != selectedField)
                        {
                            _ignoreAttributeChangedEvent = true;
                            AttributeName.SelectedItem   = selectedField;
                            _ignoreAttributeChangedEvent = false;
                        }
                    }
                    else
                    {
                        AttributeName.ItemsSource = null;
                    }
                }
            }
        }
コード例 #29
0
        private static IRenderer createClassBreakRendererBasedOnSelectedAttribute(GraphicsLayer graphicsLayer, FieldInfo attributeField, LinearGradientBrush defaultColorRampGradientBrush, GeometryType geometryType, int classBreakCount, IEnumerable <Symbol> existingSymbolSet, out FieldInfo changedAttributeField)
        {
            changedAttributeField = attributeField;
            ClassBreaksRenderer classBreaksRenderer = graphicsLayer.Renderer as ClassBreaksRenderer;

            if (classBreaksRenderer != null)                                                    // Already using classBreaksRenderer
            {
                if (attributeField != null && attributeField.Name != classBreaksRenderer.Field) // Using different attribute for the renderer
                {
                    classBreaksRenderer.Field = attributeField.Name;

                    // Rebuild the class breaks
                    double min, max;
                    getMinAndMaxForGraphicsLayer(graphicsLayer, attributeField, out min, out max);

                    return(createNewDefaultClassBreaksRenderer(graphicsLayer, attributeField, min, max, classBreakCount, defaultColorRampGradientBrush, existingSymbolSet));
                }
            }
            else
            {
                string attributeFieldName = null;
                if (graphicsLayer.Renderer is UniqueValueRenderer)
                {
                    // 1. Check if the renderer has an attribute set as UniqueValue Renderer
                    UniqueValueRenderer uniqueValueRenderer = graphicsLayer.Renderer as UniqueValueRenderer;
                    if (uniqueValueRenderer != null)
                    {
                        attributeFieldName = uniqueValueRenderer.Field;
                    }
                }

                if (string.IsNullOrEmpty(attributeFieldName)) // No attribute known .. use the first numeric field
                {
                    FieldInfo field = null;
                    Collection <FieldInfo> layerFields = ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetFields(graphicsLayer);
                    if (layerFields != null)
                    {
                        field = layerFields.FirstOrDefault <FieldInfo>(f => f.FieldType == FieldType.DecimalNumber || f.FieldType == FieldType.Integer || f.FieldType == FieldType.Currency);
                    }
                    if (field != null)
                    {
                        attributeField        = field;
                        changedAttributeField = field;
                        attributeFieldName    = field.Name;
                    }
                }
                else
                {
                    FieldInfo field = null;
                    Collection <FieldInfo> layerFields = ESRI.ArcGIS.Mapping.Core.LayerExtensions.GetFields(graphicsLayer);
                    if (layerFields != null)
                    {
                        field = layerFields.FirstOrDefault <FieldInfo>(f => f.Name == attributeFieldName); // find matching field
                    }
                    if (field == null || (field.FieldType != FieldType.Integer && field.FieldType != FieldType.DecimalNumber && field.FieldType != FieldType.Currency))
                    {
                        // if the previous field was not a number or currency, then automatically switch it to the first numeric one
                        field = layerFields.FirstOrDefault <FieldInfo>(f => f.FieldType == FieldType.Integer || f.FieldType == FieldType.DecimalNumber || f.FieldType == FieldType.Currency);
                        if (field != null)
                        {
                            attributeField        = field;
                            changedAttributeField = field;
                            attributeFieldName    = field.Name;
                        }
                    }
                }

                if (string.IsNullOrEmpty(attributeFieldName)) // An attribute name must be specified
                {
                    return(null);
                }

                // Loop through graphics and calculate max and min
                double min, max;
                getMinAndMaxForGraphicsLayer(graphicsLayer, attributeField, out min, out max);

                return(createNewDefaultClassBreaksRenderer(graphicsLayer, attributeField, min, max, classBreakCount, defaultColorRampGradientBrush, existingSymbolSet));
            }
            return(null);
        }
コード例 #30
0
        private static IRenderer createNewDefaultClassBreaksRenderer(GraphicsLayer graphicsLayer, FieldInfo attributeField, double min, double max, int numOfClassBreaks, LinearGradientBrush defaultColorRampGradientBrush, IEnumerable<Symbol> existingSymbolSet)
        {
            Symbol defaultSymbol = graphicsLayer.GetDefaultSymbolClone();
            ClassBreaksRenderer renderer = new ClassBreaksRenderer()
            {
                Field = attributeField != null ? attributeField.Name : null,
                DefaultSymbol = defaultSymbol,
            };
            List<Symbol> symbols = new List<Symbol>();
            if (numOfClassBreaks < 2) // classbreaks renderer must have atleast 2 classbreaks
                numOfClassBreaks = 2;
            double rangeSize = Math.Round((max - min) / numOfClassBreaks, 2);
            double rangeDelta = 1.0; // delta between 2 class ranges // we choose an integral size
            double lastRangeDeltaIncr = 1.0; // SL core api requires the last classbreak to be greater than max value of dataset
            bool fractionalIncrement = false;
            if (Math.Round(max, 0) != max)// we are dealing with a non-integeral values, so our delta's are in fractional increments
            {
                fractionalIncrement = true;
                rangeDelta = 0.01;
                lastRangeDeltaIncr = 0.01;
            }

            double startValue = min;
            for (int i = 0; i < numOfClassBreaks; i++)
            {
                Symbol symbol = null;
                if (existingSymbolSet != null)
                    symbol = existingSymbolSet.ElementAtOrDefault(i);
                if (symbol == null)
                    symbol = graphicsLayer.GetDefaultSymbolClone();
                double endValue = (startValue + rangeSize) - rangeDelta;
                ClassBreakInfo classBreak = new ClassBreakInfo()
                {
                    MinimumValue = fractionalIncrement ? startValue : Math.Floor(startValue),
                    MaximumValue = fractionalIncrement ? endValue : Math.Floor(endValue),
                    Symbol = symbol,
                };
                if (i == numOfClassBreaks - 1) // last class break
                {
                    classBreak.MaximumValue = max + lastRangeDeltaIncr;
                    if (max > 1000000) // SL has a limitation on values greater than a million http://msdn.microsoft.com/en-us/library/bb412393.aspx
                        classBreak.MaximumValue += 2.0;// the +2 is to workaround Silverlights limitation of single precision values
                }
                symbols.Add(symbol);
                renderer.Classes.Add(classBreak);
                startValue += rangeSize;
            }
            if (defaultColorRampGradientBrush != null)
            {
                if (existingSymbolSet == null) // apply the gradient brush, only if symbols have not been pre-defined
                {
                    applyLinearGradientBrushToSymbolSet(symbols, defaultColorRampGradientBrush, defaultSymbol);
                }
            }
            return renderer;
        }
コード例 #31
0
        public static IRenderer CloneRenderer(this IRenderer renderer)
        {
            if (renderer == null)
            {
                return(null);
            }
            SimpleRenderer simpleRenderer = renderer as SimpleRenderer;

            if (simpleRenderer != null)
            {
                return(new SimpleRenderer()
                {
                    Symbol = simpleRenderer.Symbol != null?simpleRenderer.Symbol.CloneSymbol() : null,
                });
            }
            else
            {
                ClassBreaksRenderer classBreaksRenderer = renderer as ClassBreaksRenderer;
                if (classBreaksRenderer != null)
                {
                    ClassBreaksRenderer clone = new ClassBreaksRenderer()
                    {
                        Field         = classBreaksRenderer.Field,
                        DefaultSymbol = classBreaksRenderer.DefaultSymbol != null?classBreaksRenderer.DefaultSymbol.CloneSymbol() : null,
                    };
                    if (classBreaksRenderer.Classes != null)
                    {
                        foreach (ClassBreakInfo classBreak in classBreaksRenderer.Classes)
                        {
                            clone.Classes.Add(new ClassBreakInfo()
                            {
                                Description  = classBreak.Description,
                                Label        = classBreak.Label,
                                MaximumValue = classBreak.MaximumValue,
                                MinimumValue = classBreak.MinimumValue,
                                Symbol       = classBreak.Symbol != null ? classBreak.Symbol.CloneSymbol() : null,
                            });
                        }
                    }
                    return(clone);
                }
                else
                {
                    UniqueValueRenderer uniqueValueRenderer = renderer as UniqueValueRenderer;
                    if (uniqueValueRenderer != null)
                    {
                        UniqueValueRenderer clone = new UniqueValueRenderer()
                        {
                            Field         = uniqueValueRenderer.Field,
                            DefaultSymbol = uniqueValueRenderer.DefaultSymbol != null?uniqueValueRenderer.DefaultSymbol.CloneSymbol() : null,
                        };
                        if (uniqueValueRenderer.Infos != null)
                        {
                            foreach (UniqueValueInfo uniqueValue in uniqueValueRenderer.Infos)
                            {
                                clone.Infos.Add(new UniqueValueInfo()
                                {
                                    Description = uniqueValue.Description,
                                    Label       = uniqueValue.Label,
                                    Value       = uniqueValue.Value,
                                    Symbol      = uniqueValue.Symbol != null ? uniqueValue.Symbol.CloneSymbol() : null,
                                });
                            }
                        }
                        return(clone);
                    }
                }
            }
            return(null);
        }
コード例 #32
0
 public static IRenderer CloneRenderer(this IRenderer renderer)
 {
     if (renderer == null)
         return null;
     SimpleRenderer simpleRenderer = renderer as SimpleRenderer;
     if (simpleRenderer != null)
     {
         return new SimpleRenderer()
         {
             Symbol = simpleRenderer.Symbol != null ? simpleRenderer.Symbol.CloneSymbol() : null,
         };
     }
     else
     {
         ClassBreaksRenderer classBreaksRenderer = renderer as ClassBreaksRenderer;
         if (classBreaksRenderer != null)
         {
             ClassBreaksRenderer clone = new ClassBreaksRenderer() { 
                  Field = classBreaksRenderer.Field,
                  DefaultSymbol = classBreaksRenderer.DefaultSymbol != null ? classBreaksRenderer.DefaultSymbol.CloneSymbol() : null,
             };
             if (classBreaksRenderer.Classes != null)
             {
                 foreach (ClassBreakInfo classBreak in classBreaksRenderer.Classes)
                 {
                     clone.Classes.Add(new ClassBreakInfo() { 
                          Description = classBreak.Description,
                          Label = classBreak.Label,
                          MaximumValue = classBreak.MaximumValue,
                          MinimumValue = classBreak.MinimumValue,
                          Symbol = classBreak.Symbol != null ? classBreak.Symbol.CloneSymbol() : null,
                     });
                 }
             }
             return clone;
         }
         else
         {
             UniqueValueRenderer uniqueValueRenderer = renderer as UniqueValueRenderer;
             if (uniqueValueRenderer != null)
             {
                 UniqueValueRenderer clone = new UniqueValueRenderer() { 
                      Field = uniqueValueRenderer.Field,
                      DefaultSymbol = uniqueValueRenderer.DefaultSymbol != null ? uniqueValueRenderer.DefaultSymbol.CloneSymbol() : null,
                 };
                 if (uniqueValueRenderer.Infos != null)
                 {
                     foreach (UniqueValueInfo uniqueValue in uniqueValueRenderer.Infos)
                     {
                         clone.Infos.Add(new UniqueValueInfo()
                         {
                             Description = uniqueValue.Description,
                             Label = uniqueValue.Label,
                             Value = uniqueValue.Value,
                             Symbol = uniqueValue.Symbol != null ? uniqueValue.Symbol.CloneSymbol() : null,
                         });
                     }
                 }
                 return clone;
             }
         }
     }
     return null;
 }
コード例 #33
0
        public void SetShapeRangeValues(DashboardHelper dashboardHelper, string shapeKey, string dataKey, string valueField, Color lowColor, Color highColor, int classCount)
        {
            try
            {
                this.classCount = classCount;
                this.dashboardHelper = dashboardHelper;
                this.shapeKey = shapeKey;
                this.dataKey = dataKey;
                this.valueField = valueField;
                this.lowColor = lowColor;
                this.highColor = highColor;

                List<string> columnNames = new List<string>();
                if (dashboardHelper.IsUsingEpiProject)
                {
                    columnNames.Add("UniqueKey");
                }
                columnNames.Add(valueField);
                columnNames.Add(dataKey);

                DataTable loadedData;

                if (valueField.Equals("{Record Count}"))
                {
                    GadgetParameters gadgetOptions = new GadgetParameters();
                    gadgetOptions.MainVariableName = dataKey;

                    Dictionary<string, string> inputVariableList = new Dictionary<string, string>();
                    inputVariableList.Add("freqvar", dataKey);
                    inputVariableList.Add("allvalues", "false");
                    inputVariableList.Add("showconflimits", "false");
                    inputVariableList.Add("showcumulativepercent", "false");
                    inputVariableList.Add("includemissing", "false");
                    inputVariableList.Add("maxrows", "500");

                    gadgetOptions.InputVariableList = inputVariableList;
                    loadedData = dashboardHelper.GenerateFrequencyTable(gadgetOptions).First().Key;
                    foreach (DataRow dr in loadedData.Rows)
                    {
                        dr[0] = dr[0].ToString().Trim();
                    }
                    valueField = "freq";
                }
                else
                {
                    loadedData = dashboardHelper.GenerateTable(columnNames);
                }

                GraphicsLayer graphicsLayer = myMap.Layers[layerId.ToString()] as GraphicsLayer;
                CreateColorList(lowColor, highColor);
                ThematicItem thematicItem = new ThematicItem() { Name = dataKey, Description = dataKey, CalcField = "" };
                List<double> valueList = new List<double>();
                for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                {
                    Graphic graphicFeature = graphicsLayer.Graphics[i];
                    //string filterExpression = dataKey + " = '" + graphicFeature.Attributes[shapeKey].ToString().Trim() + "'";
                    string filterExpression = "";
                    if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        filterExpression += "[";
                    filterExpression += dataKey;
                    if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                        filterExpression += "]";
                    filterExpression += " = '" + graphicFeature.Attributes[shapeKey].ToString().Replace("'","''").Trim() + "'";

                    double graphicValue = Double.PositiveInfinity;
                    try
                    {
                        graphicValue = Convert.ToDouble(loadedData.Select(filterExpression)[0][valueField]);
                    }
                    catch (Exception)
                    {
                        graphicValue = Double.PositiveInfinity;
                    }

                    string graphicName = graphicFeature.Attributes[shapeKey].ToString();

                    if (i == 0)
                    {
                        thematicItem.Min = Double.PositiveInfinity;
                        thematicItem.Max = Double.NegativeInfinity;
                        thematicItem.MinName = string.Empty;
                        thematicItem.MaxName = string.Empty;
                    }
                    else
                    {
                        if (graphicValue < thematicItem.Min) { thematicItem.Min = graphicValue; thematicItem.MinName = graphicName; }
                        if (graphicValue > thematicItem.Max && graphicValue != Double.PositiveInfinity) { thematicItem.Max = graphicValue; thematicItem.MaxName = graphicName; }
                    }

                    if (graphicValue != Double.PositiveInfinity)
                    {
                        valueList.Add(graphicValue);
                    }
                }
                thematicItem.RangeStarts = new List<double>();

                double totalRange = thematicItem.Max - thematicItem.Min;
                double portion = totalRange / classCount;

                thematicItem.RangeStarts.Add(thematicItem.Min);
                double startRangeValue = thematicItem.Min;
                IEnumerable<double> valueEnumerator =
                from aValue in valueList
                orderby aValue
                select aValue;

                if (classCount == 2)
                {
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt(valueList.Count / 3));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 2) / 3));
                }
                else if (classCount == 3)
                {
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt(valueList.Count / 4));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 2) / 4));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 3) / 4));
                }
                else if (classCount == 4)
                {
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt(valueList.Count / 5));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 2) / 5));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 3) / 5));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 4) / 5));
                }
                else
                {
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt(valueList.Count / 6));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 2) / 6));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 3) / 6));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 4) / 6));
                    thematicItem.RangeStarts.Add(valueEnumerator.ElementAt((valueList.Count * 5) / 6));
                }

                // Create graphic features and set symbol using the class range which contains the value
                List<SolidColorBrush> brushList = ColorList[_colorShadeIndex];
                if (graphicsLayer.Graphics != null && graphicsLayer.Graphics.Count > 0)
                {

                    for (int i = 0; i < graphicsLayer.Graphics.Count; i++)
                    {
                        Graphic graphicFeature = graphicsLayer.Graphics[i];

                        //string filterExpression = dataKey + " = '" + graphicFeature.Attributes[shapeKey].ToString().Trim() + "'";
                        string filterExpression = "";
                        if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                            filterExpression += "[";
                        filterExpression += dataKey;
                        if (dataKey.Contains(" ") || dataKey.Contains("$") || dataKey.Contains("#"))
                            filterExpression += "]";
                        filterExpression += " = '" + graphicFeature.Attributes[shapeKey].ToString().Replace("'", "''").Trim() + "'";

                        double graphicValue = Double.PositiveInfinity;
                        try
                        {
                            graphicValue = Convert.ToDouble(loadedData.Select(filterExpression)[0][valueField]);
                        }
                        catch (Exception ex)
                        {
                            graphicValue = Double.PositiveInfinity;
                        }

                        if (graphicValue != Double.PositiveInfinity)
                        {
                            if (graphicFeature.Attributes.Keys.Contains("EpiInfoValCol"))
                            {
                                graphicFeature.Attributes["EpiInfoValCol"] = graphicValue;
                            }
                            else
                            {
                                graphicFeature.Attributes.Add("EpiInfoValCol", graphicValue);
                            }
                        }

                        int brushIndex = GetRangeIndex(graphicValue, thematicItem.RangeStarts);

                        TextBlock t = new TextBlock();
                        t.Background = Brushes.White;
                        if (graphicValue == Double.PositiveInfinity)
                        {
                            t.Text = graphicFeature.Attributes[shapeKey].ToString().Trim() + " : No Data";
                        }
                        else
                        {
                            t.Text = graphicFeature.Attributes[shapeKey].ToString().Trim() + " : " + graphicValue.ToString();
                        }
                        t.FontSize = 14;
                        Border border = new Border();
                        border.BorderThickness = new Thickness(1);
                        Panel panel = new StackPanel();
                        panel.Children.Add(t);
                        border.Child = panel;

                        graphicFeature.MapTip = border;
                    }
                    ClassBreaksRenderer renderer = new ClassBreaksRenderer();
                    renderer.Field = "EpiInfoValCol";
                    renderer.DefaultSymbol = new SimpleFillSymbol()
                        {
                            Fill = new SolidColorBrush(Colors.Transparent),
                            BorderBrush = new SolidColorBrush(Colors.Black),
                            BorderThickness = 1
                        };
                    renderer.Classes.Add(new ClassBreakInfo()
                    {
                        MinimumValue = thematicItem.Min,
                        MaximumValue = thematicItem.RangeStarts[1],
                        Symbol = new SimpleFillSymbol()
                            {
                                Fill = brushList[0],
                                BorderBrush = new SolidColorBrush(Colors.Black),
                                BorderThickness = 1
                            }
                    });
                    renderer.Classes.Add(new ClassBreakInfo()
                    {
                        MinimumValue = thematicItem.RangeStarts[1],
                        MaximumValue = thematicItem.RangeStarts[2],
                        Symbol = new SimpleFillSymbol()
                        {
                            Fill = brushList[1],
                            BorderBrush = new SolidColorBrush(Colors.Black),
                            BorderThickness = 1
                        }
                    });
                    if (classCount > 2)
                    {
                        renderer.Classes.Add(new ClassBreakInfo()
                        {
                            MinimumValue = thematicItem.RangeStarts[2],
                            MaximumValue = thematicItem.RangeStarts[3],
                            Symbol = new SimpleFillSymbol()
                            {
                                Fill = brushList[2],
                                BorderBrush = new SolidColorBrush(Colors.Black),
                                BorderThickness = 1
                            }
                        });
                    }
                    if (classCount > 3)
                    {
                        renderer.Classes.Add(new ClassBreakInfo()
                        {
                            MinimumValue = thematicItem.RangeStarts[3],
                            MaximumValue = thematicItem.RangeStarts[4],
                            Symbol = new SimpleFillSymbol()
                            {
                                Fill = brushList[3],
                                BorderBrush = new SolidColorBrush(Colors.Black),
                                BorderThickness = 1
                            }
                        });
                    }
                    if (classCount > 4)
                    {
                        renderer.Classes.Add(new ClassBreakInfo()
                        {
                            MinimumValue = thematicItem.RangeStarts[4],
                            MaximumValue = thematicItem.RangeStarts[5],
                            Symbol = new SimpleFillSymbol()
                            {
                                Fill = brushList[4],
                                BorderBrush = new SolidColorBrush(Colors.Black),
                                BorderThickness = 1
                            }
                        });
                    }
                    if (classCount > 5)
                    {
                        renderer.Classes.Add(new ClassBreakInfo()
                        {
                            MinimumValue = thematicItem.RangeStarts[5],
                            MaximumValue = thematicItem.RangeStarts[6],
                            Symbol = new SimpleFillSymbol()
                            {
                                Fill = brushList[5],
                                BorderBrush = new SolidColorBrush(Colors.Black),
                                BorderThickness = 1
                            }
                        });
                    }
                    renderer.Classes.Add(new ClassBreakInfo()
                    {
                        MinimumValue = thematicItem.RangeStarts[classCount - 1],
                        MaximumValue = thematicItem.Max,
                        Symbol = new SimpleFillSymbol()
                        {
                            Fill = brushList[classCount],
                            BorderBrush = new SolidColorBrush(Colors.Black),
                            BorderThickness = 1
                        }
                    });

                    graphicsLayer.Renderer = renderer;
                }

                if (LegendStackPanel == null)
                {
                    LegendStackPanel = new StackPanel();
                }
                LegendStackPanel.Children.Clear();

                System.Windows.Controls.ListBox legendList = new System.Windows.Controls.ListBox();
                legendList.Margin = new Thickness(5);
                legendList.Background = Brushes.White;// new LinearGradientBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF), Color.FromArgb(0x7F, 0xFF, 0xFF, 0xFF), 45);
                legendList.BorderBrush = Brushes.Black;
                legendList.BorderThickness = new Thickness(3);
                //LegendTitle.Text = thematicItem.Description;

                for (int c = 0; c <= classCount; c++)
                {
                    Rectangle swatchRect = new Rectangle()
                    {
                        Width = 20,
                        Height = 20,
                        Stroke = new SolidColorBrush(Colors.Black),
                        Fill = brushList[c]
                    };

                    TextBlock classTextBlock = new TextBlock();

                    // First classification
                    if (c == 0)
                        classTextBlock.Text = String.Format("  Less than or equal to {0}", Math.Round(thematicItem.RangeStarts[1], 2));
                    // Last classification
                    else if (c == classCount)
                        classTextBlock.Text = String.Format("  {0} and above", Math.Round(thematicItem.RangeStarts[c], 2));
                    // Middle classifications
                    else
                    {
                        if (thematicItem.RangeStarts[c] == thematicItem.RangeStarts[c + 1])
                            classTextBlock.Text = String.Format("  Exactly {0}", Math.Round(thematicItem.RangeStarts[c], 2));
                        else
                            classTextBlock.Text = String.Format("  {0} to {1}", Math.Round(thematicItem.RangeStarts[c], 2), Math.Round(thematicItem.RangeStarts[c + 1], 2));
                    }

                    StackPanel classStackPanel = new StackPanel();
                    classStackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
                    classStackPanel.Children.Add(swatchRect);
                    classStackPanel.Children.Add(classTextBlock);

                    legendList.Items.Add(classStackPanel);
                }

                TextBlock minTextBlock = new TextBlock();
                StackPanel minStackPanel = new StackPanel();
                minStackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
                minTextBlock.Text = String.Format("Min: {0} ({1})", thematicItem.Min, string.IsNullOrEmpty(thematicItem.MinName) ? string.Empty : thematicItem.MinName.Trim());
                minStackPanel.Children.Add(minTextBlock);
                legendList.Items.Add(minStackPanel);

                TextBlock maxTextBlock = new TextBlock();
                StackPanel maxStackPanel = new StackPanel();
                maxStackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
                maxTextBlock.Text = String.Format("Max: {0} ({1})", thematicItem.Max, string.IsNullOrEmpty(thematicItem.MaxName) ? string.Empty : thematicItem.MaxName.Trim());
                maxStackPanel.Children.Add(maxTextBlock);
                legendList.Items.Add(maxStackPanel);

                LegendStackPanel.Children.Add(legendList);

            }
            catch (Exception ex)
            {
            }
        }
コード例 #34
0
        void queryTaskPolygon_ExecuteCompleted(object sender, QueryEventArgs args)
        {
            FeatureSet featureSet = args.FeatureSet;

            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }

            GraphicsLayer graphicsLayer = MyMap.Layers["MyPolygonGraphicsLayer"] as GraphicsLayer;

            Random random = new Random();

            // Random switch between class breaks and unique value renderers
            if (random.Next(0, 2) == 0)
            {
                ClassBreaksRenderer classBreakRenderer = new ClassBreaksRenderer();
                classBreakRenderer.Field = "POP2008";
                int classCount = 6;

                List <double> valueList = new List <double>();
                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    graphicsLayer.Graphics.Add(graphic);
                    valueList.Add((int)graphic.Attributes[classBreakRenderer.Field]);
                }

                // LINQ
                IEnumerable <double> valueEnumerator =
                    from aValue in valueList
                    orderby aValue
                    select aValue;

                int increment = Convert.ToInt32(Math.Ceiling((double)args.FeatureSet.Features.Count / classCount));
                int rgbFactor = 255 / classCount;
                int j         = 255;

                for (int i = increment; i < valueList.Count; i += increment)
                {
                    ClassBreakInfo classBreakInfo = new ClassBreakInfo();

                    if (i == increment)
                    {
                        classBreakInfo.MinimumValue = 0;
                    }
                    else
                    {
                        classBreakInfo.MinimumValue = valueEnumerator.ElementAt(i - increment);
                    }

                    classBreakInfo.MaximumValue = valueEnumerator.ElementAt(i);

                    SimpleFillSymbol symbol = new SimpleFillSymbol()
                    {
                        Fill            = new SolidColorBrush(Color.FromArgb(192, (byte)j, (byte)j, (byte)j)),
                        BorderBrush     = new SolidColorBrush(Colors.Transparent),
                        BorderThickness = 1
                    };

                    classBreakInfo.Symbol = symbol;
                    classBreakRenderer.Classes.Add(classBreakInfo);

                    j = j - rgbFactor;
                }

                // Set maximum value for largest class break
                classBreakRenderer.Classes[classBreakRenderer.Classes.Count - 1].MaximumValue = valueEnumerator.ElementAt(valueList.Count - 1) + 1;

                graphicsLayer.Renderer = classBreakRenderer;
            }
            else
            {
                UniqueValueRenderer uniqueValueRenderer = new UniqueValueRenderer();
                uniqueValueRenderer.Field = "STATE_NAME";

                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    graphicsLayer.Graphics.Add(graphic);
                    UniqueValueInfo uniqueValueInfo = new UniqueValueInfo();

                    SimpleFillSymbol symbol = new SimpleFillSymbol()
                    {
                        Fill            = new SolidColorBrush(Color.FromArgb(192, (byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255))),
                        BorderBrush     = new SolidColorBrush(Colors.Transparent),
                        BorderThickness = 1
                    };

                    uniqueValueInfo.Symbol = symbol;
                    uniqueValueInfo.Value  = graphic.Attributes["STATE_NAME"];
                    uniqueValueRenderer.Infos.Add(uniqueValueInfo);
                }

                graphicsLayer.Renderer = uniqueValueRenderer;
            }
        }
コード例 #35
0
        public Traffic()
        {
            try
            {
                traffic        = GlobalLayers.TrafficLayer;
                traffic_lights = GlobalLayers.LightsLayer;

                traffic.OutFields = new OutFields {
                    "*"
                };
                traffic_lights.OutFields = new OutFields {
                    "*"
                };
            }
            catch (Exception)
            {
                return;
            }


            // 设定道路的流量渲染模型
            ClassBreaksRenderer rTrafficRoad = new ClassBreaksRenderer(); // 流量

            rTrafficRoad.Field = "SHAPE_Length";                          // 指定渲染道路属性字段
            // 设定红绿灯的3状态渲染
            ClassBreakInfo _Normal = new ClassBreakInfo();

            _Normal.MinimumValue = 0;
            _Normal.MaximumValue = 100;
            _Normal.Symbol       = App.Current.Resources["NORMAL"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            ClassBreakInfo _Middle = new ClassBreakInfo();

            _Middle.MinimumValue = 101;
            _Middle.MaximumValue = 200;
            _Middle.Symbol       = App.Current.Resources["MIDDLE"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            ClassBreakInfo _High = new ClassBreakInfo();

            _High.MinimumValue = 201;
            _High.MaximumValue = 1000;
            _High.Symbol       = App.Current.Resources["BUSY"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            rTrafficRoad.Classes.Add(_Normal);
            rTrafficRoad.Classes.Add(_Middle);
            rTrafficRoad.Classes.Add(_High);
            traffic.Renderer = rTrafficRoad;


            foreach (Graphic e in traffic as GraphicsLayer)
            {
                e.Attributes["SHAPE_Length"] = 0;
            }

            traffic.Visible = true;



            ClassBreaksRenderer rTrafficLights = new ClassBreaksRenderer(); // 红绿灯

            rTrafficLights.Field = "status";                                // 指定渲染的红绿灯属性字段
            // 设定红绿灯的3状态渲染
            ClassBreakInfo r = new ClassBreakInfo();

            r.MinimumValue = 0;
            r.MaximumValue = 0;
            r.Symbol       = App.Current.Resources["REDFLAG"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            ClassBreakInfo y = new ClassBreakInfo();

            y.MinimumValue = 1;
            y.MaximumValue = 1;
            y.Symbol       = App.Current.Resources["YELLOWFLAG"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            ClassBreakInfo g = new ClassBreakInfo();

            g.MinimumValue = 2;
            g.MaximumValue = 2;
            g.Symbol       = App.Current.Resources["GREENFLAG"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            rTrafficLights.Classes.Add(r);
            rTrafficLights.Classes.Add(y);
            rTrafficLights.Classes.Add(g);
            traffic_lights.Renderer = rTrafficLights;

            //         GlobalLayers._MainMap.Layers.Add(traffic_lights);
            foreach (Graphic e in traffic_lights as GraphicsLayer)
            {
                e.Attributes["status"] = 1;
            }

            traffic_lights.Visible = true;

            /*
             * road_traffic_stat.Symbol = App.Current.Resources["TRAFFIC_NORMAL"] as ESRI.ArcGIS.Client.Symbols.Symbol;
             * traffic.Renderer = road_traffic_stat;
             */

/*
 *          ArcGISLocalFeatureLayer FLAG = new ArcGISLocalFeatureLayer("dhnew\\traffic.mpk", "FLAG"); // 道路中心线_Clip/ FLAG
 *          SimpleRenderer traffic_stat = new SimpleRenderer();
 *          traffic_stat.Symbol = App.Current.Resources["REDFLAG"] as ESRI.ArcGIS.Client.Symbols.Symbol;
 *          FLAG.Renderer = traffic_stat;
 *          GlobalLayers._MainMap.Layers.Add(FLAG);
 */


            try
            {
                IConnectionFactory factory;

                factory = new ConnectionFactory(ConfigurationManager.AppSettings["MQ"].ToString());   // 连接MQ数据发布服务器
                IConnection connection = factory.CreateConnection();
                connection.Start();
                ISession session = connection.CreateSession();
                // 连接红绿灯 主题
                IMessageConsumer consumerLights = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(ConfigurationManager.AppSettings["Topic_Traffic_lights"].ToString()), "GQY_L", null, false);
                consumerLights.Listener += new MessageListener(ProcessLights);
                IMessageConsumer consumerTraffic = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(ConfigurationManager.AppSettings["Topic_Traffic"].ToString()), "GQY_T", null, false);
                consumerTraffic.Listener += new MessageListener(ProcessTraffic);
            }
            catch (Exception e)
            {
                MessageBox.Show("订阅交通信号失败" + e.ToString());
            }
        }
コード例 #36
0
        public void ApplyClsssBreaks(IGeoFeatureLayer geoLayer, string aFieldName, long numBreaks)
        {
            //Create a Table from the geofeature layer
            ITable table = geoLayer as ITable;
            //ITableHistogram tableHistogram=new TableHistogram(); that is error but canbe coded by following
            TableHistogram  tableHistogram2 = new TableHistogram();
            ITableHistogram tableHistogram  = tableHistogram2 as ITableHistogram;

            tableHistogram.Table = table;
            tableHistogram.Field = aFieldName;
            IHistogram histogram = tableHistogram as IHistogram;
            object     vValues;
            object     vFregs;

            //先统计每个值和各个值出现的次数
            histogram.GetHistogram(out vValues, out vFregs);

            //Classify the data
            IClassifyGEN classifyGEN = new EqualInterval();
            int          intBreaks   = Convert.ToInt32(numBreaks);

            classifyGEN.Classify(vValues, vFregs, ref intBreaks);

            double[] vBreaks = (double[])classifyGEN.ClassBreaks;
            //books
            int classCount = vBreaks.GetUpperBound(0);
            //Create the ClassBreaksRenderer
            IClassBreaksRenderer classBreaksRenderer = new ClassBreaksRenderer();

            //assigh a field as breaked
            classBreaksRenderer.Field = aFieldName;
            //passed as a string to the sub routine
            //classBreaksRenderer.BreakCount =classCount;
            classBreaksRenderer.BreakCount           = (int)(numBreaks);
            classBreaksRenderer.SortClassesAscending = false;


            IRgbColor fromColor = new RgbColor();

            fromColor.UseWindowsDithering = true;
            fromColor.RGB = Information.RGB(0, 0, 255);
            IRgbColor toColor = new RgbColor();

            toColor.UseWindowsDithering = true;
            toColor.RGB = Information.RGB(255, 0, 0);
            //Set up the fill symbol
            ISymbol pSym;
            //ISimpleFillSymbol sym = new SimpleFillSymbol();
            IColor fillColor;

            MessageBox.Show("vBreaks.Length: " + vBreaks.Length.ToString());

            IEnumColors colors = GetColors(fromColor.RGB, toColor.RGB, numBreaks);

            for (int i = 0; i <= (vBreaks.Length - 2); i++)
            {
                fillColor = colors.Next();
                //code by jin
                if (geoLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    ISimpleFillSymbol sym = new SimpleFillSymbol();
                    sym.Color = fillColor;
                    pSym      = sym as ISymbol;
                }
                else if (geoLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    ISimpleLineSymbol sym = new SimpleLineSymbol();
                    sym.Color = fillColor;
                    pSym      = sym as ISymbol;
                }
                else
                {
                    ISimpleMarkerSymbol sym = new SimpleMarkerSymbol();
                    sym.Color = fillColor;
                    pSym      = sym as ISymbol;
                }
                classBreaksRenderer.set_Break(i, vBreaks[i + 1]);
                classBreaksRenderer.set_Symbol(i, pSym);
                geoLayer.Renderer = classBreaksRenderer as IFeatureRenderer;
                axMapControl1.ActiveView.Refresh();
                axTOCControl1.Update();
            }
        }
コード例 #37
0
        private void SetRenderers()
        {
            SimpleRenderer simpleRenderer = new SimpleRenderer()
            {
                Description = "Rivers",
                Label       = "Rivers",
                Symbol      = new SimpleLineSymbol()
                {
                    Color = Colors.Blue, Style = SimpleLineStyle.Dash, Width = 2
                }
            };

            (mapView1.Map.Layers["MyFeatureLayerSimple"] as FeatureLayer).Renderer = simpleRenderer;

            UniqueValueRenderer uvr = new UniqueValueRenderer();

            uvr.Fields = new ObservableCollection <string>(new string [] { "STATE_NAME" });
            uvr.Infos.Add(new UniqueValueInfo {
                Values = new ObservableCollection <object>(new object[] { "New Mexico" }), Symbol = new SimpleFillSymbol()
                {
                    Color = Colors.Yellow
                }
            });
            uvr.Infos.Add(new UniqueValueInfo {
                Values = new ObservableCollection <object>(new object[] { "Texas" }), Symbol = new SimpleFillSymbol()
                {
                    Color = Colors.PaleGreen
                }
            });
            uvr.Infos.Add(new UniqueValueInfo {
                Values = new ObservableCollection <object>(new object[] { "Arizona" }), Symbol = new SimpleFillSymbol()
                {
                    Color = Colors.YellowGreen
                }
            });

            (mapView1.Map.Layers["MyFeatureLayerUnique"] as FeatureLayer).Renderer = uvr;


            ClassBreaksRenderer CBR = new ClassBreaksRenderer()
            {
                DefaultLabel  = "All Other Values",
                DefaultSymbol = new SimpleMarkerSymbol()
                {
                    Color = Colors.Black, Style = SimpleMarkerStyle.Cross, Size = 10
                },
                Field   = "POP1990",
                Minimum = 0
            };

            CBR.Infos.Add(new ClassBreakInfo()
            {
                Maximum     = 30000,
                Label       = "0-30000",
                Description = "Pop between 0 and 30000",
                Symbol      = new SimpleMarkerSymbol()
                {
                    Color = Colors.Yellow, Size = 8, Style = SimpleMarkerStyle.Circle
                }
            });
            CBR.Infos.Add(new ClassBreakInfo()
            {
                Maximum     = 300000,
                Label       = "30000-300000",
                Description = "Pop between 30000 and 300000",
                Symbol      = new SimpleMarkerSymbol()
                {
                    Color = Colors.Red, Size = 10, Style = SimpleMarkerStyle.Circle
                }
            });

            CBR.Infos.Add(new ClassBreakInfo()
            {
                Maximum     = 5000000,
                Label       = "300000-5000000",
                Description = "Pop between 300000 and 5000000",
                Symbol      = new SimpleMarkerSymbol()
                {
                    Color = Colors.Orange, Size = 12, Style = SimpleMarkerStyle.Circle
                }
            });
            (mapView1.Map.Layers["MyFeatureLayerClassBreak"] as FeatureLayer).Renderer = CBR;
        }
コード例 #38
0
        void queryTaskPolygon_ExecuteCompleted(object sender, QueryEventArgs args)
        {
            FeatureSet featureSet = args.FeatureSet;

            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }

            GraphicsLayer graphicsLayer = MyMap.Layers["MyPolygonGraphicsLayer"] as GraphicsLayer;

            Random random = new Random();

            // Random switch between class breaks and unique value renderers
            if (random.Next(0, 2) == 0)
            {
                ClassBreaksRenderer classBreakRenderer = new ClassBreaksRenderer();
                classBreakRenderer.Field = "POP2000";
                int classCount = 6;

                List<double> valueList = new List<double>();
                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    graphicsLayer.Graphics.Add(graphic);
                    valueList.Add((int)graphic.Attributes[classBreakRenderer.Field]);
                }

                // LINQ
                IEnumerable<double> valueEnumerator =
                   from aValue in valueList
                   orderby aValue
                   select aValue;

                int increment = Convert.ToInt32(Math.Ceiling(args.FeatureSet.Features.Count / classCount));
                int rgbFactor = 255 / classCount;
                int j = 255;

                for (int i = increment; i < valueList.Count; i += increment)
                {
                    ClassBreakInfo classBreakInfo = new ClassBreakInfo();

                    if (i == increment)
                        classBreakInfo.MinimumValue = 0;
                    else
                        classBreakInfo.MinimumValue = valueEnumerator.ElementAt(i - increment);

                    classBreakInfo.MaximumValue = valueEnumerator.ElementAt(i);

                    SimpleFillSymbol symbol = new SimpleFillSymbol()
                    {
                        Fill = new SolidColorBrush(Color.FromArgb(192, (byte)j, (byte)j, (byte)j)),
                        BorderBrush = new SolidColorBrush(Colors.Transparent),
                        BorderThickness = 1
                    };

                    classBreakInfo.Symbol = symbol;
                    classBreakRenderer.Classes.Add(classBreakInfo);

                    j = j - rgbFactor;
                }

                // Set maximum value for largest class break
                classBreakRenderer.Classes[classBreakRenderer.Classes.Count - 1].MaximumValue = valueEnumerator.ElementAt(valueList.Count - 1) + 1;

                graphicsLayer.Renderer = classBreakRenderer;

            }
            else
            {
                UniqueValueRenderer uniqueValueRenderer = new UniqueValueRenderer();
                uniqueValueRenderer.DefaultSymbol = LayoutRoot.Resources["RedFillSymbol"] as Symbol;
                uniqueValueRenderer.Field = "STATE_NAME";

                foreach (Graphic graphic in args.FeatureSet.Features)
                {
                    graphicsLayer.Graphics.Add(graphic);
                    UniqueValueInfo uniqueValueInfo = new UniqueValueInfo();

                    SimpleFillSymbol symbol = new SimpleFillSymbol()
                    {
                        Fill = new SolidColorBrush(Color.FromArgb(192, (byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255))),
                        BorderBrush = new SolidColorBrush(Colors.Transparent),
                        BorderThickness = 1
                    };

                    uniqueValueInfo.Symbol = symbol;
                    uniqueValueInfo.Value = graphic.Attributes["STATE_NAME"];
                    uniqueValueRenderer.Infos.Add(uniqueValueInfo);
                }

                graphicsLayer.Renderer = uniqueValueRenderer;
            }
        }
コード例 #39
0
        // Create a legend from the class breaks renderer
        private async Task CreateLegend(ClassBreaksRenderer renderer)
        {
            var tasks = renderer.Infos.Select(info => info.Symbol.CreateSwatchAsync());
            var images = await Task.WhenAll(tasks);

            listLegend.ItemsSource = renderer.Infos
                .Select((info, idx) => new ClassBreakLegendItem() { SymbolImage = images[idx], Label = info.Label });
        }
コード例 #40
0
        private void ApplyRangeValueClick(object sender, RoutedEventArgs e)
        {
            ClassBreaksRenderer newClassBreaksRenderer = new ClassBreaksRenderer();

            newClassBreaksRenderer.Field = "Educacion";
            var Infos = new ClassBreakInfoCollection();

            Infos.Add(new ClassBreakInfo()
            {
                Minimum = 0,
                Maximum = 5,
                Symbol  = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 0)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 10,
                Symbol  = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 100, 255, 100)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 20,
                Symbol  = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 200)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 30,
                Symbol  = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 255)
                }
            });

            Infos.Add(new ClassBreakInfo()
            {
                Maximum = 41,
                Symbol  = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 0, 255)
                }
            });
            newClassBreaksRenderer.Infos = Infos;
            var layer = mapView1.Map.Layers["Col"] as ArcGISDynamicMapServiceLayer;
            LayerDrawingOptionCollection layerDrawingOptionCollection = new LayerDrawingOptionCollection()
            {
                new LayerDrawingOptions()
                {
                    LayerID  = 3,
                    Renderer = newClassBreaksRenderer
                }
            };

            layer.LayerDrawingOptions = layerDrawingOptionCollection;

            layer.VisibleLayers = new ObservableCollection <int> {
                3
            };
        }
コード例 #41
0
        private void ApplyRangeValueClick(object sender, RoutedEventArgs e)
        {
            ClassBreaksRenderer newClassBreaksRenderer = new ClassBreaksRenderer();
            newClassBreaksRenderer.Field = "POP00_SQMI";

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MinimumValue = 0,
                MaximumValue = 12,
                Symbol = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 31.3,
                Symbol = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 100, 255, 100))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 59.7,
                Symbol = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 200))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 146.2,
                Symbol = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 255, 255))
                }
            });

            newClassBreaksRenderer.Classes.Add(new ClassBreakInfo()
            {
                MaximumValue = 57173,
                Symbol = new SimpleFillSymbol()
                {
                    Fill = new SolidColorBrush(Color.FromArgb(255, 0, 0, 255))
                }
            });

            LayerDrawingOptions layerDrawOptions = new LayerDrawingOptions();
            layerDrawOptions.LayerID = 3;
            layerDrawOptions.Renderer = newClassBreaksRenderer;

            (MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer).LayerDrawingOptions =
                new LayerDrawingOptionsCollection() { layerDrawOptions };
            (MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer).VisibleLayers = new int[] { 3 };
            // Changing VisibleLayers will refresh the layer, otherwise an explicit call to Refresh is needed.
            //(MyMap.Layers["USA"] as ArcGISDynamicMapServiceLayer).Refresh();
        }
コード例 #42
0
        protected void WriteClassBreaksRenderer(ClassBreaksRenderer cbRenderer)
        {
            writer.WriteStartElement("ClassBreaksRenderer", Namespaces[Constants.esriPrefix]);
			if (!string.IsNullOrEmpty(cbRenderer.Field))
				writer.WriteAttributeString("Field", cbRenderer.Field);
			if (cbRenderer.DefaultSymbol != null)
            {
                writer.WriteStartElement("ClassBreaksRenderer.DefaultSymbol", Namespaces[Constants.esriPrefix]);
                (new SymbolXamlWriter(writer, Namespaces)).WriteSymbol(cbRenderer.DefaultSymbol);
                writer.WriteEndElement();
            }
            if (cbRenderer.Classes != null && cbRenderer.Classes.Count > 0)
            {
                writer.WriteStartElement("ClassBreaksRenderer.Classes", Namespaces[Constants.esriPrefix]);

                foreach (ESRI.ArcGIS.Client.ClassBreakInfo classBreak in cbRenderer.Classes)
                {
                    WriteClassBreakInfo(classBreak);
                }

                writer.WriteEndElement();// ClassBreaksRenderer.Classes
            }
            writer.WriteEndElement();
        }
コード例 #43
0
 internal static void ensureCustomClassBreakRendererIsSet(GraphicsLayer lyr, Layer layerInfo)
 {
     ClassBreaksRenderer cb = lyr.Renderer as ClassBreaksRenderer;
     if (cb == null) // ensure that the classbreaks renderer is enabled
     {
         if (lyr.Clusterer == null) // no clustering enabled
         {
             cb = new ClassBreaksRenderer();
             cb.DefaultSymbol = new PictureMarkerSymbol()
             {
                 // TODO:- nik (Refactor)
                 // ThematicMapWrapper.createImageFillSymbol(layerInfo.DefaultSymbol as PictureMarkerSymbol);
             };
             // TODO:- nik (Refactor)
             //if (layerInfo.ClassBreaks != null)
             //{
             //    cb.Attribute = layerInfo.ClassBreaks.Attribute;
             //    if (layerInfo.ClassBreaks.Items != null)
             //    {
             //        foreach (ClassBreakInfo cbInfo in layerInfo.ClassBreaks.Items)
             //        {
             //            cb.Classes.Add(
             //                new ESRI.ArcGIS.Client.ClassBreakInfo
             //                {
             //                    MaximumValue = cbInfo.IsMax ? cbInfo.MaxValue + 1 : cbInfo.MaxValue,
             //                    MinimumValue = cbInfo.MinValue,
             //                    Symbol = ThematicMapWrapper.createImageFillSymbol(cbInfo.Symbol as PictureMarkerSymbol)
             //                }
             //                );
             //        }
             //    }
             //}
         }
         else // clustering enabled
         {
         }
     }
     lyr.Renderer = cb;
 }
        // Shows counties by population density when the Class Breaks button is clicked
        private void ClassBreaksButton_Click(object sender, RoutedEventArgs e)
        {
            ClassBreaksRenderer cbr = new ClassBreaksRenderer();

            // Symbolize based on the population density field
            cbr.Field = "POP00_SQMI";
            var Infos = new ClassBreakInfoCollection();
            SimpleLineSymbol outline = new SimpleLineSymbol() { Color = Colors.LightGray };

            #region Define Class Breaks

            // Create five class breaks, with symbols ranging from green for the lowest density to
            // blue for the highest
            cbr.Infos.Add(new ClassBreakInfo()
            {

                Minimum = 0,
                Maximum = 12,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 0),
                    Outline = outline
                }
            });

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 31.3,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 100, 255, 100),
                    Outline = outline
                }
            });

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 59.7,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 200),
                    Outline = outline
                }
            });

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 146.2,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 255, 255),
                    Outline = outline
                }
            });

            cbr.Infos.Add(new ClassBreakInfo()
            {
                Maximum = 57173,
                Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromArgb(255, 0, 0, 255),
                    Outline = outline
                }
            });

            #endregion

            // Get the USA layer from the map and apply the class breaks renderer to the counties layer
            var layer = map1.Layers["USA"] as ArcGISDynamicMapServiceLayer;
            if (layer.LayerDrawingOptions == null)
                layer.LayerDrawingOptions = new LayerDrawingOptionCollection();
            layer.LayerDrawingOptions.Add(new LayerDrawingOptions()
            {
                LayerID = 3, // counties layer has an ID of 3
                Renderer = cbr
            });

            // Make it so only the counties layer is visible
            layer.VisibleLayers = new ObservableCollection<int>(new int[] { 3 });
        }