/// <summary>
        /// Displays search results (all data series and sites complying to the search criteria)
        /// </summary>
        public IEnumerable <IMapPointLayer> ShowSearchResults(SearchResult searchResult)
        {
            //try to save the search result layer and re-add it
            var    hdProjectPath = HydroDesktop.Configuration.Settings.Instance.CurrentProjectDirectory;
            String timeStamp     = string.Format("{0}_{1}{2}{3}",
                                                 DateTime.Now.Date.ToString("yyyy-MM-dd"), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

            var loadedFeatures = new List <SearchResultItem>(searchResult.ResultItems.Count());

            Debug.WriteLine(searchResult.ResultItems.Count());
            foreach (var key in searchResult.ResultItems)
            {
                Debug.WriteLine("hdProjectPath: " + hdProjectPath + "/Search Results");
                Debug.WriteLine("The other part: " + string.Format(HydroDesktop.Plugins.Search.Properties.Settings.Default.SearchResultNameMask, key.ServiceCode, timeStamp));
                var fs = key.FeatureSet;

                var filename = Path.Combine(hdProjectPath + "/Search Results",
                                            string.Format(HydroDesktop.Plugins.Search.Properties.Settings.Default.SearchResultNameMask, key.ServiceCode, timeStamp));
                fs.Filename = filename;
                fs.Save();
                loadedFeatures.Add(new SearchResultItem(key.ServiceCode, FeatureSet.OpenFile(filename)));
            }
            Debug.WriteLine("Loop done.");

            var _searchSettings    = new SearchSettings();
            var searchLayerCreator = new SearchLayerCreator(App.Map, new SearchResult(loadedFeatures), _searchSettings);

            return(searchLayerCreator.Create());
        }
Esempio n. 2
0
        public void OpenFileThrowsRightException(string missingFile, string errorMessage)
        {
            string missingFileExt = Path.GetExtension(missingFile);

            List <string> extensions = new() { ".shp", ".shx", ".dbf", ".prj" };

            extensions.Remove(missingFileExt);

            var source         = Path.Combine(_shapefiles, missingFile);
            var tmpFile        = FileTools.GetTempFileName(".shp");
            var missingTmpFile = Path.ChangeExtension(tmpFile, missingFileExt);

            foreach (var ext in extensions)
            {
                var sourceName  = Path.ChangeExtension(source, ext);
                var tmpFileName = Path.ChangeExtension(tmpFile, ext);

                Assert.NotNull(tmpFileName, "tmpFileName != null");
                File.Copy(sourceName, tmpFileName);
            }

            if (errorMessage != string.Empty)
            {
                var e = Assert.Throws <FileNotFoundException>(() => FeatureSet.OpenFile(tmpFile));
                Assert.AreEqual(string.Format(errorMessage, missingTmpFile), e.Message);
            }
            else
            {
                Assert.DoesNotThrow(() => FeatureSet.OpenFile(tmpFile));
            }

            FileTools.DeleteShapeFile(tmpFile);
        }
Esempio n. 3
0
        private static Layer GetPolygonLayer(dynamic layer)
        {
            MapPolygonLayer polyLayer = new MapPolygonLayer(FeatureSet.OpenFile(layer["Path"]));

            LegacyDeserializer.DeserializeLayer(layer, polyLayer);

            return(polyLayer);
        }
Esempio n. 4
0
        private static Layer GetLineLayer(dynamic layer)
        {
            MapLineLayer lineLayer = new MapLineLayer(FeatureSet.OpenFile(layer["Path"]));

            LegacyDeserializer.DeserializeLayer(layer, lineLayer);

            return(lineLayer);
        }
Esempio n. 5
0
        /// <summary>
        /// Displays search results (all data series and sites complying to the search criteria)
        /// </summary>
        private void ShowSearchResults(SearchResult searchResult)
        {
            //try to save the search result layer and re-add it
            var hdProjectPath = HydroDesktop.Configuration.Settings.Instance.CurrentProjectDirectory;

            var loadedFeatures = new List <SearchResultItem>(searchResult.ResultItems.Count());

            foreach (var key in searchResult.ResultItems)
            {
                var fs       = key.FeatureSet;
                var filename = Path.Combine(hdProjectPath,
                                            string.Format(Properties.Settings.Default.SearchResultNameMask, key.ServiceCode));
                fs.Filename = filename;
                fs.Save();
                loadedFeatures.Add(new SearchResultItem(key.ServiceCode, FeatureSet.OpenFile(filename)));
            }

            var searchLayerCreator = new SearchLayerCreator(App.Map, new SearchResult(loadedFeatures));

            searchLayerCreator.Create();
        }
        /// <summary>
        /// Load base maps for World template project. The base shapefiles
        /// are loaded from the [Program Files]\[Cuahsi HIS]\HydroDesktop\maps\BaseData folder.
        /// </summary>
        public static Boolean LoadBaseMaps(AppManager applicationManager1, Map mainMap)
        {
            //set the projection of main map
            mainMap.Projection = projWorld.WebMercator;

            Extent defaultMapExtent = new Extent(-170, -50, 170, 50);

            string baseMapFolder = Settings.Instance.DefaultBaseMapDirectory;

            //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
            {
                mainMap.BackColor = Color.LightBlue;

                string fileName = Path.Combine(baseMapFolder, "world_countries.shp");
                if (File.Exists(fileName))
                {
                    IFeatureSet     fsCountries  = FeatureSet.OpenFile(fileName);
                    MapPolygonLayer layCountries = new MapPolygonLayer(fsCountries);
                    layCountries.LegendText = "Countries";
                    layCountries.Symbolizer = new PolygonSymbolizer(Color.FromArgb(255, 239, 213), Color.LightGray);
                    //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);
                    mainMap.Layers.Add(layCountries);
                    layCountries.MapFrame = mainMap.MapFrame;
                    layCountries.ProgressReportingEnabled = false;
                }
            }
            catch { }


            //load a rivers layer
            try
            {
                var fileName = Path.Combine(baseMapFolder, "world_rivers.shp");
                if (File.Exists(fileName))
                {
                    IFeatureSet fsRivers = FeatureSet.OpenFile(fileName);
                    //fsRivers.Reproject(mainMap.Projection);
                    MapLineLayer layRivers = new MapLineLayer(fsRivers);
                    layRivers.LegendText = "rivers";
                    LineSymbolizer symRivers = new LineSymbolizer(Color.Blue, 1.0);
                    layRivers.Symbolizer = symRivers;
                    mainMap.Layers.Add(layRivers);
                    layRivers.MapFrame = mainMap.MapFrame;
                }
            }
            catch { }

            //load a lakes layer
            try
            {
                var fileName = Path.Combine(baseMapFolder, "world_lakes.shp");
                if (File.Exists(fileName))
                {
                    IFeatureSet fsLakes = FeatureSet.OpenFile(fileName);
                    //fsLakes.Reproject(mainMap.Projection);
                    MapPolygonLayer layLakes = new MapPolygonLayer(fsLakes);
                    layLakes.LegendText = "lakes";
                    PolygonSymbolizer symLakes = new PolygonSymbolizer(Color.Blue,
                                                                       Color.Blue);
                    layLakes.Symbolizer = symLakes;
                    mainMap.Layers.Add(layLakes);
                    layLakes.MapFrame = mainMap.MapFrame;
                    layLakes.ProgressReportingEnabled = false;
                }
            }
            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 };
            var      wgs84 = ProjectionInfo.FromEsriString(Properties.Resources.wgs_84_esri_string);

            Reproject.ReprojectPoints(xy, z, wgs84, mainMap.Projection, 0, 2);

            mainMap.ViewExtents = new Extent(xy);

            return(true);
        }
        /// <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);
        }
