Ejemplo n.º 1
0
        private void CategorizeCitiesByAlgorithm(IMapPointLayer alayer)
        {
            /*
             * There are a large number of settings that can be controlled directly using the PointScheme.
             * In this illustration the classification type is quantities, but this can also be
             * UniqueValues or custom.
             * The categories can always be edited programmatically after they are created, but this
             * simply controls what will happen when the CreateCategories method is ultimately called.
             * The interval snap methods include none, rounding, significant figures, and snapping to the
             * nearest value. These can help the appearance of the categories in the legend,
             * but it can also cause trouble. With Significant figures, the IntervalRoundingDigits controls the
             * number of significant figures instead.
             * One property is deceptive in its power.
             * The TemplateSymbolizer property allows you to control the basic appearance of the categories for
             * any property that is not being controlled by either the size or color ramping.
             * For example, if we wanted to add black borders to the stars above, we would simply add that
             * to the template symbolizer. In this case we chose to make them appear as stars and controlled
             * them to have equal sizes since UseSizeRange defaults to false, but UseColorRange defaults to true.
             */
            PointScheme lScheme = new PointScheme();

            lScheme.Categories.Clear();
            lScheme.EditorSettings.ClassificationType     = ClassificationType.Quantities;
            lScheme.EditorSettings.IntervalMethod         = IntervalMethod.EqualInterval;
            lScheme.EditorSettings.IntervalSnapMethod     = IntervalSnapMethod.Rounding;
            lScheme.EditorSettings.IntervalRoundingDigits = 5;
            lScheme.EditorSettings.TemplateSymbolizer     = new PointSymbolizer(Color.Yellow, DotSpatial.Symbology.PointShape.Star, 16);
            lScheme.EditorSettings.FieldName = "Area";
            lScheme.CreateCategories(alayer.DataSet.DataTable);
            alayer.Symbology = lScheme;
        }
        public void GivenLayerWithConvertedProperties_WhenConvertingLayerFeatures_ThenOnlyDefaultCategoryAdded()
        {
            // Given
            var mocks           = new MockRepository();
            var defaultCategory = mocks.Stub <IPointCategory>();
            var categoryOne     = mocks.Stub <IPointCategory>();
            var categoryTwo     = mocks.Stub <IPointCategory>();

            mocks.ReplayAll();

            const string metadataAttributeName = "Meta";
            var          theme = new MapTheme <TestCategoryTheme>(metadataAttributeName, new[]
            {
                new TestCategoryTheme(ValueCriterionTestFactory.CreateValueCriterion())
            });
            var mapData = new TestFeatureBasedMapData("test data", theme)
            {
                Features = new[]
                {
                    new MapFeature(Enumerable.Empty <MapGeometry>())
                    {
                        MetaData =
                        {
                            {
                                metadataAttributeName, new object()
                            }
                        }
                    }
                }
            };

            var scheme = new PointScheme();

            scheme.Categories.Clear();
            scheme.Categories.Add(categoryOne);
            scheme.Categories.Add(categoryTwo);

            var mapLayer = new TestFeatureLayer
            {
                Symbology = scheme
            };

            var testConverter = new TestFeatureBasedMapDataConverter
            {
                CreatedDefaultCategory = defaultCategory
            };

            // Precondition
            Assert.AreEqual(2, mapLayer.Symbology.Categories.Count);

            // When
            mapData.Features = Enumerable.Empty <MapFeature>();
            testConverter.ConvertLayerFeatures(mapData, mapLayer);

            // Then
            Assert.AreSame(defaultCategory, mapLayer.Symbology.Categories.Single());
        }
        public void ConvertLayerProperties_MapDataWithMapThemeAndVaryingValueCriteria_SetsCorrectFilterExpression(ValueCriterionOperator criterionOperator,
                                                                                                                  string expressionFormat)
        {
            // Setup
            const string metadataAttributeName = "Meta";
            const string value = "test value";

            var valueCriterion = new ValueCriterion(criterionOperator,
                                                    value);
            var theme = new MapTheme <TestCategoryTheme>(metadataAttributeName, new[]
            {
                new TestCategoryTheme(valueCriterion)
            });

            var mapData = new TestFeatureBasedMapData("test data", theme)
            {
                Features = new[]
                {
                    new MapFeature(Enumerable.Empty <MapGeometry>())
                    {
                        MetaData =
                        {
                            {
                                metadataAttributeName, new object()
                            }
                        }
                    }
                }
            };

            var featureScheme   = new PointScheme();
            var defaultCategory = new PointCategory();
            var category        = new PointCategory();
            var testConverter   = new TestFeatureBasedMapDataConverter
            {
                CreatedFeatureScheme         = featureScheme,
                CreatedDefaultCategory       = defaultCategory,
                CreatedCategoryThemeCategory = category
            };

            var mapLayer = new TestFeatureLayer();

            // Call
            testConverter.ConvertLayerProperties(mapData, mapLayer);

            // Assert
            Assert.IsNull(defaultCategory.FilterExpression);
            string expectedFilterExpression = string.Format(expressionFormat, value);

            Assert.AreEqual(expectedFilterExpression, category.FilterExpression);
        }
        public void ConvertLayerProperties_MapDataWithMapThemeAndExistingMetaData_SetsExpectedSymbology()
        {
            // Setup
            const string metadataAttributeName = "metaData";
            var          theme = new MapTheme <TestCategoryTheme>(metadataAttributeName, new[]
            {
                new TestCategoryTheme(ValueCriterionTestFactory.CreateValueCriterion())
            });
            var mapData = new TestFeatureBasedMapData("test data", theme)
            {
                Features = new[]
                {
                    new MapFeature(Enumerable.Empty <MapGeometry>())
                    {
                        MetaData =
                        {
                            {
                                metadataAttributeName, new object()
                            }
                        }
                    }
                }
            };

            var scheme          = new PointScheme();
            var defaultCategory = new PointCategory();
            var categoryTheme   = new PointCategory();
            var testConverter   = new TestFeatureBasedMapDataConverter
            {
                CreatedFeatureScheme         = scheme,
                CreatedDefaultCategory       = defaultCategory,
                CreatedCategoryThemeCategory = categoryTheme
            };

            var mapLayer = new TestFeatureLayer();

            // Call
            testConverter.ConvertLayerProperties(mapData, mapLayer);

            // Assert
            IPointScheme symbology = mapLayer.Symbology;

            Assert.AreSame(scheme, symbology);
            CollectionAssert.AreEqual(new[]
            {
                defaultCategory,
                categoryTheme
            }, symbology.Categories);
        }
