private void menu_Click(object sender, EventArgs e) { FormContour Frm = new FormContour(); Frm.layers = App.Map.GetRasterLayers(); if (Frm.layers.GetLength(0) <= 0) { MessageBox.Show("No raster layer found!"); return; } if (Frm.ShowDialog() == DialogResult.OK) { IMapFeatureLayer fl = App.Map.Layers.Add(Frm.Contours); fl.LegendText = Frm.LayerName + " - Contours"; int numlevs = Frm.lev.GetLength(0); switch (Frm.contourtype) { case (Contour.ContourType.Line): { LineScheme ls = new LineScheme(); ls.Categories.Clear(); for (int i = 0; i < Frm.color.GetLength(0); i++) { LineCategory lc = new LineCategory(Frm.color[i], 2.0); lc.FilterExpression = "[Value] = " + Frm.lev[i].ToString(); lc.LegendText = Frm.lev[i].ToString(); ls.AddCategory(lc); } fl.Symbology = ls; } break; case (Contour.ContourType.Polygon): { PolygonScheme ps = new PolygonScheme(); ps.Categories.Clear(); for (int i = 0; i < Frm.color.GetLength(0); i++) { PolygonCategory pc = new PolygonCategory(Frm.color[i], Color.Transparent, 0); pc.FilterExpression = "[Lev] = " + i.ToString(); pc.LegendText = Frm.lev[i].ToString() + " - " + Frm.lev[i + 1].ToString(); ps.AddCategory(pc); } fl.Symbology = ps; } break; } } }
/// <summary> /// Gets the FeatureLayer that is used for the selection tests. /// </summary> /// <param name="cat">Reference to the second category.</param> /// <returns>The FeatureLayer.</returns> private static IFeatureLayer GetFeatureLayer(out PolygonCategory cat) { // load layer with us states ShapefileLayerProvider provider = new ShapefileLayerProvider(); var fl = (IFeatureLayer)provider.OpenLayer(Path.Combine(@"TestFiles", "50mil_us_states.shp"), false, null, null); Assert.IsNotNull(fl); // add two categories for testing category.SelectionEnabled PolygonScheme scheme = new PolygonScheme(); scheme.ClearCategories(); scheme.AddCategory(new PolygonCategory(Color.LightBlue, Color.DarkBlue, 1) { FilterExpression = "[FIPS] >= 10", LegendText = ">= 10" }); cat = new PolygonCategory(Color.Pink, Color.DarkRed, 1) { FilterExpression = "[FIPS] < 10", LegendText = "< 10" }; scheme.AddCategory(cat); fl.Symbology = scheme; Assert.IsTrue(cat.SelectionEnabled, "Categories must be initialized with SelectionEnabled = true."); return(fl); }
private void btnFilterByPopState_Click(object sender, EventArgs e) { //check the number of layers from map control if (map1.Layers.Count > 0) { //Delacre a MapPolygonLayer MapPolygonLayer stateLayer = default(MapPolygonLayer); //Type cast the FirstLayer of MapControl to MapPolygonLayer stateLayer = (MapPolygonLayer)map1.Layers[0]; //Check the MapPolygonLayer ( Make sure that it has a polygon layer) if (stateLayer == null) { MessageBox.Show("The layer is not a polygon layer."); } else { //!!!-------------------- this line is necessary otherwise the code doesn't work------------------------!!!!!!!!!!!!!!!!!!!! } stateLayer.DataSet.FillAttributes(); //Create a new PolygonScheme PolygonScheme scheme = new PolygonScheme(); //Create a new PolygonCategory PolygonCategory category = new PolygonCategory(Color.Yellow, Color.Red, 1); //Declare a filter string //[POP1990],[STATE_NAME] are attributes from the attribute table of the given shape file. string filter = "[POP1990] > 10000000 OR [STATE_NAME] = 'Idaho'"; //Set/Assign the filter expression to PolygonCategory category.FilterExpression = filter; //Set the Legend Text category.LegendText = "population > 10 Million"; //Add the PolygonCategory in to the PolygonScheme scheme.AddCategory(category); //Set the scheme in to the MapPolygonLayer's symbology stateLayer.Symbology = scheme; } else { MessageBox.Show("Please add a layer to the map."); } }
//------------------------------------------------------- public void AddProviderShapeFileLayers() { ProviderMap.Layers.Clear(); AddProviderBaseShapeFile(); MapPolygonLayer MPL = AddFieldLayer("PRVDCODE"); PolygonScheme BaseScheme = new PolygonScheme(); BaseScheme.EditorSettings.ClassificationType = ClassificationType.UniqueValues; ////Set the UniqueValue field name BaseScheme.EditorSettings.FieldName = "PRVDCODE"; // Create Catagories based on data BaseScheme.CreateCategories(MPL.DataSet.DataTable); MPL.Symbology = BaseScheme; }
/// <summary> /// Translates the given style as polygon style and adds it to the given polygon scheme. /// </summary> /// <param name="scheme">The scheme the style gets added to.</param> /// <param name="style">The style that gets translated.</param> private static void TranslatePolygonStyle(PolygonScheme scheme, string style) { if (string.IsNullOrWhiteSpace(style)) { return; } var tools = GetToolNames(style); Color col = Color.Black; Color fillCol = Color.White; double numWidth = 1; foreach (var tool in tools) { switch (tool.Key) { case "PEN": { var myStyle = tool.Value.Substring(4); col = GetColor(ref myStyle, Parameters.Color); numWidth = GetWidth(ref myStyle); break; } case "BRUSH": { var myStyle = tool.Value.Substring(6); fillCol = GetColor(ref myStyle, Parameters.BrushForeColor); break; } } } var cat = new PolygonCategory(fillCol, col, numWidth) { FilterExpression = $"[style] = '{style}'", LegendText = style, Symbolizer = { ScaleMode = ScaleMode.Simple, Smoothing = false } }; scheme.AddCategory(cat); }
//-------------------------------------------------------------- internal void AddProviderBaseShapeFile() { try { ProviderMap.AddLayer(DataPath + ShapeFilename); //Assign the mappolygon layer from the map MapPolygonLayer BaseLayer = default(MapPolygonLayer); BaseLayer = (MapPolygonLayer)ProviderMap.Layers[0]; if (BaseLayer == null) { MessageBox.Show("The Base Layer of Provider Map is not a polygon layer."); } else { //Get the shapefile's attribute table to our datatable dt DataTable DT = BaseLayer.DataSet.DataTable; // Create a Scheme PolygonScheme BaseScheme = new PolygonScheme(); //Set the ClassificationType for the PolygonScheme via EditorSettings BaseScheme.EditorSettings.ClassificationType = ClassificationType.UniqueValues; //Set the UniqueValue field name BaseScheme.EditorSettings.FieldName = "ADWR_NAME"; // Create Catagories based on data BaseScheme.CreateCategories(DT); // Set the Symbology to this Scheme BaseLayer.Symbology = BaseScheme; } } catch (Exception e) { MessageBox.Show("Error Loading Shape File:[ " + DataPath + ShapeFilename + "] :" + e.Message); } }
private void ColorMap() { try { FeatureLayer fl = mainMap.Layers[0] as FeatureLayer; PolygonCategoryCollection pcc = new PolygonCategoryCollection(); PolygonScheme myScheme = new PolygonScheme(); myScheme.Categories = new PolygonCategoryCollection(); string strrow = ""; int iRegionColor = 0; foreach (BenMAPRollback brb in _monitorRollbackLine.BenMAPRollbacks) { if (brb.SelectRegions.Count != 0) { iRegionColor += brb.SelectRegions.Count; } } foreach (BenMAPRollback brb in _monitorRollbackLine.BenMAPRollbacks) { if (brb.SelectRegions.Count != 0) { foreach (RowCol rc in brb.SelectRegions) { if (iRegionColor != dicMyColorIndex.Count) { if (strrow == "") { strrow = dicMyColorIndex[rc.Col + "," + rc.Row].ToString(); } else { strrow += "," + dicMyColorIndex[rc.Col + "," + rc.Row].ToString(); } } PolygonCategory pcin = new PolygonCategory(); pcin.FilterExpression = string.Format("[{0}]={1} ", "MyColorIndex", dicMyColorIndex[rc.Col + "," + rc.Row].ToString()); pcin.Symbolizer.SetOutline(Color.Black, 1); string[] strColor = brb.DrawingColor.Split(new char[] { ',' }); pcin.Symbolizer.SetFillColor(Color.FromArgb(Convert.ToInt32(strColor[0]), int.Parse(strColor[1]), int.Parse(strColor[2]))); myScheme.Categories.Add(pcin); } } } if (myScheme.Categories.Count > 0) { if (iRegionColor != dicMyColorIndex.Count) { PolygonCategory pcin = new PolygonCategory(); pcin.FilterExpression = string.Format("[{0}] not in({1})", "MyColorIndex", strrow); pcin.Symbolizer.SetFillColor(Color.White); pcin.Symbolizer.SetOutline(Color.Black, 1); myScheme.Categories.Add(pcin); } (fl as IFeatureLayer).Symbology = myScheme; } } catch (Exception ex) { Logger.LogError(ex); } }
private void MonitorRollbackSettings2_Load(object sender, EventArgs e) { try { if (CommonClass.GBenMAPGrid == null) { return; } mainMap.ProjectionModeReproject = ActionMode.Never; mainMap.ProjectionModeDefine = ActionMode.Never; if (_monitorRollbackLine.RollbackGrid is ShapefileGrid) { if (File.Exists(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.MainSetup.SetupName + "\\" + (_monitorRollbackLine.RollbackGrid as ShapefileGrid).ShapefileName + ".shp")) { mainMap.Layers.Add(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.MainSetup.SetupName + "\\" + (_monitorRollbackLine.RollbackGrid as ShapefileGrid).ShapefileName + ".shp"); } } else if (_monitorRollbackLine.RollbackGrid is RegularGrid) { if (File.Exists(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.MainSetup.SetupName + "\\" + (_monitorRollbackLine.RollbackGrid as RegularGrid).ShapefileName + ".shp")) { mainMap.Layers.Add(CommonClass.DataFilePath + @"\Data\Shapefiles\" + CommonClass.MainSetup.SetupName + "\\" + (_monitorRollbackLine.RollbackGrid as RegularGrid).ShapefileName + ".shp"); } } PolygonLayer playerRegion = mainMap.Layers[mainMap.Layers.Count - 1] as PolygonLayer; playerRegion.DataSet.DataTable.Columns.Add("MyColorIndex", typeof(int)); for (int i = 0; i < playerRegion.DataSet.DataTable.Rows.Count; i++) { playerRegion.DataSet.DataTable.Rows[i]["MyColorIndex"] = i; dicMyColorIndex.Add(Convert.ToInt32(playerRegion.DataSet.DataTable.Rows[i]["COL"]).ToString() + "," + Convert.ToInt32(playerRegion.DataSet.DataTable.Rows[i]["ROW"]).ToString(), i); } Color cRegion = Color.Transparent; PolygonSymbolizer TransparentRegion = new PolygonSymbolizer(cRegion); TransparentRegion.OutlineSymbolizer = new LineSymbolizer(Color.Black, 1); playerRegion.Symbolizer = TransparentRegion; lstMonitorValues = DataSourceCommonClass.GetMonitorData(_monitorRollbackLine.GridType, _monitorRollbackLine.Pollutant, _monitorRollbackLine); IFeatureSet fsPoints = new FeatureSet(); MonitorValue mv = null; Feature feature = null; List <DotSpatial.Topology.Coordinate> lstCoordinate = new List <DotSpatial.Topology.Coordinate>(); List <double> fsInter = new List <double>(); if (lstMonitorValues != null && lstMonitorValues.Count > 0) { PolygonScheme myScheme = new PolygonScheme(); PolygonCategory pcin = new PolygonCategory(); pcin.Symbolizer.SetFillColor(Color.Red); myScheme.Categories.Add(pcin); DotSpatial.Topology.Point point; for (int i = 0; i < lstMonitorValues.Count; i++) { mv = lstMonitorValues[i]; point = new DotSpatial.Topology.Point(mv.Longitude, mv.Latitude); feature = new Feature(point); fsPoints.AddFeature(feature); } mainMap.Layers.Add(fsPoints); } } catch (Exception ex) { Logger.LogError(ex); } }
/// <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); }
/// <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 bool DrawMonitorMap() { try { IFeatureSet fsPoints = new FeatureSet(); fsPoints.DataTable.Columns.Add("Name"); fsPoints.DataTable.Columns.Add("Description"); fsPoints.DataTable.Columns.Add("Longitude"); fsPoints.DataTable.Columns.Add("Latitude"); string[] tmps = new string[_lstMonitorPoints[0].dicMetricValues.Count]; _lstMonitorPoints[0].dicMetricValues.Keys.CopyTo(tmps, 0); for (int i = 0; i < tmps.Length; i++) { fsPoints.DataTable.Columns.Add(tmps[i]); } MonitorValue mv = null; Feature feature = null; List <Coordinate> lstCoordinate = new List <Coordinate>(); List <double> fsInter = new List <double>(); mainMap.Layers.Clear(); mainMap.ProjectionModeReproject = ActionMode.Never; mainMap.ProjectionModeDefine = ActionMode.Never; mainMap.Layers.Clear(); if (File.Exists(this._gridShapeFile)) { mainMap.Layers.Add(this._gridShapeFile); } if (this._lstMonitorPoints != null && this.LstMonitorPoints.Count > 0) { PolygonScheme myScheme = new PolygonScheme(); PolygonCategory pcin = new PolygonCategory(); pcin.Symbolizer.SetFillColor(Color.Red); myScheme.Categories.Add(pcin); DotSpatial.Topology.Point point; for (int i = 0; i < LstMonitorPoints.Count; i++) { mv = LstMonitorPoints[i]; point = new DotSpatial.Topology.Point(mv.Longitude, mv.Latitude); feature = new Feature(point); fsPoints.AddFeature(feature); fsPoints.DataTable.Rows[i]["Name"] = mv.MonitorName; fsPoints.DataTable.Rows[i]["Latitude"] = mv.Latitude; fsPoints.DataTable.Rows[i]["Longitude"] = mv.Longitude; for (int col = 0; col < tmps.Length; col++) { fsPoints.DataTable.Rows[i][tmps[col]] = mv.dicMetricValues[tmps[col]]; } } mainMap.Layers.Add(fsPoints); mainMap.Layers[0].LegendText = "Air quality grid"; mainMap.Layers[1].LegendText = "Monitors"; } PolygonLayer player = mainMap.Layers[0] as PolygonLayer; float f = 0.9f; Color c = Color.Transparent; PolygonSymbolizer Transparent = new PolygonSymbolizer(c); Transparent.OutlineSymbolizer = new LineSymbolizer(Color.DarkBlue, 1); player.Symbolizer = Transparent; LayerObject = null; return(true); } catch (Exception ex) { Logger.LogError(ex); return(false); } }
/// <summary> /// This method is only used when opening the default project fails. The base shapefiles /// are loaded from the [Documents]\HydroDesktop\maps folder. /// </summary> public static Boolean LoadBaseMaps(AppManager applicationManager1, Map mainMap) { //set the projection of main map mainMap.Projection = projWorld.WebMercator; string baseMapFolder = Settings.Instance.DefaultBaseMapDirectory; SetMapExtent(mainMap); MapPolygonLayer layStates; MapGroup baseGroup = new MapGroup(mainMap.Layers, mainMap.MapFrame, mainMap.ProgressHandler); baseGroup.LegendText = "Base Map Data"; baseGroup.ParentMapFrame = mainMap.MapFrame; baseGroup.MapFrame = mainMap.MapFrame; baseGroup.IsVisible = true; //load the 'Countries of the world' layer string fileName1 = Path.Combine(baseMapFolder, "world_countries.shp"); if (File.Exists(fileName1)) { IFeatureSet fsCountries = FeatureSet.OpenFile(fileName1); //fsCountries.Reproject(projWorld.WebMercator); MapPolygonLayer layCountries = new MapPolygonLayer(fsCountries); layCountries.LegendText = "Countries"; PolygonScheme schmCountries = new PolygonScheme(); schmCountries.EditorSettings.StartColor = Color.Orange; schmCountries.EditorSettings.EndColor = Color.Silver; schmCountries.EditorSettings.ClassificationType = ClassificationType.UniqueValues; schmCountries.EditorSettings.FieldName = "NAME"; schmCountries.EditorSettings.UseGradient = true; schmCountries.CreateCategories(layCountries.DataSet.DataTable); layCountries.Symbology = schmCountries; layCountries.ProgressReportingEnabled = false; baseGroup.Layers.Add(layCountries); layCountries.MapFrame = mainMap.MapFrame; } //load Canada Provinces layer try { string fileName3 = Path.Combine(baseMapFolder, "canada_provinces.shp"); if (File.Exists(fileName3)) { IFeatureSet fsProvince = FeatureSet.OpenFile(fileName3); //fsProvince.Reproject(projWorld.WebMercator); MapPolygonLayer layProvince = new MapPolygonLayer(fsProvince); PolygonScheme schmProvince = new PolygonScheme(); layProvince.IsVisible = true; layProvince.LegendText = "Canada Provinces"; schmProvince.EditorSettings.StartColor = Color.Green; schmProvince.EditorSettings.EndColor = Color.Yellow; schmProvince.EditorSettings.ClassificationType = ClassificationType.UniqueValues; schmProvince.EditorSettings.FieldName = "NAME"; schmProvince.EditorSettings.UseGradient = true; schmProvince.CreateCategories(layProvince.DataSet.DataTable); layProvince.Symbology = schmProvince; layProvince.ProgressReportingEnabled = false; baseGroup.Layers.Add(layProvince); layProvince.MapFrame = mainMap.MapFrame; } } catch { } //load U.S. states layer string fileName2 = Path.Combine(baseMapFolder, "us_states.shp"); if (File.Exists(fileName2)) { IFeatureSet fsStates = FeatureSet.OpenFile(fileName2); //fsStates.Reproject(projWorld.WebMercator); layStates = new MapPolygonLayer(fsStates); PolygonScheme schmStates = new PolygonScheme(); layStates.IsVisible = true; layStates.LegendText = "U.S. States"; schmStates.EditorSettings.StartColor = Color.LemonChiffon; schmStates.EditorSettings.EndColor = Color.LightPink; schmStates.EditorSettings.ClassificationType = ClassificationType.UniqueValues; schmStates.EditorSettings.FieldName = "NAME"; schmStates.EditorSettings.UseGradient = true; schmStates.CreateCategories(layStates.DataSet.DataTable); layStates.Symbology = schmStates; layStates.ProgressReportingEnabled = false; baseGroup.Layers.Add(layStates); layStates.MapFrame = mainMap.MapFrame; } //load a U.S. counties layer try { string fileName4 = Path.Combine(baseMapFolder, "us_counties.shp"); if (File.Exists(fileName4)) { IFeatureSet fsCounties = FeatureSet.OpenFile(fileName4); //fsCounties.Reproject(projWorld.WebMercator); MapPolygonLayer layCounties = new MapPolygonLayer(fsCounties); layCounties.LegendText = "U.S. Counties"; layCounties.IsVisible = false; layCounties.Symbolizer = new PolygonSymbolizer(Color.FromArgb(120, Color.Beige), Color.LightGray); layCounties.ProgressReportingEnabled = false; baseGroup.Layers.Add(layCounties); layCounties.MapFrame = mainMap.MapFrame; } } catch { } //load a U.S. HUC layer try { string fileName5 = Path.Combine(baseMapFolder, "us_huc.shp"); if (File.Exists(fileName5)) { IFeatureSet fsHUC = FeatureSet.OpenFile(fileName5); //fsHUC.Reproject(projWorld.WebMercator); MapPolygonLayer layHUC = new MapPolygonLayer(fsHUC); layHUC.LegendText = "U.S. HUC"; layHUC.IsVisible = false; layHUC.Symbolizer = new PolygonSymbolizer(Color.FromArgb(100, Color.PaleGreen), Color.Gray); layHUC.ProgressReportingEnabled = false; baseGroup.Layers.Add(layHUC); layHUC.MapFrame = mainMap.MapFrame; } } catch { } ////load a rivers layer //try //{ // string fileName6 = Path.Combine(baseMapFolder, "world_rivers.shp"); // if (File.Exists(fileName6)) // { // IFeatureSet fsRivers = FeatureSet.OpenFile(fileName6); // //fsRivers.Reproject(projWorld.WebMercator); // MapLineLayer layRivers = new MapLineLayer(fsRivers); // layRivers.LegendText = "rivers"; // LineSymbolizer symRivers = new LineSymbolizer(Color.Blue, 1.0); // layRivers.Symbolizer = symRivers; // baseGroup.Layers.Add(layRivers); // layRivers.MapFrame = mainMap.MapFrame; // } //} //catch { } ////load a lakes layer //try //{ // string fileName7 = Path.Combine(baseMapFolder, "world_lakes.shp"); // if (File.Exists(fileName7)) // { // IFeatureSet fsLakes = FeatureSet.OpenFile(fileName7); // //fsLakes.Reproject(projWorld.WebMercator); // MapPolygonLayer layLakes = new MapPolygonLayer(fsLakes); // layLakes.LegendText = "lakes"; // PolygonSymbolizer symLakes = new PolygonSymbolizer(Color.Blue, // Color.Blue); // layLakes.Symbolizer = symLakes; // layLakes.ProgressReportingEnabled = false; // baseGroup.Layers.Add(layLakes); // layLakes.MapFrame = mainMap.MapFrame; // } //} //catch { } SetMapExtent(mainMap); return(true); }
public void SelectionTest() { IMap map = new Map(); // load layer with us states IMapLayer ml = map.AddLayer(Path.Combine(@"Testfiles", "50mil_us_states.shp")); IFeatureLayer fl = ml as IFeatureLayer; Assert.IsNotNull(fl); // add two categories for testing category.SelectionEnabled PolygonScheme scheme = new PolygonScheme(); scheme.ClearCategories(); scheme.AddCategory(new PolygonCategory(Color.LightBlue, Color.DarkBlue, 1) { FilterExpression = "[FIPS] >= 10", LegendText = ">= 10" }); var cat = new PolygonCategory(Color.Pink, Color.DarkRed, 1) { FilterExpression = "[FIPS] < 10", LegendText = "< 10" }; scheme.AddCategory(cat); fl.Symbology = scheme; Assert.IsTrue(cat.SelectionEnabled, "Categories must be initialized with SelectionEnabled = true."); // load the second layer for testing the layers SelectionEnabled property IMapLayer ml2 = map.AddLayer(Path.Combine(@"Testfiles", "50m_admin_0_countries.shp")); ml2.SelectionEnabled = false; IFeatureLayer fl2 = ml2 as IFeatureLayer; Assert.IsNotNull(fl2); // select the first area Envelope e = new Envelope(-72, -66, 40, 48); Assert.IsTrue(map.Select(e, e, ClearStates.False)); Assert.AreEqual(7, fl.Selection.Count, "Error selecting 50mil_us_states"); Assert.AreEqual(0, fl2.Selection.Count, "Error selecting 50m_admin_0_countries"); // invert a slighly larger area, ignoring the features of the second category cat.SelectionEnabled = false; Envelope e2 = new Envelope(-78, -66, 40, 48); Assert.IsTrue(map.InvertSelection(e2, e2)); Assert.AreEqual(4, fl.Selection.Count, "Error inverting selection 50mil_us_states"); Assert.AreEqual(0, fl2.Selection.Count, "Error inverting selection 50m_admin_0_countries"); // add another area allowing the second layer to be selected too ml2.SelectionEnabled = true; Envelope e3 = new Envelope(-89, -77, 24, 33); Assert.IsTrue(map.Select(e3, e3, ClearStates.False)); Assert.AreEqual(9, fl.Selection.Count, "Error adding to selection 50mil_us_states"); Assert.AreEqual(2, fl2.Selection.Count, "Error adding to selection 50m_admin_0_countries"); ml2.SelectionEnabled = false; // unselect the whole area ignoring the second layer and the deactivated category Envelope e4 = new Envelope(-89, -66, 24, 48); Assert.IsTrue(map.UnSelect(e4, e4)); Assert.AreEqual(1, fl.Selection.Count, "Error unselecting 50mil_us_states"); Assert.AreEqual(2, fl2.Selection.Count, "Error unselecting 50m_admin_0_countries"); }
public void TestSetViewExtents() { Map mainMap = new Map(); mainMap.Projection = KnownCoordinateSystems.Projected.World.WebMercator; Extent defaultMapExtent = new Extent(-130, 5, -70, 60); string baseMapFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles"); //SetDefaultMapExtents(mainMap); MapPolygonLayer layStates; MapGroup baseGroup = new MapGroup(mainMap.Layers, mainMap.MapFrame, mainMap.ProgressHandler); baseGroup.LegendText = "Base Map Data"; baseGroup.ParentMapFrame = mainMap.MapFrame; baseGroup.MapFrame = mainMap.MapFrame; baseGroup.IsVisible = true; //load the 'Countries of the world' layer try { string fileName = Path.Combine(baseMapFolder, "50m_admin_0_countries.shp"); IFeatureSet fsCountries = FeatureSet.OpenFile(fileName); fsCountries.Reproject(mainMap.Projection); MapPolygonLayer layCountries = new MapPolygonLayer(fsCountries); layCountries.LegendText = "Countries"; PolygonScheme schmCountries = new PolygonScheme(); schmCountries.EditorSettings.StartColor = Color.Orange; schmCountries.EditorSettings.EndColor = Color.Silver; schmCountries.EditorSettings.ClassificationType = ClassificationType.UniqueValues; schmCountries.EditorSettings.FieldName = "NAME"; schmCountries.EditorSettings.UseGradient = true; schmCountries.CreateCategories(layCountries.DataSet.DataTable); layCountries.Symbology = schmCountries; baseGroup.Layers.Add(layCountries); layCountries.MapFrame = mainMap.MapFrame; } catch { } //load U.S. states layer try { string fileName = Path.Combine(baseMapFolder, "50mil_us_states.shp"); IFeatureSet fsStates = FeatureSet.OpenFile(fileName); fsStates.Reproject(mainMap.Projection); layStates = new MapPolygonLayer(fsStates); PolygonScheme schmStates = new PolygonScheme(); layStates.IsVisible = true; layStates.LegendText = "U.S. States"; schmStates.EditorSettings.StartColor = Color.LemonChiffon; schmStates.EditorSettings.EndColor = Color.LightPink; schmStates.EditorSettings.ClassificationType = ClassificationType.UniqueValues; schmStates.EditorSettings.FieldName = "NAME"; schmStates.EditorSettings.UseGradient = true; schmStates.CreateCategories(layStates.DataSet.DataTable); layStates.Symbology = schmStates; baseGroup.Layers.Add(layStates); layStates.MapFrame = mainMap.MapFrame; } catch { } //load Canada Provinces layer try { string fileName = Path.Combine(baseMapFolder, "50mil_canada_provinces.shp"); IFeatureSet fsProvince = FeatureSet.OpenFile(fileName); fsProvince.Reproject(mainMap.Projection); MapPolygonLayer layProvince = new MapPolygonLayer(fsProvince); PolygonScheme schmProvince = new PolygonScheme(); layProvince.IsVisible = true; layProvince.LegendText = "Canada Provinces"; schmProvince.EditorSettings.StartColor = Color.Green; schmProvince.EditorSettings.EndColor = Color.Yellow; schmProvince.EditorSettings.ClassificationType = ClassificationType.UniqueValues; schmProvince.EditorSettings.FieldName = "NAME"; schmProvince.EditorSettings.UseGradient = true; schmProvince.CreateCategories(layProvince.DataSet.DataTable); layProvince.Symbology = schmProvince; baseGroup.Layers.Add(layProvince); layProvince.MapFrame = mainMap.MapFrame; } catch { } //theme data group //create a new empty 'themes' data group try { MapGroup themeGroup = new MapGroup(mainMap.Layers, mainMap.MapFrame, mainMap.ProgressHandler); themeGroup.ParentMapFrame = mainMap.MapFrame; themeGroup.MapFrame = mainMap.MapFrame; themeGroup.LegendText = "Themes"; } catch { } double[] xy = new double[4]; xy[0] = defaultMapExtent.MinX; xy[1] = defaultMapExtent.MinY; xy[2] = defaultMapExtent.MaxX; xy[3] = defaultMapExtent.MaxY; double[] z = new double[] { 0, 0 }; string esri = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223562997]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]"; ProjectionInfo wgs84 = ProjectionInfo.FromEsriString(esri); Reproject.ReprojectPoints(xy, z, wgs84, mainMap.Projection, 0, 2); xy[0] = 1000000000000000; xy[1] = 2000000000000000; xy[2] = 3000000000000000; xy[3] = 4000000000000000; Extent ext = new Extent(xy); mainMap.ViewExtents = ext; }
private void MenuClick(object sender, EventArgs e) { using (FormContour frm = new FormContour()) { frm.Layers = App.Map.GetRasterLayers(); if (frm.Layers.GetLength(0) <= 0) { MessageBox.Show(Resources.NoRasterLayerFound); return; } if (frm.ShowDialog() != DialogResult.OK) { return; } IMapFeatureLayer fl = App.Map.Layers.Add(frm.Contours); fl.LegendText = frm.LayerName + " - Contours"; int numlevs = frm.Lev.GetLength(0); switch (frm.Contourtype) { case Contour.ContourType.Line: { LineScheme ls = new LineScheme(); ls.Categories.Clear(); for (int i = 0; i < frm.Color.GetLength(0); i++) { LineCategory lc = new LineCategory(frm.Color[i], 2.0) { FilterExpression = "[Value] = " + frm.Lev[i], LegendText = frm.Lev[i].ToString(CultureInfo.InvariantCulture) }; ls.AddCategory(lc); } fl.Symbology = ls; } break; case Contour.ContourType.Polygon: { PolygonScheme ps = new PolygonScheme(); ps.Categories.Clear(); for (int i = 0; i < frm.Color.GetLength(0); i++) { PolygonCategory pc = new PolygonCategory(frm.Color[i], Color.Transparent, 0) { FilterExpression = "[Lev] = " + i, LegendText = frm.Lev[i] + " - " + frm.Lev[i + 1] }; ps.AddCategory(pc); } fl.Symbology = ps; } break; } } }
//------------------------------------------------------- public MapPolygonLayer AddFieldLayer(string Fieldname) { MapPolygonLayer MyLayer = null; if (MapDataTable != null) { if (MapDataTable.Columns.Contains(Fieldname)) { try { DataColumn DC = MapDataTable.Columns[Fieldname]; MyLayer = AddProviderShapeFile(Fieldname); //(MapPolygonLayer)ProviderMap.AddLayer(DataPath + ShapeFilename); if (MyLayer == null) { MessageBox.Show("The Base ShapeFile is not a polygon layer."); } else { // Get the years string yrfield = WaterSimManager_DB.rdbfSimYear; // MyLayer.DataSet.FillAttributes(); DataTable LayerDT = MyLayer.DataSet.DataTable; DataColumn AddColumn = new DataColumn(DC.ColumnName, DC.DataType); LayerDT.Columns.Add(AddColumn); foreach (DataRow DR in LayerDT.Rows) { Boolean found = false; string pfcode = DR["Provider"].ToString().Trim(); // Get the Provider Field code for this SHape File Record // find this code in Scenario DataTable foreach (DataRow ScnDR in MapDataTable.Rows) { if (ScnDR[yrfield].ToString().Trim() == MapTargetYear) { string Scnpfcode = ScnDR[WaterSimManager_DB.rdbfProviderCode].ToString().Trim(); // "PRVDCODE" if (pfcode == Scnpfcode) { DR[Fieldname] = ScnDR[Fieldname].ToString(); found = true; break; } if (!found) { if (DC.DataType == System.Type.GetType("System.String")) { DR[Fieldname] = ""; } else { DR[Fieldname] = 0; } } } //= provider } // = target year } //MyLayer.DataSet.FillAttributes(); if (DC.DataType == System.Type.GetType("System.String")) { PolygonScheme FldScheme = new PolygonScheme(); FldScheme.EditorSettings.ClassificationType = ClassificationType.UniqueValues; ////Set the UniqueValue field name FldScheme.EditorSettings.FieldName = Fieldname; // Create Catagories based on data FldScheme.CreateCategories(LayerDT); MyLayer.Symbology = FldScheme; } else { PolygonScheme FldScheme = new PolygonScheme(); FldScheme.EditorSettings.ClassificationType = ClassificationType.Quantities; FldScheme.EditorSettings.IntervalMethod = IntervalMethod.StandardDeviation; FldScheme.EditorSettings.NumBreaks = 8; FldScheme.EditorSettings.FieldName = Fieldname; FldScheme.AppearsInLegend = true; FldScheme.CreateCategories(LayerDT); PolygonCategory NullCat = new PolygonCategory(Color.WhiteSmoke, Color.DarkBlue, 1); NullCat.FilterExpression = "[" + Fieldname + "] = NULL"; NullCat.LegendText = "[" + Fieldname + "] = NULL"; FldScheme.AddCategory(NullCat); MyLayer.Symbology = FldScheme; } } } catch (Exception e) { MessageBox.Show("Error Loading Shape File:[ " + DataPath + ShapeFilename + "] :" + e.Message); } } } return(MyLayer); }