Esempio n. 8
0
        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;
        }
        /// <summary>
        /// Deserializes beginning from the given root.
        /// </summary>
        /// <param name="xmlRoot">Root to use as string point.</param>
        public void Deserialize(dynamic xmlRoot)
        {
            var mapwin4Section   = xmlRoot.MapWindow4;
            var mapwingisSection = xmlRoot.MapWinGIS;

            _map.MapFrame.ProjectionString = mapwin4Section["ProjectProjection"];

            if (!Convert.ToBoolean(mapwin4Section["ViewBackColor_UseDefault"]))
            {
                var mapControl = _map as Control;
                if (mapControl != null)
                {
                    mapControl.BackColor = LegacyDeserializer.GetColor(mapwin4Section["ViewBackColor"]);
                }

                _map.Invalidate();
            }

            // Deserialize layers
            var layersDescs = mapwingisSection.Layers.Elements();
            var allLayers   = new Dictionary <int, List <ILayer> >(); // key: Group Name. Value: layers

            foreach (var layer in mapwin4Section.Layers.Elements())
            {
                var name     = (string)layer["Name"];
                var groupInd = Convert.ToInt32(layer["GroupIndex"]);
                if (!allLayers.ContainsKey(groupInd))
                {
                    allLayers[groupInd] = new List <ILayer>();
                }
                var listLayers = allLayers[groupInd];

                IMapLayer layerToAdd = null;
                foreach (var layersDesc in layersDescs)
                {
                    if (layersDesc["LayerName"] == name)
                    {
                        var lt = (string)layersDesc["LayerType"];
                        switch (lt)
                        {
                        case "Image":
                            layerToAdd = new MapImageLayer(ImageData.Open(layersDesc["Filename"]));
                            break;

                        case "Shapefile":
                            var fs = FeatureSet.OpenFile(layersDesc["Filename"]);
                            if (fs is PointShapefile)
                            {
                                layerToAdd = new MapPointLayer(fs);
                            }
                            else if (fs is PolygonShapefile)
                            {
                                layerToAdd = new MapPolygonLayer(fs);
                            }
                            else if (fs is LineShapefile)
                            {
                                layerToAdd = new MapLineLayer(fs);
                            }
                            else
                            {
                                var type = (object)fs.GetType().ToString();
                                Trace.WriteLine("Unsupported FeatureSet Type: " + type);
                            }

                            break;

                        default:
                            Trace.WriteLine("Unsupported LayerType: " + lt);
                            break;
                        }

                        break;
                    }
                }

                if (layerToAdd != null)
                {
                    layerToAdd.IsExpanded = Convert.ToBoolean(layer["Expanded"]);
                    listLayers.Add(layerToAdd);
                }
            }

            // Deserialize groups
            foreach (var group in mapwin4Section.Groups.Elements())
            {
                var gInd = Convert.ToInt32(group["Position"]);
                var g    = new MapGroup
                {
                    LegendText = group["Name"],
                    IsExpanded = Convert.ToBoolean(group["Expanded"])
                };
                List <ILayer> gl;
                if (allLayers.TryGetValue(gInd, out gl))
                {
                    foreach (var layer in gl)
                    {
                        g.Add(layer);
                    }
                }

                _map.MapFrame.Layers.Add(g);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// given a data table, create an in-memory point feature set.
        /// The feature set must have the 'Latitude' and 'Longitude' numeric
        /// columns
        /// </summary>
        /// <param name="themeTable">The table of distinct series</param>
        /// <param name="projection">The projection of the theme feature set</param>
        /// <returns>A point FeatureSet in the WGS-84 coordinate system
        /// All columns of the data table will be converted to atrribute fields</returns>
        private IFeatureSet TableToFeatureSet(DataTable themeTable, ProjectionInfo projection = null)
        {
            //index of the Latitude column
            int latColIndex = -1;

            //index of the Longitude column
            int lonColIndex = -1;

            //get the latitude and longitude column indices
            for (int col = 0; col < themeTable.Columns.Count; col++)
            {
                string colName = themeTable.Columns[col].ColumnName.ToLower();

                if (colName == "latitude")
                {
                    latColIndex = col;
                }

                if (colName == "longitude")
                {
                    lonColIndex = col;
                }
            }

            //check if the latitude column exists
            if (latColIndex == -1)
            {
                throw new ArgumentException("The table doesn't have a column 'Latitude'");
            }
            //check if the longitude column exists
            if (lonColIndex == -1)
            {
                throw new ArgumentException("The table doesn't have a column 'Longitude'");
            }

            //generate attribute table schema
            var fs             = new FeatureSet(FeatureType.Point);
            var attributeTable = fs.DataTable;

            foreach (DataColumn column in themeTable.Columns)
            {
                attributeTable.Columns.Add(column.DataType == typeof(DateTime)
                                               ? new Field(column.ColumnName, 'C', 16, 0)
                                               : new DataColumn(column.ColumnName, column.DataType));
            }

            //generate features
            foreach (DataRow row in themeTable.Rows)
            {
                double lat        = Convert.ToDouble(row[latColIndex]);
                double lon        = Convert.ToDouble(row[lonColIndex]);
                var    coord      = new Coordinate(lon, lat);
                var    newFeature = new Feature(FeatureType.Point, new[] { coord });
                fs.Features.Add(newFeature);

                var featureRow = newFeature.DataRow;
                for (int c = 0; c < attributeTable.Columns.Count; c++)
                {
                    featureRow[c] = themeTable.Columns[c].DataType == typeof(DateTime)
                                        ? ConvertTime((DateTime)row[c])
                                        : row[c];
                }
            }

            //to save the feature set to a file with unique name
            string uniqueID = DateTime.Now.ToString("yyyyMMdd_hhmmss");
            var    rnd      = new Random();

            uniqueID += rnd.Next(100).ToString("000");
            var filename = Path.Combine(Settings.Instance.CurrentProjectDirectory, "theme_" + uniqueID + ".shp");

            fs.Filename   = filename;
            fs.Projection = _wgs84Projection;
            fs.Save();
            fs.Dispose();

            var fs2 = FeatureSet.OpenFile(filename);

            //to reproject the feature set
            if (projection != null)
            {
                fs2.Reproject(projection);
            }

            return(fs2);
        }