Ejemplo n.º 5
0
        private void CategorizeCities(IMapPointLayer alayer)
        {
            PointScheme lScheme = new PointScheme();

            lScheme.Categories.Clear();
            PointCategory smallSize = new PointCategory(Color.Blue, DotSpatial.Symbology.PointShape.Rectangle, 4);

            smallSize.FilterExpression = "[Area] < 1e+08";
            smallSize.LegendText       = "Small Cities";
            lScheme.AddCategory(smallSize);

            PointCategory largeSize = new PointCategory(Color.Yellow, DotSpatial.Symbology.PointShape.Star, 16);

            largeSize.FilterExpression = "[Area] >= 1e+08";
            largeSize.LegendText       = "Large Cities";
            lScheme.AddCategory(largeSize);

            alayer.Symbology = lScheme;
        }
Ejemplo n.º 6
0
        override protected void setSymbolizer()
        {
            int baseWidth = 48;

            PointScheme ftrScheme = new PointScheme();

            PointCategory catDef = new PointCategory(Properties.Resources.feature, baseWidth);

            catDef.LegendText = "No Info";
            catDef.SelectionSymbolizer.ScaleMode = ScaleMode.Geographic;
            catDef.SelectionSymbolizer.SetOutline(Color.Cyan, baseWidth / 4);
            catDef.Symbolizer.ScaleMode = ScaleMode.Geographic;
            ftrScheme.AddCategory(catDef);

            Image[] images =
            {
                Properties.Resources.feature,
                Properties.Resources.important,
                Properties.Resources.question,
                Properties.Resources.problem,
                Properties.Resources.ramp,
                Properties.Resources.sidewalk,
                Properties.Resources.feature,
                Properties.Resources.problem,
                Properties.Resources.pooling,
                Properties.Resources.crash
            };
            string[] iconNames = { "feature", "important", "question", "problem", "ramp", "sidewalk", "other", "road", "drainage", "accident" };

            for (int i = 0; i < images.Length; i++)
            {
                PointCategory cat = new PointCategory(images[i], baseWidth);
                cat.FilterExpression = "[TAMSICON] = '" + iconNames[i] + "'";
                cat.SelectionSymbolizer.ScaleMode = ScaleMode.Geographic;
                cat.SelectionSymbolizer.SetOutline(Color.Cyan, baseWidth / 4);
                cat.Symbolizer.ScaleMode = ScaleMode.Geographic;
                ftrScheme.AddCategory(cat);
            }

            ((MapPointLayer)Layer).Symbology = ftrScheme;
            ((MapPointLayer)Layer).ApplyScheme(ftrScheme);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a new raster with the specified cell size.  If the cell size
        /// is zero, this will default to the shorter of the width or height
        /// divided by 256.  If the cell size produces a raster that is greater
        /// than 8, 000 pixels in either dimension, it will be re-sized to
        /// create an 8, 000 length or width raster.
        /// </summary>
        /// <param name="fs">The featureset to convert to a raster.</param>
        /// <param name="extent">Force the raster to this specified extent.</param>
        /// <param name="cellSize">The double extent of the cell.</param>
        /// <param name="fieldName">The integer field index of the file.</param>
        /// <param name="outputFileName">The fileName of the raster to create.</param>
        /// <param name="driverCode">The optional GDAL driver code to use if using GDAL
        /// for a format that is not discernable from the file extension.  An empty string
        ///  is usually perfectly acceptable here.</param>
        /// <param name="options">For GDAL rasters, they can be created with optional parameters
        ///  passed in as a string array.  In most cases an empty string is perfectly acceptable.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>Generates a raster from the vectors.</returns>
        public static IRaster ToRaster(IFeatureSet fs, Extent extent, double cellSize, string fieldName,
                                       string outputFileName,
                                       string driverCode, string[] options, IProgressHandler progressHandler)
        {
            Extent env = extent;

            if (cellSize == 0)
            {
                if (env.Width < env.Height)
                {
                    cellSize = env.Width / 256;
                }
                else
                {
                    cellSize = env.Height / 256;
                }
            }
            int w = (int)Math.Ceiling(env.Width / cellSize);

            if (w > 8000)
            {
                w        = 8000;
                cellSize = env.Width / 8000;
            }
            int h = (int)Math.Ceiling(env.Height / cellSize);

            if (h > 8000)
            {
                h = 8000;
            }
            Bitmap   bmp = new Bitmap(w, h);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Transparent);
            g.SmoothingMode     = SmoothingMode.None;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            Hashtable colorTable;
            MapArgs   args = new MapArgs(new Rectangle(0, 0, w, h), env, g);

            switch (fs.FeatureType)
            {
            case FeatureType.Polygon:
            {
                MapPolygonLayer mpl = new MapPolygonLayer(fs);
                PolygonScheme   ps  = new PolygonScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;

            case FeatureType.Line:
            {
                MapLineLayer mpl = new MapLineLayer(fs);
                LineScheme   ps  = new LineScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;

            default:
            {
                MapPointLayer mpl = new MapPointLayer(fs);
                PointScheme   ps  = new PointScheme();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    });
            }
            break;
            }
            Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType;

            // We will try to convert to double if it is a string
            if (tp == typeof(string))
            {
                tp = typeof(double);
            }
            InRamImageData image = new InRamImageData(bmp, env);
            ProgressMeter  pm    = new ProgressMeter(progressHandler, "Converting To Raster Cells", h);

            IRaster output;

            output        = Raster.Create(outputFileName, driverCode, w, h, 1, tp, options);
            output.Bounds = new RasterBounds(h, w, env);

            double noDataValue = output.NoDataValue;

            if (fieldName != "FID")
            {
                // We can't use this method to calculate Max on a non-existent FID field.
                double dtMax = Convert.ToDouble(fs.DataTable.Compute("Max(" + fieldName + ")", ""));
                double dtMin = Convert.ToDouble(fs.DataTable.Compute("Min(" + fieldName + ")", ""));

                if (dtMin <= noDataValue && dtMax >= noDataValue)
                {
                    if (dtMax != GetFieldValue(tp, "MaxValue"))
                    {
                        output.NoDataValue = noDataValue;
                    }
                    else if (dtMin != GetFieldValue(tp, "MinValue"))
                    {
                        output.NoDataValue = noDataValue;
                    }
                }
            }

            List <RcIndex> locations   = new List <RcIndex>();
            List <string>  failureList = new List <string>();

            for (int row = 0; row < h; row++)
            {
                for (int col = 0; col < w; col++)
                {
                    Color c = image.GetColor(row, col);
                    if (c.A == 0)
                    {
                        output.Value[row, col] = output.NoDataValue;
                    }
                    else
                    {
                        if (colorTable.ContainsKey(c) == false)
                        {
                            if (c.A < 125)
                            {
                                output.Value[row, col] = output.NoDataValue;
                                continue;
                            }

                            // Use a color matching distance to pick the closest member
                            object val = GetCellValue(w, h, row, col, image, c, colorTable, locations);

                            output.Value[row, col] = GetDouble(val, failureList);
                        }
                        else
                        {
                            output.Value[row, col] = GetDouble(colorTable[c], failureList);
                        }
                    }
                }
                pm.CurrentValue = row;
            }
            const int maxIterations = 5;
            int       iteration     = 0;

            while (locations.Count > 0)
            {
                List <RcIndex> newLocations = new List <RcIndex>();
                foreach (RcIndex location in locations)
                {
                    object val = GetCellValue(w, h, location.Row, location.Column, image,
                                              image.GetColor(location.Row, location.Column), colorTable, newLocations);
                    output.Value[location.Row, location.Column] = GetDouble(val, failureList);
                }
                locations = newLocations;
                iteration++;
                if (iteration > maxIterations)
                {
                    break;
                }
            }

            pm.Reset();
            return(output);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Translates the given style as point style and adds it to the given point scheme.
        /// </summary>
        /// <param name="scheme">The scheme the style gets added to.</param>
        /// <param name="labelScheme">The scheme the label definitions gets added to.</param>
        /// <param name="style">The style that gets translated.</param>
        private static void TranslatePointStyle(PointScheme scheme, ILabelScheme labelScheme, string style)
        {
            if (string.IsNullOrWhiteSpace(style))
            {
                return;
            }

            var myStyle = style;
            int index   = myStyle.IndexOf("(", StringComparison.Ordinal);

            if (index < 1)
            {
                return;
            }

            var toolname = myStyle.Substring(0, index);

            myStyle = myStyle.Substring(index + 1);

            switch (toolname)
            {
            case "PEN":
            {
                var color = GetColor(ref myStyle, Parameters.Color);
                var width = GetWidth(ref myStyle);

                var cat = new PointCategory(color, Symbology.PointShape.Rectangle, width)
                {
                    FilterExpression = $"[style] = '{style}'",
                    LegendText       = style,
                    Symbolizer       =
                    {
                        ScaleMode = ScaleMode.Simple,
                        Smoothing = false
                    }
                };
                scheme.AddCategory(cat);
                break;
            }

            case "LABEL":
            {
                var fontSize    = GetFontSize(ref myStyle);
                var fontColor   = GetColor(ref myStyle, Parameters.Color);
                var boxColor    = GetColor(ref myStyle, Parameters.BoxColor);
                var haloColor   = GetColor(ref myStyle, Parameters.HaloColor);
                var shadowColor = GetColor(ref myStyle, Parameters.ShadowColor);
                var angle       = GetAngle(ref myStyle);
                var font        = GetFontName(ref myStyle);
                var orientation = GetOrientation(ref myStyle);

                // create a transparent point category because the point is only used to position the label
                var cat = new PointCategory(Color.Transparent, Symbology.PointShape.Rectangle, 1)
                {
                    FilterExpression = $"[style] = '{style}'",
                    LegendText       = style,
                    Symbolizer       =
                    {
                        ScaleMode = ScaleMode.Simple,
                        Smoothing = false
                    }
                };
                scheme.AddCategory(cat);

                // create the label category only if the text column exists, otherwise we don't know where to take the text from
                if (hasTextField)
                {
                    var lcat = new LabelCategory
                    {
                        Name             = style,
                        Expression       = "[Text]",
                        FilterExpression = $"[style] = '{style}'",
                        Symbolizer       =
                        {
                            ScaleMode   = ScaleMode.Simple,
                            Alignment   = StringAlignment.Center,
                            FontColor   = fontColor,
                            FontSize    = (float)fontSize,
                            Orientation = orientation
                        }
                    };

                    if (!string.IsNullOrWhiteSpace(font))
                    {
                        lcat.Symbolizer.FontFamily = font;
                    }

                    if (angle != 0)
                    {
                        lcat.Symbolizer.Angle    = angle;
                        lcat.Symbolizer.UseAngle = true;
                    }

                    if (haloColor != Color.Empty)
                    {
                        lcat.Symbolizer.HaloColor   = haloColor;
                        lcat.Symbolizer.HaloEnabled = true;
                    }

                    if (boxColor != Color.Empty)
                    {
                        lcat.Symbolizer.BackColor        = boxColor;
                        lcat.Symbolizer.BackColorEnabled = true;
                    }

                    if (shadowColor != Color.Empty)
                    {
                        lcat.Symbolizer.DropShadowColor   = shadowColor;
                        lcat.Symbolizer.DropShadowEnabled = true;
                    }

                    labelScheme.Categories.Add(lcat);
                }

                break;
            }

            default: throw new NotImplementedException($"The translation of the point tool {toolname} is not yet implemented.");
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Translates the style strings from the list to DotSpatial style categories and adds them to the given layer.
        /// </summary>
        /// <param name="layer">The layer the styles get added to.</param>
        /// <param name="styles">The style strings that should get translated.</param>
        public static void TranslateStyles(IMapFeatureLayer layer, IList <string> styles)
        {
            var featureType = layer.DataSet.FeatureType;

            switch (featureType)
            {
            case FeatureType.MultiPoint:
            case FeatureType.Point:
            {
                // create the scheme
                var scheme = new PointScheme();
                scheme.Categories.Clear();
                scheme.EditorSettings.ClassificationType = ClassificationType.UniqueValues;
                scheme.EditorSettings.FieldName          = "style";
                scheme.LegendText = "Point";

                // add the default category
                var cat = new PointCategory(Color.Black, Symbology.PointShape.Rectangle, 5)
                {
                    LegendText = "default",
                    Symbolizer =
                    {
                        ScaleMode = ScaleMode.Simple,
                        Smoothing = false
                    }
                };
                scheme.AddCategory(cat);

                var labelLayer = new MapLabelLayer();
                labelLayer.Symbology.Categories.Clear();

                bool needsLabels = styles.Any(_ => !string.IsNullOrWhiteSpace(_) && _.StartsWith("LABEL"));

                foreach (var style in styles)
                {
                    TranslatePointStyle(scheme, labelLayer.Symbology, style);
                }

                // assign the scheme
                layer.Symbology = scheme;

                // assign the label layer if needed
                if (needsLabels)
                {
                    layer.LabelLayer = labelLayer;
                    layer.ShowLabels = true;
                    layer.LabelLayer.CreateLabels();
                }

                layer.DataSet.UpdateExtent();
                layer.DataSet.InitializeVertices();
                layer.AssignFastDrawnStates();

                break;
            }

            case FeatureType.Line:
            {
                // create the scheme
                var scheme = new LineScheme();
                scheme.Categories.Clear();
                scheme.EditorSettings.ClassificationType = ClassificationType.UniqueValues;
                scheme.EditorSettings.FieldName          = "style";
                scheme.LegendText = "Line";

                // add the default category
                var cat = new LineCategory(Color.Black, 1)
                {
                    LegendText = "default",
                    Symbolizer =
                    {
                        ScaleMode = ScaleMode.Simple,
                        Smoothing = false
                    }
                };
                scheme.AddCategory(cat);

                // add the categories from the file
                foreach (var style in styles)
                {
                    TranslateLineStyle(scheme, style);
                }

                // assign the scheme
                layer.Symbology = scheme;

                layer.DataSet.UpdateExtent();
                layer.DataSet.InitializeVertices();
                layer.AssignFastDrawnStates();

                break;
            }

            case FeatureType.Polygon:
            {
                // create the scheme
                var scheme = new PolygonScheme();
                scheme.Categories.Clear();
                scheme.EditorSettings.ClassificationType = ClassificationType.UniqueValues;
                scheme.EditorSettings.FieldName          = "style";
                scheme.LegendText = "Polygon";

                // add the default category
                var cat = new PolygonCategory(Color.GhostWhite, Color.Black, 1)
                {
                    LegendText = "default",
                    Symbolizer =
                    {
                        ScaleMode = ScaleMode.Simple,
                        Smoothing = false
                    }
                };
                scheme.AddCategory(cat);

                // add the categories from the file
                foreach (var style in styles)
                {
                    TranslatePolygonStyle(scheme, style);
                }

                // assign the scheme
                layer.Symbology = scheme;

                layer.DataSet.UpdateExtent();
                layer.DataSet.InitializeVertices();
                layer.AssignFastDrawnStates();

                break;
            }

            default: throw new ArgumentOutOfRangeException(nameof(featureType), featureType, null);
            }
        }
        private void UpdateSymbology(IFeatureLayer mapLayer, string columnName)
        {
            var scheme = new PointScheme();

            scheme.ClearCategories();

            var settings = scheme.EditorSettings;

            settings.ClassificationType = ClassificationType.Custom;

            var colors = new[]
            {
                Color.Aqua, Color.Blue, Color.Brown, Color.Cyan, Color.Fuchsia, Color.LightSalmon,
                Color.Olive, Color.Wheat, Color.DodgerBlue
            };

            // Find min/max value in valueField
            var minValue = double.MaxValue;
            var maxValue = double.MinValue;

            foreach (DataRow row in mapLayer.DataSet.DataTable.Rows)
            {
                double value;
                try
                {
                    value = Convert.ToDouble(row[columnName]);
                }
                catch
                {
                    value = 0;
                }
                if (value < minValue)
                {
                    minValue = value;
                }
                if (value > maxValue)
                {
                    maxValue = value;
                }
            }
            const double EPSILON = 0.00001;

            if (Math.Abs(minValue - double.MaxValue) < EPSILON)
            {
                minValue = 0.0;
            }
            if (Math.Abs(maxValue - double.MinValue) < EPSILON)
            {
                maxValue = 0.0;
            }

            var fracLength = maxValue - minValue > 10? 0 : 1;

            // Set number of categories
            const int categoriesCount = 3;
            var       categorieStep   = (maxValue - minValue) / categoriesCount; // value step in filter

            const int imageStep = 5;
            var       imageSize = 10; // start image size

            var imageColor = colors[new Random().Next(0, colors.Length - 1)];

            for (int i = 0; i < categoriesCount; i++)
            {
                var min = minValue + categorieStep * i;
                var max = min + categorieStep;
                if (max >= maxValue)
                {
                    max = maxValue + 1;
                }

                min = Math.Round(min, fracLength);
                max = Math.Round(max, fracLength);

                // Fix possible round problems on interval borders
                if (i == 0 && min > minValue)
                {
                    min--;
                }
                if (i == categoriesCount - 1 && max < maxValue)
                {
                    max++;
                }

                imageSize += imageStep;
                var baseFilter = string.Format("[{0}] >= {1} and [{0}] < {2}", columnName,
                                               fracLength == 0 ? (int)min : min,
                                               fracLength == 0 ? (int)max : max);
                var legendText = string.Format("[{0}, {1})",
                                               fracLength == 0 ? (int)min : min,
                                               fracLength == 0 ? (int)max : max);
                var mySymbolizer = new PointSymbolizer(imageColor, PointShape.Ellipse, imageSize);
                var myCategory   = new PointCategory(mySymbolizer)
                {
                    FilterExpression = baseFilter.Replace(",", "."),
                    LegendText       = legendText,
                };
                scheme.AddCategory(myCategory);
            }

            mapLayer.Symbology = scheme;
        }
Ejemplo n.º 11
0
        private static IPointScheme CreateSymbology(string servCode, IFeatureSet featureSet)
        {
            Debug.Assert(featureSet != null);

            var scheme = new PointScheme();

            scheme.ClearCategories();

            var settings = scheme.EditorSettings;

            settings.ClassificationType = ClassificationType.Custom;

            const string valueField = "ValueCount";
            // Find min/max value in valueField
            var minValue = int.MaxValue;
            var maxValue = int.MinValue;

            foreach (DataRow row in featureSet.DataTable.Rows)
            {
                int value;
                try
                {
                    value = Convert.ToInt32(row[valueField]);
                }
                catch
                {
                    value = 0;
                }
                if (value < minValue)
                {
                    minValue = value;
                }
                if (value > maxValue)
                {
                    maxValue = value;
                }
            }
            if (minValue == int.MaxValue)
            {
                minValue = 0;
            }
            if (maxValue == int.MinValue)
            {
                maxValue = 0;
            }

            // Calculate number of categories
            int categoriesCount;
            var length = maxValue - minValue;

            if (length < 50)
            {
                categoriesCount = 1;
            }
            else if (length < 100)
            {
                categoriesCount = 2;
            }
            else
            {
                categoriesCount = 3;
            }

            var       categorieStep = (maxValue - minValue) / categoriesCount + 1; // value step in filter
            const int imageStep     = 5;
            var       imageSize     = 5;

            var imageHelper = new WebServices.ServiceIconHelper(Settings.Instance.SelectedHISCentralURL); // we need it only to get image
            var image       = imageHelper.GetImageForService(servCode);

            const string seriesID = "SeriesID";
            var          needDownloadedCategories = featureSet.DataTable.Columns.Contains(seriesID);

            for (int i = 0; i < categoriesCount; i++)
            {
                var min = minValue - 1;
                var max = minValue + categorieStep;
                if (max > maxValue)
                {
                    max = maxValue;
                }
                minValue = max + 1;

                imageSize += imageStep;

                var baseFilter = string.Format("[{0}] > {1} and [{0}] <= {2}", valueField, min, max);

                var filterEx = needDownloadedCategories
                                   ? baseFilter + string.Format(" AND ([{0}] is null)", seriesID)
                                   : baseFilter;

                var legendText   = string.Format("({0}, {1}]", min, max);
                var mySymbolizer = new PointSymbolizer(image, imageSize);
                var myCategory   = new PointCategory(mySymbolizer)
                {
                    FilterExpression    = filterEx,
                    LegendText          = legendText,
                    SelectionSymbolizer = new PointSymbolizer(image, imageSize + 2)
                };
                myCategory.SelectionSymbolizer.SetFillColor(Color.Yellow);
                scheme.AddCategory(myCategory);

                // add category for downloaded
                if (needDownloadedCategories)
                {
                    mySymbolizer = new PointSymbolizer(image, imageSize);
                    mySymbolizer.SetOutline(Color.Green, 3);

                    filterEx   = string.Format("{0} AND not([{1}] is null)", baseFilter, seriesID);
                    legendText = myCategory.LegendText + " (downloaded)";
                    var categorieForDownload = new PointCategory(mySymbolizer)
                    {
                        FilterExpression    = filterEx,
                        LegendText          = legendText,
                        SelectionSymbolizer = new PointSymbolizer(image, imageSize + 2)
                    };
                    categorieForDownload.SelectionSymbolizer.SetFillColor(Color.Yellow);
                    scheme.AddCategory(categorieForDownload);
                }
            }

            return(scheme);
        }