Exemple #1
0
 private void Setup()
 {
     // Load the layer
     try
     {
         mapControl1.Map.Load(new MapTableLoader("mexico.tab"));
         FeatureLayer layer = mapControl1.Map.Layers["mexico"] as FeatureLayer;
         LabelLayer labelLayer = new LabelLayer("Label Layer", "Label Layer");
         labelLayer.Sources.Append(new LabelSource(layer.Table));
         mapControl1.Map.Layers.Add(labelLayer);
     }
     catch(Exception)
     {
         mnuCloseTable.Enabled = false;
         mnuCloseAll.Enabled = false;
         mnuTheme.Enabled = false;
     }
 }
Exemple #2
0
        private static Map InitializeMapOsm(float angle)
        {
            //Transparent style
            VectorStyle transparentStyle = new VectorStyle();

            transparentStyle.Fill          = Brushes.Transparent;
            transparentStyle.EnableOutline = true; //otherwise all the fancy theming stuff won't work!
            transparentStyle.Line.Brush    = Brushes.Transparent;
            transparentStyle.Outline.Brush = Brushes.Transparent;
            transparentStyle.Symbol        = null;

            VectorStyle transparentStyle2 = new VectorStyle();

            transparentStyle2.Fill          = Brushes.Transparent;
            transparentStyle2.EnableOutline = true; //otherwise all the fancy theming stuff won't work!
            transparentStyle2.Line.Brush    = Brushes.Transparent;
            transparentStyle2.Outline.Brush = Brushes.Transparent;
            transparentStyle2.Symbol        = null;

            //Initialize a new map
            Map map = new Map();

            map.BackColor = Color.Cornsilk;

            var encoding = System.Text.Encoding.UTF8;

            //Set up the countries layer
            VectorLayer layNatural = new VectorLayer("Natural");

            //Set the datasource to a shapefile in the App_data folder
            layNatural.DataSource = new ShapeFile(string.Format("{0}/natural.shp", PathOsm), true)
            {
                Encoding = encoding
            };
            //Set default style to draw nothing
            layNatural.Style = transparentStyle;
            //Set theme
            ThemeViaDelegate theme = new ThemeViaDelegate(layNatural.Style, "type");

            theme.GetStyleFunction = delegate(FeatureDataRow row)
            {
                string caseVal = (String)row["type"];
                caseVal = caseVal.ToLowerInvariant();
                VectorStyle returnStyle = new VectorStyle();

                switch (caseVal)
                {
                case "forest":
                    returnStyle.Fill          = Brushes.ForestGreen;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.DarkGreen;
                    break;

                case "water":
                    returnStyle.Fill          = Brushes.Aqua;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.DarkBlue;
                    break;

                case "riverbank":
                    returnStyle.Fill          = Brushes.Peru;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.OrangeRed;
                    break;

                case "park":
                    returnStyle.Fill          = Brushes.PaleGreen;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.DarkGreen;
                    break;

                default:
                    returnStyle = null;
                    break;
                }
                return(returnStyle);
            };
            layNatural.Theme = theme;
            layNatural.SRID  = 31466;

            VectorLayer layRoads = new VectorLayer("Roads");

            layRoads.DataSource = new ShapeFile(string.Format("{0}/roads.shp", PathOsm))
            {
                Encoding = encoding
            };
            layRoads.DataSource.Open();
            _roadsExtents = layRoads.DataSource.GetExtents();
            //layRoads.DataSource.Close();
            layRoads.Style = transparentStyle;
            ThemeViaDelegate themeRoads = new ThemeViaDelegate(transparentStyle, "type");

            themeRoads.GetStyleFunction = delegate(FeatureDataRow row)
            {
                VectorStyle returnStyle = new VectorStyle();

                switch ((String)row["type"])
                {
                case "rail":
                    returnStyle.Fill             = Brushes.White;
                    returnStyle.Line.DashPattern = new float[] { 4f, 4f };                                      //;System.Drawing.Drawing2D.DashStyle.Dash;
                    returnStyle.Line.Width       = 4;
                    returnStyle.EnableOutline    = true;
                    returnStyle.Outline.Brush    = Brushes.Black;
                    returnStyle.Outline.Width    = 6;
                    break;

                case "canal":
                    returnStyle.Fill          = Brushes.Aqua;
                    returnStyle.Outline.Brush = Brushes.DarkBlue;
                    returnStyle.Outline.Width = 5;
                    break;

                case "cycleway":
                case "footway":
                case "pedestrian":
                    returnStyle.Line.Brush     = Brushes.DarkGray;
                    returnStyle.Line.DashStyle =
                        DashStyle.Dot;
                    returnStyle.Line.Width = 1;
                    returnStyle.MaxVisible = _roadsExtents.Width * 0.05d;
                    break;

                case "living_street":
                case "residential":
                    returnStyle.Line.Brush    = Brushes.LightGoldenrodYellow;
                    returnStyle.Line.Width    = 2;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.DarkGray;
                    returnStyle.Outline.Width = 4;
                    returnStyle.MaxVisible    = _roadsExtents.Width * 0.15d;
                    break;

                case "primary":
                    returnStyle.Line.Brush    = Brushes.LightGoldenrodYellow;
                    returnStyle.Line.Width    = 7;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.Black;
                    returnStyle.Outline.Width = 11;
                    break;

                case "secondary":
                    returnStyle.Line.Brush    = Brushes.LightGoldenrodYellow;
                    returnStyle.Line.Width    = 6;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.Black;
                    returnStyle.MaxVisible    = _roadsExtents.Width * 0.3d;
                    returnStyle.Outline.Width = 10;
                    break;

                case "tertiary":
                    returnStyle.Line.Brush    = Brushes.LightGoldenrodYellow;
                    returnStyle.Line.Width    = 5;
                    returnStyle.EnableOutline = true;
                    returnStyle.Outline.Brush = Brushes.Black;
                    returnStyle.MaxVisible    = _roadsExtents.Width * 0.6d;
                    returnStyle.Outline.Width = 9;
                    break;

                case "path":
                case "track":
                case "unclassified":
                    returnStyle.Line.Brush     = Brushes.DarkGray;
                    returnStyle.Line.DashStyle =
                        DashStyle.DashDotDot;
                    returnStyle.Line.Width = 1;
                    returnStyle.MaxVisible = _roadsExtents.Width * 0.025d;
                    break;

                default:
                    returnStyle = null;
                    break;
                }
                return(returnStyle);
            };
            layRoads.Theme = themeRoads;
            layRoads.SRID  = 31466;

            VectorLayer layRail = new VectorLayer("Railways");

            layRail.DataSource = new ShapeFile(string.Format("{0}/railways.shp", PathOsm))
            {
                Encoding = encoding
            };
            layRail.Style.Line.Brush       = Brushes.White;
            layRail.Style.Line.DashPattern = new float[] { 4f, 4f };//;System.Drawing.Drawing2D.DashStyle.Dash;
            layRail.Style.Line.Width       = 4;
            layRail.Style.EnableOutline    = true;
            layRail.Style.Outline.Brush    = Brushes.Black;
            layRail.Style.Outline.Width    = 6;

            VectorLayer layWaterways = new VectorLayer("Waterways");

            layWaterways.Style      = transparentStyle;
            layWaterways.DataSource = new ShapeFile(string.Format("{0}/waterways.shp", PathOsm))
            {
                Encoding = encoding
            };
            layRoads.Style = transparentStyle;
            ThemeViaDelegate themeWater = new ThemeViaDelegate(transparentStyle, "type");

            themeWater.GetStyleFunction = delegate(FeatureDataRow row)
            {
                VectorStyle returnStyle = new VectorStyle();
                returnStyle.Line.Brush    = Brushes.Aqua;
                returnStyle.EnableOutline = true;
                Int32 lineWidth = 1;
                switch ((String)row["type"])
                {
                case "canal":
                case "derelict_canal":
                    lineWidth = 2;
                    break;

                case "drain":
                    returnStyle.EnableOutline = false;
                    break;

                case "stream":
                    lineWidth = 2;
                    break;

                default:
                    //returnStyle = null;
                    break;
                }
                returnStyle.Line.Width    = lineWidth;
                returnStyle.Outline.Brush = Brushes.DarkBlue;
                returnStyle.Outline.Width = lineWidth + 1;
                return(returnStyle);
            };
            layWaterways.Theme = themeWater;
            layWaterways.SRID  = 31466;

            VectorLayer layPoints = new VectorLayer("Points");

            layPoints.DataSource = new ShapeFile(string.Format("{0}/points.shp", PathOsm))
            {
                Encoding = encoding
            };
            layPoints.Style = transparentStyle2;
            ThemeViaDelegate themePoints = new ThemeViaDelegate(transparentStyle2, "type");

            themePoints.GetStyleFunction = delegate(FeatureDataRow row)
            {
                VectorStyle returnStyle = new VectorStyle();
                switch ((String)row["type"])
                {
                case "bank":
                    returnStyle.Symbol = new Bitmap("Images/Bank.gif");
                    break;

                case "hospital":
                    returnStyle.Symbol = new Bitmap("Images/Medical-Facility.gif");
                    break;

                case "hotel":
                    returnStyle.Symbol = new Bitmap("Images/Hotel.gif");
                    break;

                case "restaurant":
                case "fast-food":
                    returnStyle.Symbol = new Bitmap("Images/Restaurant.gif");
                    break;

                case "parking":
                    returnStyle.Symbol = new Bitmap("Images/Car.gif");
                    break;

                default:
                    Bitmap tmp = new Bitmap(1, 1);
                    tmp.SetPixel(0, 0, Color.Transparent);
                    returnStyle.Symbol = tmp;
                    break;
                }
                return(returnStyle);
            };
            layPoints.Theme   = themePoints;
            layWaterways.SRID = 31466;

            var layLabel = new LabelLayer("Road Labels");

            layLabel.DataSource  = layRoads.DataSource;
            layLabel.LabelColumn = "Name";

            //Add layers to Map
            map.Layers.Add(layNatural);
            map.Layers.Add(layWaterways);
            map.Layers.Add(layRail);
            map.Layers.Add(layRoads);
            map.Layers.Add(layPoints);
            map.Layers.Add(layLabel);

            ShapeProvider sp = new ShapeProvider(string.Format("{0}/obepath.shp", PathOsm))
            {
                Encoding = encoding
            };
            VectorLayer vl = new VectorLayer("obepath", sp);

            vl.SRID = 31466;
            var bmp = new Bitmap("Images/Car.gif");

            bmp.MakeTransparent(bmp.GetPixel(0, 0));
            vl.Style.Symbol = bmp;

            VariableLayerCollection.Interval = 500;
            map.VariableLayers.Add(vl);

            //Restrict zoom
            map.MaximumZoom = layRoads.Envelope.Width * 0.75d;
            map.Zoom        = layRoads.Envelope.Width * 0.2d;;
            map.Center      = layRoads.Envelope.Centre;

            var disclaimer = new Disclaimer
            {
                Font   = new Font(FontFamily.GenericSansSerif, 7f, FontStyle.Italic),
                Text   = "Geodata from OpenStreetMap (CC-by-SA)\nTransformed to Shapefile by geofabrik.de",
                Anchor = MapDecorationAnchor.CenterBottom
            };

            map.Decorations.Add(disclaimer);
            transparentStyle2.MaxVisible = map.MaximumZoom * 0.3;

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Exemple #3
0
        private static Map InitializeMapOrig(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layCountries = new VectorLayer("Countries");

            //Set the datasource to a shapefile in the App_data folder
            layCountries.DataSource = new ShapeFile("GeoData/World/countries.shp", true);
            //Set fill-style to green
            layCountries.Style.Fill = new SolidBrush(Color.FromArgb(64, Color.Green));
            //Set the polygons to have a black outline
            layCountries.Style.Outline       = Pens.Black;
            layCountries.Style.EnableOutline = true;
            layCountries.SRID = 4326;

            //Set up a river layer
            VectorLayer layRivers = new VectorLayer("Rivers");

            //Set the datasource to a shapefile in the App_data folder
            layRivers.DataSource = new ShapeFile("GeoData/World/rivers.shp", true);
            //Define a blue 1px wide pen
            layRivers.Style.Line = new Pen(Color.Blue, 1);
            layRivers.SRID       = 4326;

            //Set up a cities layer
            VectorLayer layCities = new VectorLayer("Cities");

            //Set the datasource to a shapefile in the App_data folder
            layCities.DataSource        = new ShapeFile("GeoData/World/cities.shp", true);
            layCities.Style.SymbolScale = 0.8f;
            layCities.MaxVisible        = 40;
            layCities.SRID = 4326;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Country labels");

            layLabel.DataSource                = layCountries.DataSource;
            layLabel.Enabled                   = true;
            layLabel.LabelColumn               = "Name";
            layLabel.Style                     = new LabelStyle();
            layLabel.Style.ForeColor           = Color.White;
            layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
            layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
            layLabel.MaxVisible                = 90;
            layLabel.MinVisible                = 30;
            layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
            layLabel.SRID = 4326;
            layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;
            layLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
            layLabel.Style.CollisionDetection = true;
            layLabel.LabelPositionDelegate    = fdr => fdr.Geometry.InteriorPoint.Coordinate;
            layLabel.PriorityColumn           = "POPDENS";

            //Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels");

            layCityLabel.DataSource                = layCities.DataSource;
            layCityLabel.Enabled                   = true;
            layCityLabel.LabelColumn               = "Name";
            layCityLabel.Style                     = new LabelStyle();
            layCityLabel.Style.ForeColor           = Color.Black;
            layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
            layCityLabel.MaxVisible                = layLabel.MinVisible;
            layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
            layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
            layCityLabel.Style.Offset              = new PointF(3, 3);
            layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
            layCityLabel.TextRenderingHint         = TextRenderingHint.AntiAlias;
            layCityLabel.SmoothingMode             = SmoothingMode.AntiAlias;
            layCityLabel.SRID        = 4326;
            layCityLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
            layCityLabel.Style.CollisionDetection = true;
            layCityLabel.PriorityColumn           = "POPULATION";
            layCityLabel.Theme = new GradientTheme(layCityLabel.PriorityColumn, 250000, 5000000,
                                                   new LabelStyle
            {
                MaxVisible          = 10,
                CollisionBuffer     = new Size(0, 0), CollisionDetection = true, Enabled = true,
                ForeColor           = Color.LightSlateGray, Halo = new Pen(Color.Silver, 1),
                HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Middle,
                Font = new Font(GenericFontFamilies.SansSerif.ToString(), 8f, FontStyle.Regular)
            },
                                                   new LabelStyle
            {
                MaxVisible          = layLabel.MinVisible,
                CollisionBuffer     = new Size(3, 3), CollisionDetection = true, Enabled = true,
                ForeColor           = Color.LightSlateGray, Halo = new Pen(Color.Silver, 5),
                HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Middle,
                Font = new Font(GenericFontFamilies.SansSerif.ToString(), 16f, FontStyle.Bold)
            });

            bool ignoreLength = false;

            var layRiverLabel = new LabelLayer("River labels")
            {
                DataSource        = layRivers.DataSource,
                Enabled           = true,
                LabelColumn       = "Name",
                TextRenderingHint = TextRenderingHint.AntiAlias,
                SmoothingMode     = SmoothingMode.AntiAlias,
                SRID        = 4326,
                LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection,
                MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.CommonCenter,
                Style =
                    new LabelStyle
                {
                    ForeColor           = Color.DarkBlue,
                    Font                = new Font(FontFamily.GenericSansSerif, 11),
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                    VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Middle,
                    //CollisionDetection = true,
                    Halo         = new Pen(Color.Azure, 2),
                    IgnoreLength = ignoreLength,
                    Offset       = new PointF(0, -10)
                },
            };

            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            //map.BackgroundLayer.Add(AsyncLayerProxyLayer.Create(layCountries));
            map.Layers.Add(layCountries);
            map.Layers.Add(layRivers);
            map.Layers.Add(layCities);
            map.Layers.Add(layLabel);
            map.Layers.Add(layCityLabel);
            map.Layers.Add(layRiverLabel);


            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.Zoom   = 360;
            map.Center = new Point(0, 0);

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Exemple #4
0
        public static void Render(Graphics graphics, IViewport viewport, LabelLayer labelLayer)
        {
            var layerStyles = BaseLayer.GetLayerStyles(labelLayer);

            foreach (var layerStyle in layerStyles)
            {
                if (layerStyle.Enabled && labelLayer.MaxVisible >= viewport.Resolution && labelLayer.MinVisible < viewport.Resolution)
                {
                    if (labelLayer.DataSource == null)
                    {
                        throw (new ApplicationException("DataSource property not set"));
                    }

                    graphics.SmoothingMode = SmoothingMode.AntiAlias;

                    var features = labelLayer.GetFeaturesInView(viewport.Extent, viewport.Resolution);

                    //Initialize label collection
                    var labels = new List <Label>();

                    var style = layerStyle as LabelStyle;

                    //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection
                    //Render labels
                    foreach (IFeature feature in features)
                    {
                        if (layerStyle is IThemeStyle)
                        {
                            style = (layerStyle as IThemeStyle).GetStyle(feature) as LabelStyle;
                        }

                        float rotation = 0;
                        if (!String.IsNullOrEmpty(labelLayer.RotationColumn))
                        {
                            rotation = float.Parse(feature[labelLayer.RotationColumn].ToString(), NumberStyles.Any, CultureInfo.InvariantCulture);
                        }

                        int priority = labelLayer.Priority;
                        if (labelLayer.PriorityDelegate != null)
                        {
                            priority = labelLayer.PriorityDelegate(feature);
                        }
                        else if (!String.IsNullOrEmpty(labelLayer.PriorityColumn))
                        {
                            priority = int.Parse(feature[labelLayer.PriorityColumn].ToString(), NumberStyles.Any, CultureInfo.InvariantCulture);
                        }

                        string text;

                        if (labelLayer.LabelStringDelegate != null)
                        {
                            text = labelLayer.LabelStringDelegate(feature);
                        }
                        else
                        {
                            text = feature[labelLayer.LabelColumn].ToString();
                        }

                        if (!string.IsNullOrEmpty(text))
                        {
                            if (feature.Geometry is GeometryCollection)
                            {
                                var geometryCollection = feature.Geometry as GeometryCollection;
                                if (labelLayer.MultipartGeometryBehaviour == LabelLayer.MultipartGeometryBehaviourEnum.All)
                                {
                                    foreach (var geometry in geometryCollection)
                                    {
                                        var label = CreateLabel(geometry, text, rotation, priority, style, viewport, graphics);
                                        if (label != null)
                                        {
                                            labels.Add(label);
                                        }
                                    }
                                }
                                else if (labelLayer.MultipartGeometryBehaviour == LabelLayer.MultipartGeometryBehaviourEnum.CommonCenter)
                                {
                                    var label = CreateLabel(feature.Geometry, text, rotation, priority, style, viewport, graphics);
                                    if (label != null)
                                    {
                                        labels.Add(label);
                                    }
                                }
                                else if (labelLayer.MultipartGeometryBehaviour == LabelLayer.MultipartGeometryBehaviourEnum.First)
                                {
                                    if ((feature.Geometry as GeometryCollection).Collection.Count > 0)
                                    {
                                        Label label = CreateLabel(geometryCollection.Collection[0], text, rotation, 0,
                                                                  style, viewport, graphics);
                                        if (label != null)
                                        {
                                            labels.Add(label);
                                        }
                                    }
                                }
                                else if (labelLayer.MultipartGeometryBehaviour == LabelLayer.MultipartGeometryBehaviourEnum.Largest)
                                {
                                    var coll = (feature.Geometry as GeometryCollection);
                                    if (coll.NumGeometries > 0)
                                    {
                                        double largestVal   = 0;
                                        int    idxOfLargest = 0;
                                        for (var j = 0; j < coll.NumGeometries; j++)
                                        {
                                            Geometry geom = coll.Geometry(j);
                                            if (geom is LineString && ((LineString)geom).Length > largestVal)
                                            {
                                                largestVal   = ((LineString)geom).Length;
                                                idxOfLargest = j;
                                            }
                                            if (geom is MultiLineString && ((MultiLineString)geom).Length > largestVal)
                                            {
                                                largestVal   = ((MultiLineString)geom).Length;
                                                idxOfLargest = j;
                                            }
                                            if (geom is Polygon && ((Polygon)geom).Area > largestVal)
                                            {
                                                largestVal   = ((Polygon)geom).Area;
                                                idxOfLargest = j;
                                            }
                                            if (geom is MultiPolygon && ((MultiPolygon)geom).Area > largestVal)
                                            {
                                                largestVal   = ((MultiPolygon)geom).Area;
                                                idxOfLargest = j;
                                            }
                                        }

                                        var label = CreateLabel(coll.Geometry(idxOfLargest), text, rotation, priority, style,
                                                                viewport, graphics);
                                        if (label != null)
                                        {
                                            labels.Add(label);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var label = CreateLabel(feature.Geometry, text, rotation, priority, style, viewport, graphics);
                                if (label != null)
                                {
                                    labels.Add(label);
                                }
                            }
                        }
                    }

                    if (labels.Count > 0) //We have labels to render...
                    {
                        if ((layerStyle is LabelStyle) && (layerStyle as LabelStyle).CollisionDetection && labelLayer.LabelFilter != null)
                        {
                            labelLayer.LabelFilter(labels);
                        }
                        foreach (Label label in labels)
                        {
                            if (!label.Show)
                            {
                                continue;
                            }
                            LabelRenderer.DrawLabel(graphics, label.LabelPoint, label.Style.Offset, label.Style.Font,
                                                    label.Style.ForeColor, label.Style.BackColor, label.Halo, label.Rotation, label.Text, viewport);
                        }
                    }
                }
            }
        }
Exemple #5
0
        private static Map InitializeMapOrig(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layCountries = new VectorLayer("Countries");

            //Set the datasource to a shapefile in the App_data folder
            layCountries.DataSource = new ShapeFile("GeoData/World/countries.shp", true);
            //Set fill-style to green
            layCountries.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            layCountries.Style.Outline       = Pens.Black;
            layCountries.Style.EnableOutline = true;
            layCountries.SRID = 4326;

            //Set up a river layer
            VectorLayer layRivers = new VectorLayer("Rivers");

            //Set the datasource to a shapefile in the App_data folder
            layRivers.DataSource = new ShapeFile("GeoData/World/rivers.shp", true);
            //Define a blue 1px wide pen
            layRivers.Style.Line = new Pen(Color.Blue, 1);
            layRivers.SRID       = 4326;

            //Set up a cities layer
            VectorLayer layCities = new VectorLayer("Cities");

            //Set the datasource to a shapefile in the App_data folder
            layCities.DataSource        = new ShapeFile("GeoData/World/cities.shp", true);
            layCities.Style.SymbolScale = 0.8f;
            layCities.MaxVisible        = 40;
            layCities.SRID = 4326;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Country labels");

            layLabel.DataSource                = layCountries.DataSource;
            layLabel.Enabled                   = true;
            layLabel.LabelColumn               = "Name";
            layLabel.Style                     = new LabelStyle();
            layLabel.Style.ForeColor           = Color.White;
            layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
            layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
            layLabel.MaxVisible                = 90;
            layLabel.MinVisible                = 30;
            layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
            layLabel.SRID = 4326;
            layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;

            //Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels");

            layCityLabel.DataSource                = layCities.DataSource;
            layCityLabel.Enabled                   = true;
            layCityLabel.LabelColumn               = "Name";
            layCityLabel.Style                     = new LabelStyle();
            layCityLabel.Style.ForeColor           = Color.Black;
            layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
            layCityLabel.MaxVisible                = layLabel.MinVisible;
            layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
            layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
            layCityLabel.Style.Offset              = new PointF(3, 3);
            layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
            layCityLabel.TextRenderingHint         = TextRendering.AntiAlias;
            layCityLabel.SmoothingMode             = Smoothing.AntiAlias;
            layCityLabel.SRID        = 4326;
            layCityLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
            layCityLabel.Style.CollisionDetection = true;

            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            map.Layers.Add(layCountries);
            map.Layers.Add(layRivers);
            map.Layers.Add(layCities);
            map.Layers.Add(layLabel);
            map.Layers.Add(layCityLabel);


            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.Zoom   = 360;
            map.Center = new Point(0, 0);

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Exemple #6
0
        public static Map InitializeMap(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layCountries = new VectorLayer("OracleSample");

            //Set the datasource to a shapefile in the App_data folder
            layCountries.DataSource = new SharpMap.Data.Providers.OracleProvider("system", "metsys", "127.0.0.1",
                                                                                 "COUNTRIES", "GEOM", "ID");
            //System.Diagnostics.Debug.WriteLine(layCountries.DataSource.GetGeometryByOid(101).ToString());

            //Set fill-style to green
            layCountries.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            layCountries.Style.Outline       = Pens.Black;
            layCountries.Style.EnableOutline = true;

            //Set up a river layer
            VectorLayer layRivers = new SharpMap.Layers.VectorLayer("Rivers");

            //Set the datasource to a shapefile in the App_data folder
            layRivers.DataSource = new SharpMap.Data.Providers.OracleProvider("system", "metsys", "127.0.0.1", "RIVERS", "GEOM", "ID");
            //Define a blue 1px wide pen
            layRivers.Style.Line = new Pen(Color.Blue, 1);

            //Set up a river layer
            VectorLayer layCities = new VectorLayer("Cities");

            //Set the datasource to a shapefile in the App_data folder
            layCities.DataSource        = new SharpMap.Data.Providers.OracleProvider("system", "metsys", "127.0.0.1", "CITIES", "GEOM", "ID");
            layCities.Style.SymbolScale = 0.8f;
            layCities.MaxVisible        = 40;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Country labels")
            {
                DataSource  = layCountries.DataSource,
                Enabled     = true,
                LabelColumn = "NAME",
                MaxVisible  = 90,
                MinVisible  = 30,
                MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest,
                LabelFilter    = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection,
                PriorityColumn = "POPDENS",
                Style          = new LabelStyle()
                {
                    ForeColor           = Color.White,
                    Font                = new Font(FontFamily.GenericSerif, 12),
                    BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0)),
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                    CollisionDetection  = true
                }
            };

            ////Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels")
            {
                DataSource       = layCities.DataSource,
                Enabled          = true,
                LabelColumn      = "NAME",
                PriorityColumn   = "POPULATION",
                PriorityDelegate = delegate(GeoAPI.Features.IFeature fdr)
                {
                    Int32 retVal = 10000000 * ((String)fdr.Attributes["capital"] == "Y" ? 1 : 0);
                    return(retVal + Convert.ToInt32(fdr.Attributes["population"]));
                },
                TextRenderingHint = TextRendering.AntiAlias,
                SmoothingMode     = Smoothing.AntiAlias,
                LabelFilter       = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection,
                Style             = new LabelStyle()
                {
                    ForeColor           = Color.Black,
                    Font                = new Font(FontFamily.GenericSerif, 11),
                    MaxVisible          = layLabel.MinVisible,
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                    VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom,
                    Offset              = new PointF(3, 3),
                    Halo                = new Pen(Color.Yellow, 2),
                    CollisionDetection  = true
                }
            };

            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            map.Layers.Add(layCountries);
            map.Layers.Add(layRivers);
            map.Layers.Add(layCities);
            map.Layers.Add(layLabel);
            map.Layers.Add(layCityLabel);

            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.ZoomToExtents(); // = 360;

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
        public static Canvas Render(IViewport viewport, LabelLayer layer)
        {
            // todo: Move stack functionality to Mapsui core.
            // step 1) Split RenderStackedLabelLayer into a method
            // GetFeaturesInViewStacked en a RenderStackedLabel
            // which can later be replace by normal label rendering.
            // The method GetFeaturesInViewStacked
            // returns a style with an offset determined by the stackoffset
            // and a position determined by CenterX en Cluster.Box.Bottom.
            // step 2) Move GetFeaturesInViewStacked to a GetFeaturesInView
            // method of a new StackedLabelLayed.

            var canvas = new Canvas {
                Opacity = layer.Opacity
            };

            // todo: take into account the priority
            var features = layer.GetFeaturesInView(viewport.Extent, viewport.Resolution).ToArray();
            var margin   = viewport.Resolution * 50;

            const int symbolSize = 32; // todo: determine margin by symbol size
            const int boxMargin  = symbolSize / 2;

            var clusters = new List <Cluster>();

            //todo: repeat until there are no more merges
            ClusterFeatures(clusters, features, margin, layer.Style, viewport.Resolution);
            const int textHeight = 18;

            foreach (var cluster in clusters)
            {
                var stackOffsetY = double.NaN;

                var orderedFeatures = cluster.Features.OrderBy(f => f.Geometry.GetBoundingBox().GetCentroid().Y);

                if (cluster.Features.Count > 1)
                {
                    canvas.Children.Add(RenderBox(cluster.Box, viewport));
                }

                foreach (var feature in orderedFeatures)
                {
                    if (double.IsNaN(stackOffsetY)) // first time
                    {
                        stackOffsetY = textHeight * 0.5 + boxMargin;
                    }
                    else
                    {
                        stackOffsetY += textHeight; //todo: get size from text (or just pass stack nr)
                    }
                    LabelStyle style;
                    if (layer.Style is IThemeStyle)
                    {
                        style = (LabelStyle)((IThemeStyle)layer.Style).GetStyle(feature);
                    }
                    else
                    {
                        style = (LabelStyle)layer.Style;
                    }

                    var labelStyle = new LabelStyle(style)
                    {
                        Text = layer.GetLabelText(feature)
                               //we only use the layer for the text, this should be returned by style
                    };
                    labelStyle.Offset.Y += stackOffsetY;

                    // Since the box can be rotated, find the minimal Y value of all 4 corners
                    var rotatedBox = cluster.Box.Rotate(-viewport.Rotation);
                    var minY       = rotatedBox.Vertices.Select(v => v.Y).Min();
                    var position   = new Point(cluster.Box.GetCentroid().X, minY);

                    var labelText = labelStyle.GetLabelText(feature);
                    canvas.Children.Add(SingleLabelRenderer.RenderLabel(position, labelStyle, viewport, labelText));
                }
            }
            return(canvas);
        }
Exemple #8
0
        /// <summary>
        /// 加载指定的Layer至mapImage
        /// 注:不刷新地图
        /// 标准图层:
        ///     名称:TableOrShapeFile
        ///     标题:LayerName
        /// 分类图层:
        ///     名称:TableOrShapeFile + splitKey + ColumnName + splitKey + MaybeValue
        ///     标题:Text
        /// </summary>
        /// <param name="layerName">图层名</param>
        /// <param name="mapImage">欲加载到的控件</param>
        public static void AddLayer(string layerName, MapImage mapImage, float LabelOffset_X, float LabelOffset_Y)
        {
            try
            {
                string[]  strArray   = Regex.Split(layerName, Global.SplitKey);
                DataRow[] rows_layer = DB_Service.MainDataSet.Tables["LayerTable"].Select("TableOrShapeFile = '" + strArray[0] + "'");
                //图层
                VectorLayer layer;
                //图层样式
                VectorStyle style = new VectorStyle();
                //数据源类型
                int DataSourceType = Convert.ToInt32(rows_layer[0]["DataSourceType"]);
                //显示次序
                int viewOrder = Convert.ToInt32(rows_layer[0]["ViewOrder"]);
                //图层点样式
                string PointImageID = "";
                switch (strArray.Length)
                {
                case 1:
                    if (DataSourceType == 0 || DataSourceType == 1)
                    {
                        PointImageID = rows_layer[0]["PointImage"].ToString();
                    }
                    break;

                case 3:
                    DataRow[] roww = DB_Service.MainDataSet.Tables["LayerSortTable"].Select("TableOrShapeFile = '" + strArray[0] + "' and ColumnName = '" + strArray[1] + "' and MaybeValue = '" + strArray[2] + "'");
                    PointImageID = roww[0]["PointImage"].ToString();
                    break;
                }
                //图层线、面样式
                style.Line.Color = Color.FromArgb(Convert.ToInt32(rows_layer[0]["Line_Color"].ToString().Split(',')[0]), Convert.ToInt32(rows_layer[0]["Line_Color"].ToString().Split(',')[1]), Convert.ToInt32(rows_layer[0]["Line_Color"].ToString().Split(',')[2]), Convert.ToInt32(rows_layer[0]["Line_Color"].ToString().Split(',')[3]));
                style.Line.Width = Convert.ToInt32(rows_layer[0]["Line_Width"]);
                if (Convert.ToBoolean(rows_layer[0]["Fill_IsSolid"]))
                {
                    style.Fill = new SolidBrush(Color.FromArgb(Convert.ToInt32(rows_layer[0]["Fill_Color"].ToString().Split(',')[0]), Convert.ToInt32(rows_layer[0]["Fill_Color"].ToString().Split(',')[1]), Convert.ToInt32(rows_layer[0]["Fill_Color"].ToString().Split(',')[2]), Convert.ToInt32(rows_layer[0]["Fill_Color"].ToString().Split(',')[3])));
                }
                else
                {
                    style.Fill = new TextureBrush(Resource_Service.GetImage(rows_layer[0]["Fill_Image"].ToString()));
                }
                if (Convert.ToBoolean(rows_layer[0]["FillLine_Enable"]))
                {
                    style.EnableOutline = true;
                    style.Outline.Color = Color.FromArgb(Convert.ToInt32(rows_layer[0]["FillLine_Color"].ToString().Split(',')[0]), Convert.ToInt32(rows_layer[0]["FillLine_Color"].ToString().Split(',')[1]), Convert.ToInt32(rows_layer[0]["FillLine_Color"].ToString().Split(',')[2]), Convert.ToInt32(rows_layer[0]["FillLine_Color"].ToString().Split(',')[3]));
                    style.Outline.Width = Convert.ToInt32(rows_layer[0]["FillLine_Width"]);
                }
                else
                {
                    style.EnableOutline = false;
                }
                //加载数据源
                if (DataSourceType == 0 || DataSourceType == 1)
                {
                    //数据库数据源
                    layer = new VectorLayer(layerName, viewOrder, new GeometryFeatureProvider(new FeatureDataTable(DB_Service.GetDataTableByLayerName(layerName))));
                    //设置图层样式
                    if (PointImageID != "")
                    {
                        style.Symbol = (System.Drawing.Bitmap)Resource_Service.GetImage(PointImageID);
                    }
                }
                else
                {
                    //文件数据源
                    string file = Global.MapPath + strArray[0];
                    if (File.Exists(file))
                    {
                        ShapeFile shpfile = new ShapeFile(file, true);
                        shpfile.Encoding = System.Text.Encoding.GetEncoding("gb2312");
                        layer            = new VectorLayer(layerName, viewOrder, shpfile);
                    }
                    else
                    {
                        MessageBox.Show("加载图层失败。\n\n没有找到 " + file + " 的图层文件!", "装载图层");
                        return;
                    }
                }
                //启用图层样式
                style.Enabled = true;
                layer.Style   = style;
                //标注图层
                LabelLayer labellayer = new LabelLayer("LL" + layerName);
                labellayer.Enabled      = true;
                labellayer.Style.Offset = new PointF(LabelOffset_X, LabelOffset_Y);
                if (rows_layer[0]["LabelLayerColName"].ToString() != "")
                {
                    labellayer.LabelColumn = rows_layer[0]["LabelLayerColName"].ToString();
                }
                else
                {
                    labellayer.LabelColumn = "Name";
                }
                if (rows_layer[0]["LabelLayerMinShow"] != DBNull.Value)
                {
                    labellayer.MinVisible = Convert.ToDouble(rows_layer[0]["LabelLayerMinShow"]);
                }
                else
                {
                    labellayer.MinVisible = 0;
                }
                if (rows_layer[0]["LabelLayerMaxShow"] != DBNull.Value)
                {
                    labellayer.MaxVisible = Convert.ToDouble(rows_layer[0]["LabelLayerMaxShow"]);
                }
                else
                {
                    labellayer.MaxVisible = 9999999;
                }

                labellayer.DataSource = layer.DataSource;

                //根据不同的图层,设置不同的标注图层风格
                switch (strArray[0])
                {
                case "StationTable":
                    labellayer.Style.ForeColor = Global.StationNameColor;
                    labellayer.Style.Font      = new Font("黑体", 15, FontStyle.Underline);
                    break;

                case "PositionTable":
                    //labellayer.Style.ForeColor = Global.PersonNameColor;
                    labellayer.Style.ForeColor = Color.DodgerBlue;     //Color.Black;

                    labellayer.Style.Font = new Font("黑体", 15, FontStyle.Underline);
                    break;

                case "MapTextTable":
                    //labellayer.Style.ForeColor = Color.Blue;
                    labellayer.Style.ForeColor = Color.Black;
                    labellayer.Style.Font      = new Font("黑体", 13, FontStyle.Regular);
                    break;

                default:
                    labellayer.Style.ForeColor = Color.Black;
                    labellayer.Style.Font      = new Font("黑体", 13, FontStyle.Regular);
                    break;
                }

                if (mapImage.Map.Layers.Count == 0)
                {
                    //如果没有最后一个图层,则直接添加
                    mapImage.Map.Layers.Add(layer);
                    mapImage.Map.Layers.Add(labellayer);
                }
                else
                {
                    if (mapImage.Map.Layers[mapImage.Map.Layers.Count - 2].ViewOrder < viewOrder)
                    {
                        //最后一个图层的ViewOrder小于将添加的图层:直接添加
                        mapImage.Map.Layers.Add(layer);
                        mapImage.Map.Layers.Add(labellayer);
                    }
                    else
                    {
                        //最后一个图层的ViewOrder大于或者等于要添加的图层:循环判断找出位置插入
                        for (int i = 0; i < mapImage.Map.Layers.Count; i = i + 2)
                        {
                            if (mapImage.Map.Layers[i].ViewOrder >= viewOrder)
                            {
                                mapImage.Map.Layers.Insert(i, layer);
                                mapImage.Map.Layers.Insert(i + 1, labellayer);
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("图层 " + layerName + " 加载失败!\n\n" + ex.Message, "装载图层", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Exemple #9
0
    public static Map InitializeMapPostGis(Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

        string connectionString = ConfigurationManager.ConnectionStrings["postgis"].ConnectionString;

        //Initialize a new map of size 'imagesize'
        Map map = new Map(size);

        //Set up the countries layer
        VectorLayer layCountries = new VectorLayer("Countries");

        //Set the datasource to a new MsSqlSpatialProvider
        layCountries.DataSource = new PostGIS(connectionString, "countries", "wkb_geometry", "ogc_fid");

        //Set fill-style to green
        layCountries.Style.Fill = new SolidBrush(Color.Green);
        //Set the polygons to have a black outline
        layCountries.Style.Outline       = Pens.Black;
        layCountries.Style.EnableOutline = true;

        //Set up a river layer
        VectorLayer layRivers = new VectorLayer("Rivers");

        //Set the datasource to a new MsSqlSpatialProvider
        layRivers.DataSource = new PostGIS(connectionString, "rivers", "wkb_geometry", "ogc_fid");
        //Define a blue 1px wide pen
        layRivers.Style.Line = new Pen(Color.Blue, 1);

        //Set up a river layer
        VectorLayer layCities = new VectorLayer("Cities");

        //Set the datasource to a new MsSqlSpatialProvider
        layCities.DataSource = new PostGIS(connectionString, "cities", "wkb_geometry", "ogc_fid");;
        //Define a blue 1px wide pen
        //layCities.Style.Symbol = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
        layCities.Style.SymbolScale = 0.8f;
        layCities.MaxVisible        = 40;

        //Set up a country label layer
        LabelLayer layLabel = new LabelLayer("Country labels");

        layLabel.DataSource  = layCountries.DataSource;
        layLabel.Enabled     = true;
        layLabel.LabelColumn = "Name";
        layLabel.MaxVisible  = 90;
        layLabel.MinVisible  = 30;
        layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;
        layLabel.LabelFilter               = LabelCollisionDetection.ThoroughCollisionDetection;
        layLabel.PriorityColumn            = "popdens";
        layLabel.Style                     = new LabelStyle();
        layLabel.Style.ForeColor           = Color.White;
        layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
        layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
        layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
        layLabel.Style.CollisionDetection  = true;

        //Set up a city label layer
        LabelLayer layCityLabel = new LabelLayer("City labels");

        layCityLabel.DataSource       = layCities.DataSource;
        layCityLabel.Enabled          = true;
        layCityLabel.LabelColumn      = "name";
        layCityLabel.PriorityColumn   = "population";
        layCityLabel.PriorityDelegate = delegate(IFeature fdr)
        {
            Int32 retVal = 10000000 * (Int32)((String)fdr.Attributes["capital"] == "Y" ? 1 : 0);
            return(retVal + Convert.ToInt32(fdr.Attributes["population"]));
        };
        layCityLabel.TextRenderingHint         = TextRendering.AntiAlias;
        layCityLabel.SmoothingMode             = Smoothing.AntiAlias;
        layCityLabel.LabelFilter               = LabelCollisionDetection.ThoroughCollisionDetection;
        layCityLabel.Style                     = new LabelStyle();
        layCityLabel.Style.ForeColor           = Color.Black;
        layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
        layCityLabel.Style.MaxVisible          = layLabel.MinVisible;
        layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
        layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
        layCityLabel.Style.Offset              = new PointF(3, 3);
        layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
        layCityLabel.Style.CollisionDetection  = true;


        //Add the layers to the map object.
        //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
        map.Layers.Add(layCountries);
        map.Layers.Add(layRivers);
        map.Layers.Add(layCities);
        map.Layers.Add(layLabel);
        map.Layers.Add(layCityLabel);


        //limit the zoom to 360 degrees width
        map.MaximumZoom = 360;
        map.BackColor   = Color.LightBlue;

        map.Zoom   = 360;
        map.Center = new Point(0, 0);

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
Exemple #10
0
        /// <summary>
        /// Add a list of vector layers to the map.
        /// </summary>
        /// <param name="vectorLayers"></param>
        public void AddVectorLayers(List <FeatureInfo> vectorLayers)
        {
            int counter = 0;

            if (vectorLayers == null)
            {
                return;
            }
            vectorLayers.ForEach(layer => {
                VectorLayer vectorLayer     = new VectorLayer("VectorLayer-" + counter);
                GeometryFactory factory     = new GeometryFactory();
                List <IGeometry> geometries = new List <IGeometry>();

                FeatureDataTable featureData = new FeatureDataTable();
                featureData.Columns.Add("text", typeof(String));
                featureData.Columns.Add("style", typeof(MapExport.Style));

                layer.features.ForEach(feature =>
                {
                    FeatureDataRow dataRow = featureData.NewRow();
                    dataRow["text"]        = feature.attributes.text;
                    dataRow["style"]       = feature.attributes.style;

                    List <GeoAPI.Geometries.Coordinate> vertices = new List <GeoAPI.Geometries.Coordinate>();

                    feature.coordinates.ForEach(coordinate =>
                    {
                        double x = coordinate[0];
                        double y = coordinate[1];
                        vertices.Add((new GeoAPI.Geometries.Coordinate(x, y)));
                    });

                    bool created = false;

                    switch (feature.type)
                    {
                    case "Text":
                    case "Point":
                    case "MultiPoint":
                        if (vertices.Count > 0)
                        {
                            var point        = factory.CreatePoint(new GeoAPI.Geometries.Coordinate(vertices[0]));
                            dataRow.Geometry = point;
                        }
                        created = true;
                        break;

                    case "LineString":
                    case "MultiLineString":
                        var lineString   = factory.CreateLineString(vertices.ToArray());
                        dataRow.Geometry = lineString;
                        created          = true;
                        break;

                    case "Polygon":
                    case "MultiPolygon":
                        var polygon      = factory.CreatePolygon(vertices.ToArray());
                        dataRow.Geometry = polygon;
                        created          = true;
                        break;

                    case "Circle":
                        var circle       = factory.CreatePoint(new GeoAPI.Geometries.Coordinate(vertices[0]));
                        dataRow.Geometry = circle.Buffer(vertices[1][0]);
                        created          = true;
                        break;
                    }
                    if (created)
                    {
                        featureData.AddRow(dataRow);
                    }
                });

                vectorLayer.DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(featureData);
                vectorLayer.Theme      = new CustomTheme(GetFeatureStyle);

                map.Layers.Add(vectorLayer);

                LabelLayer labels = new LabelLayer("Labels");

                labels.DataSource        = vectorLayer.DataSource;
                labels.Enabled           = true;
                labels.LabelColumn       = "text";
                labels.Theme             = new CustomTheme(GetLabelStyle);
                labels.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                labels.SmoothingMode     = SmoothingMode.HighQuality;
                labels.SRID = vectorLayer.SRID;

                map.Layers.Add(labels);
                counter++;
            });
        }
Exemple #11
0
        private void Form2_Load(object sender, EventArgs e)
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form2));


            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.ZoomWindowToolStripButton = new System.Windows.Forms.ToolStripButton();
            this.ZoomInToolStripButton     = new System.Windows.Forms.ToolStripButton();
            this.ZoomOutToolStripButton    = new System.Windows.Forms.ToolStripButton();
            this.PanToolStripButton        = new System.Windows.Forms.ToolStripButton();
            this.PreviousToolStripButton   = new System.Windows.Forms.ToolStripButton();
            this.NextToolStripButton       = new System.Windows.Forms.ToolStripButton();
            this.QueryToolStripButton      = new System.Windows.Forms.ToolStripButton();
            this.toolStrip1.SuspendLayout();

            //
            // toolStrip1
            //
            this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                this.ZoomWindowToolStripButton,
                this.ZoomInToolStripButton,
                this.ZoomOutToolStripButton,
                this.PanToolStripButton,
                this.PreviousToolStripButton,
                this.NextToolStripButton,
                this.QueryToolStripButton
            });
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name     = "toolStrip1";
            this.toolStrip1.Size     = new System.Drawing.Size(735, 31);
            this.toolStrip1.TabIndex = 1;
            this.toolStrip1.Text     = "toolStrip1";
            //
            // toolStripButton1
            //
            this.ZoomWindowToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.ZoomWindowToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("globe")));
            this.ZoomWindowToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.ZoomWindowToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.ZoomWindowToolStripButton.Name   = "toolStripButton1";
            this.ZoomWindowToolStripButton.Size   = new System.Drawing.Size(28, 28);
            this.ZoomWindowToolStripButton.Text   = "全图";
            this.ZoomWindowToolStripButton.Click += new EventHandler(ZoomWindowToolStripButton_Click);
            //
            // toolStripButton2
            //
            this.ZoomInToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.ZoomInToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("zoomin")));
            this.ZoomInToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.ZoomInToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.ZoomInToolStripButton.Name   = "toolStripButton2";
            this.ZoomInToolStripButton.Size   = new System.Drawing.Size(26, 28);
            this.ZoomInToolStripButton.Text   = "放大";
            this.ZoomInToolStripButton.Click += new EventHandler(ZoomInToolStripButton_Click);

            //
            // toolStripButton3
            //
            this.ZoomOutToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.ZoomOutToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("zoomout")));
            this.ZoomOutToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.ZoomOutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.ZoomOutToolStripButton.Name   = "toolStripButton3";
            this.ZoomOutToolStripButton.Size   = new System.Drawing.Size(26, 28);
            this.ZoomOutToolStripButton.Text   = "缩小";
            this.ZoomOutToolStripButton.Click += new EventHandler(ZoomOutToolStripButton_Click);
            //
            // toolStripButton4
            //
            this.PanToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.PanToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("hand")));
            this.PanToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.PanToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.PanToolStripButton.Name   = "toolStripButton4";
            this.PanToolStripButton.Size   = new System.Drawing.Size(28, 28);
            this.PanToolStripButton.Text   = "平移";
            this.PanToolStripButton.Click += new EventHandler(PanToolStripButton_Click);
            //
            // toolStripButton6
            //
            this.PreviousToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.PreviousToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("previous")));
            this.PreviousToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.PreviousToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.PreviousToolStripButton.Name   = "toolStripButton6";
            this.PreviousToolStripButton.Size   = new System.Drawing.Size(28, 28);
            this.PreviousToolStripButton.Text   = "前一视图";
            this.PreviousToolStripButton.Click += new EventHandler(PreviousToolStripButton_Click);
            //
            // toolStripButton7
            //
            this.NextToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.NextToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("next")));
            this.NextToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.NextToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.NextToolStripButton.Name   = "toolStripButton7";
            this.NextToolStripButton.Size   = new System.Drawing.Size(28, 28);
            this.NextToolStripButton.Text   = "后一视图";
            this.NextToolStripButton.Click += new EventHandler(NextToolStripButton_Click);
            //
            // toolStripButton8
            //
            this.QueryToolStripButton.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.QueryToolStripButton.Image                 = ((System.Drawing.Image)(resources.GetObject("identify")));
            this.QueryToolStripButton.ImageScaling          = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.QueryToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.QueryToolStripButton.Name   = "toolStripButton8";
            this.QueryToolStripButton.Size   = new System.Drawing.Size(28, 28);
            this.QueryToolStripButton.Text   = "查询";
            this.QueryToolStripButton.Click += new EventHandler(QueryToolStripButton_Click);
            this.Controls.Add(this.toolStrip1);

            //
            // button2
            //
            this.button2          = new System.Windows.Forms.Button();
            this.button2.Location = new System.Drawing.Point(158, 99);
            this.button2.Name     = "button2";
            this.button2.Size     = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 0;
            this.button2.Text     = "button2";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new EventHandler(button2_Click);
            this.Controls.Add(this.button2);


            //
            // mapBox1
            //
            this.mapBox1                      = new SharpMap.Forms.MapBox();
            this.mapBox1.ActiveTool           = SharpMap.Forms.MapBox.Tools.None;
            this.mapBox1.BackColor            = System.Drawing.Color.White;
            this.mapBox1.Cursor               = System.Windows.Forms.Cursors.Default;
            this.mapBox1.Dock                 = System.Windows.Forms.DockStyle.Fill;
            this.mapBox1.FineZoomFactor       = 10D;
            this.mapBox1.Location             = new System.Drawing.Point(0, 78);
            this.mapBox1.MapQueryMode         = SharpMap.Forms.MapBox.MapQueryType.LayerByIndex;
            this.mapBox1.Name                 = "mapBox1";
            this.mapBox1.QueryGrowFactor      = 5F;
            this.mapBox1.QueryLayerIndex      = 0;
            this.mapBox1.SelectionBackColor   = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
            this.mapBox1.SelectionForeColor   = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
            this.mapBox1.ShowProgressUpdate   = false;
            this.mapBox1.Size                 = new System.Drawing.Size(527, 317);
            this.mapBox1.TabIndex             = 0;
            this.mapBox1.Text                 = "mapBox1";
            this.mapBox1.WheelZoomMagnitude   = -2D;
            this.mapBox1.MapQueried          += new SharpMap.Forms.MapBox.MapQueryHandler(mapBox1_MapQueried);
            this.mapBox1.Map.MapViewOnChange += new SharpMap.Map.MapViewChangedHandler(Map_MapViewOnChange);
            this.mapBox1.MouseDown           += new MapBox.MouseEventHandler(mapBox1_MouseDown);
            this.mapBox1.MouseUp             += new MapBox.MouseEventHandler(mapBox1_MouseUp);
            this.Controls.Add(this.mapBox1);

            this.toolStrip1.ResumeLayout(false);
            this.toolStrip1.PerformLayout();

            this.mapBox1.Map.Layers.Clear();

            SharpMap.Layers.VectorLayer vlayer = new SharpMap.Layers.VectorLayer("states");
            string start = Application.StartupPath;
            string path  = @"E:\workspace\Code\2016\ExcelReader\ExcelReader\bin\Debug\tmp.shp";

            vlayer.DataSource          = new SharpMap.Data.Providers.ShapeFile(path);
            vlayer.Style.Fill          = new SolidBrush(Color.GreenYellow);
            vlayer.Style.Outline       = System.Drawing.Pens.Gray;
            vlayer.Style.EnableOutline = true;
            mapBox1.Map.Layers.Add(vlayer);


            SharpMap.Layers.LabelLayer labelLayer = new LabelLayer("label");
            labelLayer.DataSource               = vlayer.DataSource;
            labelLayer.Enabled                  = true;
            labelLayer.LabelColumn              = "mapNo";
            labelLayer.Style                    = new SharpMap.Styles.LabelStyle();
            labelLayer.Style.ForeColor          = Color.Black;
            labelLayer.Style.Font               = new System.Drawing.Font(FontFamily.GenericSerif, 13);
            labelLayer.Style.Offset             = new PointF(3, 3);
            labelLayer.Style.Halo               = new Pen(Color.Yellow, 2);
            labelLayer.TextRenderingHint        = System.Drawing.Text.TextRenderingHint.AntiAlias;
            labelLayer.SmoothingMode            = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            labelLayer.LabelFilter              = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
            labelLayer.Style.CollisionDetection = true;
            labelLayer.MaxVisible               = 200000;
            mapBox1.Map.Layers.Add(labelLayer);


            mapBox1.Map.ZoomToExtents();
            mapBox1.Refresh();
        }
Exemple #12
0
        private static Map InitializeMapOsmWithXls(float angle)
        {
            Map map = new Map();

            TileAsyncLayer tileLayer = new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM with XLS");

            map.BackgroundLayer.Add(tileLayer);

            //Get data from excel
            string  xlsPath = string.Format(XlsConnectionString, Directory.GetCurrentDirectory(), "GeoData\\Cities.xls");
            DataSet ds      = new DataSet("XLS");

            using (OleDbConnection cn = new OleDbConnection(xlsPath))
            {
                cn.Open();
                using (OleDbDataAdapter da = new OleDbDataAdapter(new OleDbCommand("SELECT * FROM [Cities$]", cn)))
                    da.Fill(ds);
            }

#if !DotSpatialProjections
            //The SRS for this datasource is EPSG:4326, therefore we need to transfrom it to OSM projection
            CoordinateTransformationFactory ctf = new CoordinateTransformationFactory();
            CoordinateSystemFactory         cf  = new CoordinateSystemFactory();
            ICoordinateSystem         epsg4326  = cf.CreateFromWkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]");
            ICoordinateSystem         epsg3857  = cf.CreateFromWkt("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3857\"]]");
            ICoordinateTransformation ct        = ctf.CreateFromCoordinateSystems(epsg4326, epsg3857);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value)
                {
                    continue;
                }
                double[] coords = new[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"]) };
                coords   = ct.MathTransform.Transform(coords);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }
#else
            var epsg4326 = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            var epsg3857 = DotSpatial.Projections.ProjectionInfo.FromEsriString("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3857\"]]");
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value)
                {
                    continue;
                }
                var coords = new[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"]) };
                DotSpatial.Projections.Reproject.ReprojectPoints(coords, null, epsg4326, epsg3857, 0, 1);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }
#endif
            //Add Rotation Column
            ds.Tables[0].Columns.Add("Rotation", typeof(float));
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                row["Rotation"] = -angle;
            }

            //Set up provider
            DataTablePoint xlsProvider = new DataTablePoint(ds.Tables[0], "OID", "X", "Y");
            VectorLayer    xlsLayer    = new VectorLayer("XLS", xlsProvider)
            {
                Style = { Symbol = VectorStyle.DefaultSymbol }
            };

            //Add layer to map
            map.Layers.Add(xlsLayer);
            LabelLayer xlsLabelLayer = new LabelLayer("XLSLabel")
            {
                DataSource     = xlsProvider,
                LabelColumn    = "Name",
                PriorityColumn = "Population",
                Style          =
                {
                    CollisionBuffer    = new SizeF(2f, 2f),
                    CollisionDetection = true
                },
                LabelFilter =
                    LabelCollisionDetection.ThoroughCollisionDetection
            };
            map.Layers.Add(xlsLabelLayer);

            map.ZoomToBox(tileLayer.Envelope);

            return(map);
        }
        public FtPuntualVectorLayer(FtMap ftMap, FtTransmitterDataset dataset)
        {
            _ftMap = ftMap;

            IProvider dataSource = null;
            var       symbolizer = dataset.Visulization.Symbolizer;

            var pointSymbolizer = symbolizer as IPointSymbolizer;

            if (pointSymbolizer != null)
            {
                dataSource      = dataset.GPSData.AsDataTablePoint();
                SymbolizerLayer = new VectorLayer(dataset.TagId.ToString(), dataSource)
                {
                    Style = { PointSymbolizer = pointSymbolizer }
                };

                pointSymbolizer.Size = new Size(Properties.Settings.Default.VisualizerMarkersize,
                                                Properties.Settings.Default.VisualizerMarkersize);
            }

            var lineSymbolizer = symbolizer as FtBasicLineSymbolizer;

            if (lineSymbolizer != null)
            {
                dataSource      = dataset.GPSData.AsDataTableLine();
                SymbolizerLayer = new VectorLayer(dataset.TagId.ToString(), dataSource)
                {
                    Style = { LineSymbolizer = lineSymbolizer }
                };

                lineSymbolizer.Size = new Size(Properties.Settings.Default.VisualizerMarkersize,
                                               Properties.Settings.Default.VisualizerMarkersize);
            }

            SymbolizerLayer.SmoothingMode = SmoothingMode.HighQuality;
            symbolizer.SmoothingMode      = SmoothingMode.HighQuality;

            if (dataSource?.GetFeatureCount() > 500)
            {
                SymbolizerLayer.SmoothingMode = SmoothingMode.HighSpeed;
                symbolizer.SmoothingMode      = SmoothingMode.HighSpeed;
            }

            if ((symbolizer as IFtBaseSymbolizer).Labeled)
            {
                LabelLayer = new LabelLayer($"Label{dataset.TagId}")
                {
                    DataSource            = dataset.GPSData.AsDataTablePoint(),
                    LabelColumn           = "num",
                    LabelPositionDelegate = LabelPositionDelegate,
                    SmoothingMode         = SmoothingMode.HighSpeed,
                    Style = { Font = MapFont, VerticalAlignment = LabelStyle.VerticalAlignmentEnum.Top, HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left, CollisionDetection = false, ForeColor = dataset.Visulization.Color }
                };
            }
            if (LabelLayer != null)
            {
                this.Add(LabelLayer);
            }
            this.Add(SymbolizerLayer);
        }
        void SetupMap()
        {
            FactLocations = new FeatureDataTable();
            FactLocations.Columns.Add("MapLocation", typeof(MapLocation));
            FactLocations.Columns.Add("ViewPort", typeof(Envelope));
            FactLocations.Columns.Add("Label", typeof(string));

            clusterer = new MarkerClusterer(FactLocations);
            GeometryFeatureProvider factLocationGFP = new GeometryFeatureProvider(clusterer.FeatureDataTable);

            clusterLayer = new VectorLayer("Clusters")
            {
                DataSource = factLocationGFP
            };

            Dictionary <string, IStyle> styles = new Dictionary <string, IStyle>();

            VectorStyle feature = new VectorStyle
            {
                PointColor   = new SolidBrush(Color.Red),
                PointSize    = 20,
                Symbol       = Image.FromFile(Path.Combine(Application.StartupPath, @"Resources\Icons\teardrop_blue.png")),
                SymbolOffset = new PointF(0.0f, -17.0f)
            };

            styles.Add(MapCluster.FEATURE, feature);

            VectorStyle cluster = new VectorStyle
            {
                PointColor = new SolidBrush(Color.ForestGreen),
                PointSize  = 20,
                Symbol     = Image.FromFile(Path.Combine(Application.StartupPath, @"Resources\Icons\people35.png"))
            };

            styles.Add(MapCluster.CLUSTER, cluster);

            VectorStyle unknown = new VectorStyle
            {
                PointColor = new SolidBrush(Color.Black),
                PointSize  = 10
            };

            styles.Add(MapCluster.UNKNOWN, unknown);

            clusterLayer.Theme = new SharpMap.Rendering.Thematics.UniqueValuesTheme <string>("Cluster", styles, unknown);
            map.Layers.Add(clusterLayer);

            labelLayer = new LabelLayer("Label")
            {
                DataSource = factLocationGFP,
                Enabled    = true,
                //Specifiy field that contains the label string.
                LabelColumn       = "Label",
                TextRenderingHint = TextRenderingHint.AntiAlias,
                SmoothingMode     = SmoothingMode.AntiAlias
            };
            LabelStyle style = new LabelStyle
            {
                ForeColor           = Color.Black,
                Font                = new Font(FontFamily.GenericSerif, 14, FontStyle.Bold),
                HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom,
                CollisionDetection  = true,
                Offset              = new PointF(0, 17),
                Halo                = new Pen(Color.Yellow, 3)
            };

            labelLayer.Style = style;
            map.Layers.Add(labelLayer);
        }
Exemple #15
0
 public static Canvas Render(IViewport viewport, LabelLayer layer)
 {
     throw new NotImplementedException();
 }
Exemple #16
0
    public static Map InitializeMapMsSqlSpatial(Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

        string connectionString = ConfigurationManager.ConnectionStrings["mssqlspatial"].ConnectionString;

        //Initialize a new map of size 'imagesize'
        Map map = new Map(size);

        if (connectionString.Contains("server=XXXXXXXXXXX"))
        {
            throw new ArgumentException("You need to adjust the connectionstring to MsSqlSpatial Server");
        }

        //Set up the countries layer
        VectorLayer layCountries = new VectorLayer("Countries");

        //Set the datasource to a new MsSqlSpatialProvider
        layCountries.DataSource = new MsSqlSpatial(connectionString, "Countries", "Geometry", "oid");

        //Set fill-style to green
        layCountries.Style.Fill = new SolidBrush(Color.Green);
        //Set the polygons to have a black outline
        layCountries.Style.Outline       = Pens.Black;
        layCountries.Style.EnableOutline = true;
        layCountries.SRID = 4326;

        //Set up a river layer
        VectorLayer layRivers = new VectorLayer("Rivers");

        //Set the datasource to a new MsSqlSpatialProvider
        layRivers.DataSource = new MsSqlSpatial(connectionString, "Rivers", "Geometry", "oid");
        //Define a blue 1px wide pen
        layRivers.Style.Line = new Pen(Color.Blue, 1);
        layRivers.SRID       = 4326;

        //Set up a river layer
        VectorLayer layCities = new VectorLayer("Cities");

        //Set the datasource to a new MsSqlSpatialProvider
        layCities.DataSource = new MsSqlSpatial(connectionString, "Cities", "Geometry", "oid");
        ;
        //Define a blue 1px wide pen
        //layCities.Style.Symbol = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
        layCities.Style.SymbolScale = 0.8f;
        layCities.MaxVisible        = 40;
        layCities.SRID = 4326;

        //Set up a country label layer
        LabelLayer layLabel = new LabelLayer("Country labels");

        layLabel.DataSource                = layCountries.DataSource;
        layLabel.Enabled                   = true;
        layLabel.LabelColumn               = "Name";
        layLabel.Style                     = new LabelStyle();
        layLabel.Style.ForeColor           = Color.White;
        layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
        layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
        layLabel.MaxVisible                = 90;
        layLabel.MinVisible                = 30;
        layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
        layLabel.SRID = 4326;
        layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;

        //Set up a city label layer
        LabelLayer layCityLabel = new LabelLayer("City labels");

        layCityLabel.DataSource                = layCities.DataSource;
        layCityLabel.Enabled                   = true;
        layCityLabel.LabelColumn               = "Name";
        layCityLabel.Style                     = new LabelStyle();
        layCityLabel.Style.ForeColor           = Color.Black;
        layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
        layCityLabel.MaxVisible                = layLabel.MinVisible;
        layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
        layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
        layCityLabel.Style.Offset              = new PointF(3, 3);
        layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
        layCityLabel.TextRenderingHint         = TextRenderingHint.AntiAlias;
        layCityLabel.SmoothingMode             = SmoothingMode.AntiAlias;
        layCityLabel.SRID        = 4326;
        layCityLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
        layCityLabel.Style.CollisionDetection = true;

        //Add the layers to the map object.
        //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
        map.Layers.Add(layCountries);
        map.Layers.Add(layRivers);
        map.Layers.Add(layCities);
        map.Layers.Add(layLabel);
        map.Layers.Add(layCityLabel);


        //limit the zoom to 360 degrees width
        map.MaximumZoom = 360;
        map.BackColor   = Color.LightBlue;

        map.Zoom   = 360;
        map.Center = new Point(0, 0);

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
        // Create a LabelLayer and add it into the Group Layer collection with index 0.
        private LabelLayer CreateLabelLayer(Map myMap, MapInfo.Data.Table table, string caption)
        {
            LabelLayer ll = new LabelLayer("Label Layer for bound data", SampleConstants.NewLabelLayerAlias);
            // Insert this LabelLayer into the GroupLayer
            GroupLayer gLyr = GetTheGroupLayer();
            gLyr.Insert(0, ll);

            LabelSource ls = new LabelSource(table);
            ls.DefaultLabelProperties.Caption = caption;
            ll.Sources.Append(ls);
            return ll;
        }
Exemple #18
0
        public static Map InitializeMap(float angle)
        {
            //Initialize a new map based on the simple map
            Map map = new Map();

            //Set up countries layer
            VectorLayer layCountries = new VectorLayer("Countries");

            //Set the datasource to a shapefile in the App_data folder
            layCountries.DataSource = new ShapeFile("GeoData/World/countries.shp", true);
            //Set fill-style to green
            layCountries.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            layCountries.Style.Outline       = Pens.Black;
            layCountries.Style.EnableOutline = true;
            layCountries.SRID = 4326;
            map.Layers.Add(layCountries);

            //set up cities layer
            VectorLayer layCities = new VectorLayer("Cities");

            //Set the datasource to a shapefile in the App_data folder
            layCities.DataSource        = new ShapeFile("GeoData/World/cities.shp", true);
            layCities.Style.SymbolScale = 0.8f;
            layCities.MaxVisible        = 40;
            layCities.SRID = 4326;
            map.Layers.Add(layCities);

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Country labels");

            layLabel.DataSource                = layCountries.DataSource;
            layLabel.Enabled                   = true;
            layLabel.LabelColumn               = "Name";
            layLabel.Style                     = new LabelStyle();
            layLabel.Style.ForeColor           = Color.White;
            layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
            layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
            layLabel.MaxVisible                = 90;
            layLabel.MinVisible                = 30;
            layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
            layLabel.SRID = 4326;
            layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;
            map.Layers.Add(layLabel);

            //Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels");

            layCityLabel.DataSource                = layCities.DataSource;
            layCityLabel.Enabled                   = true;
            layCityLabel.LabelColumn               = "Name";
            layCityLabel.Style                     = new LabelStyle();
            layCityLabel.Style.ForeColor           = Color.Black;
            layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
            layCityLabel.MaxVisible                = layLabel.MinVisible;
            layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
            layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
            layCityLabel.Style.Offset              = new PointF(3, 3);
            layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
            layCityLabel.TextRenderingHint         = TextRendering.AntiAlias;
            layCityLabel.SmoothingMode             = Smoothing.AntiAlias;
            layCityLabel.SRID        = 4326;
            layCityLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
            layCityLabel.Style.CollisionDetection = true;
            map.Layers.Add(layCityLabel);

            //Set a gradient theme on the countries layer, based on Population density
            //First create two styles that specify min and max styles
            //In this case we will just use the default values and override the fill-colors
            //using a colorblender. If different line-widths, line- and fill-colors where used
            //in the min and max styles, these would automatically get linearly interpolated.
            VectorStyle min = new VectorStyle();
            VectorStyle max = new VectorStyle();
            //Create theme using a density from 0 (min) to 400 (max)
            GradientTheme popdens = new GradientTheme("PopDens", 0, 400, min, max);

            //We can make more advanced coloring using the ColorBlend'er.
            //Setting the FillColorBlend will override any fill-style in the min and max fills.
            //In this case we just use the predefined Rainbow colorscale
            popdens.FillColorBlend = ColorBlend.Rainbow5;
            layCountries.Theme     = popdens;

            //Lets scale the labels so that big countries have larger texts as well
            LabelStyle lblMin = new LabelStyle();
            LabelStyle lblMax = new LabelStyle();

            lblMin.ForeColor = Color.Black;
            lblMin.Font      = new Font(FontFamily.GenericSerif, 6);
            lblMax.ForeColor = Color.Blue;
            lblMax.BackColor = new SolidBrush(Color.FromArgb(128, 255, 255, 255));
            lblMin.BackColor = lblMax.BackColor;
            lblMax.Font      = new Font(FontFamily.GenericSerif, 9);
            layLabel.Theme   = new GradientTheme("PopDens", 0, 400, lblMin, lblMax);

            //Lets scale city icons based on city population
            //cities below 1.000.000 gets the smallest symbol, and cities with more than 5.000.000 the largest symbol
            VectorStyle citymin  = new VectorStyle();
            VectorStyle citymax  = new VectorStyle();
            string      iconPath = "Images/icon.png";

            if (!File.Exists(iconPath))
            {
                throw new Exception(
                          String.Format("Error file '{0}' could not be found, make sure it is at the expected location",
                                        iconPath));
            }

            citymin.Symbol      = new Bitmap(iconPath);
            citymin.SymbolScale = 0.5f;
            citymax.Symbol      = new Bitmap(iconPath);
            citymax.SymbolScale = 1f;
            layCities.Theme     = new GradientTheme("Population", 1000000, 5000000, citymin, citymax);

            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.MaximumExtents = new Envelope(-20, 70, -65, 80);
            map.MaximumZoom    = 30;

            map.Zoom   = 20;
            map.Center = new Point(0, 0);

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Exemple #19
0
        private static Map InitializeMapinfo(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layCountries = new VectorLayer("Countries");

            //Set the datasource to a shapefile in the App_data folder
            try
            {
                layCountries.DataSource = new Ogr("GeoData/MapInfo/countriesMapInfo.tab");
            }
            catch (TypeInitializationException ex)
            {
                if (ex.Message == "The type initializer for 'OSGeo.OGR.Ogr' threw an exception.")
                {
                    throw new Exception(
                              String.Format(
                                  "The application threw a PINVOKE exception. You probably need to copy the unmanaged dll's to your bin directory. They are a part of fwtools {0}. You can download it from: http://home.gdal.org/fwtools/",
                                  GdalRasterLayer.FWToolsVersion));
                }
                throw;
            }

            //Set fill-style to green
            layCountries.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            layCountries.Style.Outline       = Pens.Black;
            layCountries.Style.EnableOutline = true;
            layCountries.SRID = 4326;

            //Set up a river layer
            VectorLayer layRivers = new VectorLayer("Rivers");

            //Set the datasource to a shapefile in the App_data folder
            layRivers.DataSource = new Ogr("GeoData/MapInfo/riversMapInfo.tab");
            //Define a blue 1px wide pen
            layRivers.Style.Line = new Pen(Color.Blue, 1);
            layRivers.SRID       = 4326;

            //Set up a river layer
            VectorLayer layCities = new VectorLayer("Cities");

            //Set the datasource to a shapefile in the App_data folder
            layCities.DataSource        = new Ogr("GeoData/MapInfo/citiesMapInfo.tab");
            layCities.Style.SymbolScale = 0.8f;
            layCities.MaxVisible        = 40;
            layCities.SRID = 4326;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Country labels");

            layLabel.DataSource                = layCountries.DataSource;
            layLabel.Enabled                   = true;
            layLabel.LabelColumn               = "Name";
            layLabel.Style                     = new LabelStyle();
            layLabel.Style.ForeColor           = Color.White;
            layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
            layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
            layLabel.MaxVisible                = 90;
            layLabel.MinVisible                = 30;
            layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
            layLabel.SRID = 4326;
            layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;

            //Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels");

            layCityLabel.DataSource                = layCities.DataSource;
            layCityLabel.Enabled                   = true;
            layCityLabel.LabelColumn               = "Name";
            layCityLabel.Style                     = new LabelStyle();
            layCityLabel.Style.ForeColor           = Color.Black;
            layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
            layCityLabel.MaxVisible                = layLabel.MinVisible;
            layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
            layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
            layCityLabel.Style.Offset              = new PointF(3, 3);
            layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
            layCityLabel.TextRenderingHint         = TextRenderingHint.AntiAlias;
            layCityLabel.SmoothingMode             = SmoothingMode.AntiAlias;
            layCityLabel.SRID        = 4326;
            layCityLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
            layCityLabel.Style.CollisionDetection = true;

            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            map.Layers.Add(layCountries);
            map.Layers.Add(layRivers);
            map.Layers.Add(layCities);
            map.Layers.Add(layLabel);
            map.Layers.Add(layCityLabel);

            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.ZoomToExtents(); // = 360;
            map.Center = new Point(0, 0);

            _ogrSampleDataset = "MapInfo";

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Exemple #20
0
        public Form3()
        {
            InitializeComponent();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form3));
            this.components = new System.ComponentModel.Container();

            this.mapBox1           = new SharpMap.Forms.MapBox();
            this.mapZoomToolStrip1 = new SharpMap.Forms.ToolBar.MapZoomToolStrip(this.components);
            this.toolsbIdentity    = new System.Windows.Forms.ToolStripButton();
            this.mapZoomToolStrip1.SuspendLayout();

            //
            // mapBox1
            //
            this.mapBox1.ActiveTool         = SharpMap.Forms.MapBox.Tools.None;
            this.mapBox1.BackColor          = System.Drawing.Color.White;
            this.mapBox1.Cursor             = System.Windows.Forms.Cursors.Default;
            this.mapBox1.Dock               = System.Windows.Forms.DockStyle.Fill;
            this.mapBox1.FineZoomFactor     = 10D;
            this.mapBox1.Location           = new System.Drawing.Point(0, 0);
            this.mapBox1.MapQueryMode       = SharpMap.Forms.MapBox.MapQueryType.LayerByIndex;
            this.mapBox1.Name               = "mapBox1";
            this.mapBox1.QueryGrowFactor    = 5F;
            this.mapBox1.QueryLayerIndex    = 0;
            this.mapBox1.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
            this.mapBox1.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))));
            this.mapBox1.ShowProgressUpdate = false;
            this.mapBox1.Size               = new System.Drawing.Size(580, 407);
            this.mapBox1.TabIndex           = 0;
            this.mapBox1.Text               = "mapBox1";
            this.mapBox1.WheelZoomMagnitude = -2D;
            this.mapBox1.MapQueried        += new SharpMap.Forms.MapBox.MapQueryHandler(this.mapBox1_MapQueried);
            //
            // mapZoomToolStrip1
            //
            this.mapZoomToolStrip1.Enabled = false;
            this.mapZoomToolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                this.toolsbIdentity
            });
            this.mapZoomToolStrip1.Location   = new System.Drawing.Point(0, 0);
            this.mapZoomToolStrip1.MapControl = this.mapBox1;
            this.mapZoomToolStrip1.Name       = "mapZoomToolStrip1";
            this.mapZoomToolStrip1.Size       = new System.Drawing.Size(580, 25);
            this.mapZoomToolStrip1.TabIndex   = 2;
            this.mapZoomToolStrip1.Text       = "mapZoomToolStrip1";
            //
            // toolsbIdentity
            //
            this.toolsbIdentity.DisplayStyle          = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolsbIdentity.Image                 = ((System.Drawing.Image)(resources.GetObject("identify")));
            this.toolsbIdentity.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolsbIdentity.Name   = "toolsbIdentity";
            this.toolsbIdentity.Size   = new System.Drawing.Size(23, 22);
            this.toolsbIdentity.Text   = "查询";
            this.toolsbIdentity.Click += new System.EventHandler(this.toolsbIdentity_Click);

            this.Controls.Add(this.mapZoomToolStrip1);
            this.Controls.Add(this.mapBox1);

            this.mapZoomToolStrip1.ResumeLayout(false);
            this.mapZoomToolStrip1.PerformLayout();

            this.mapBox1.Map.Layers.Clear();

            SharpMap.Layers.VectorLayer vlayer = new SharpMap.Layers.VectorLayer("states");
            string start = Application.StartupPath;
            string path  = @"D:\workspace\Code\2016\ExcelReader\ExcelReader\bin\Debug\tmp.shp";

            vlayer.DataSource          = new SharpMap.Data.Providers.ShapeFile(path);
            vlayer.Style.Fill          = new SolidBrush(Color.GreenYellow);
            vlayer.Style.Outline       = System.Drawing.Pens.Gray;
            vlayer.Style.EnableOutline = true;
            mapBox1.Map.Layers.Add(vlayer);


            SharpMap.Layers.LabelLayer labelLayer = new LabelLayer("label");
            labelLayer.DataSource               = vlayer.DataSource;
            labelLayer.Enabled                  = true;
            labelLayer.LabelColumn              = "mapNo";
            labelLayer.Style                    = new SharpMap.Styles.LabelStyle();
            labelLayer.Style.ForeColor          = Color.Black;
            labelLayer.Style.Font               = new System.Drawing.Font(FontFamily.GenericSerif, 13);
            labelLayer.Style.Offset             = new PointF(3, 3);
            labelLayer.Style.Halo               = new Pen(Color.Yellow, 2);
            labelLayer.TextRenderingHint        = System.Drawing.Text.TextRenderingHint.AntiAlias;
            labelLayer.SmoothingMode            = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            labelLayer.LabelFilter              = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
            labelLayer.Style.CollisionDetection = true;
            labelLayer.MaxVisible               = 200000;
            mapBox1.Map.Layers.Add(labelLayer);


            mapBox1.Map.ZoomToExtents();
            mapBox1.Refresh();
        }
Exemple #21
0
        /// <summary>
        /// Find a LabelSource node in the layer tree which uses the
        /// specified table, and select that node.  If there are no
        /// LabelSources that use the specified table, ask the user
        /// whether a LabelSource should be added to the map.
        /// </summary>
        /// <param name="sourceTable">
        /// A table which may or may not be labeled currently</param>
        /// <param name="currentLabelSource">
        /// If null is passed, we will select the first LabelSource we find
        /// that uses the specified table; if currentLabelSource is not
        /// null, we will search for the next LabelSource that uses
        /// the same table.
        /// </param>
        private void SelectNextLabelSource(
            Table sourceTable, LabelSource currentLabelSource)
        {
            LabelSource matchingLabelSource =
                LocateNextLabelSource(_lc.Map, sourceTable, currentLabelSource, true);

            if (matchingLabelSource != null)
            {
                // There is at least one LabelSource found that uses
                // the specified table.
                if (_lc.ContextMenuTargetObject == matchingLabelSource)
                {
                    // The user right-clicked on a LabelSource in the tree,
                    // and the only LabelSource that we found is the
                    // same one the user right-clicked.  So we failed
                    // to find a Next LabelSource.
                    MapInfo.Windows.MessageBox.Show(
                        "There are no more label sources based on the table:\n\n"
                        + sourceTable.TableInfo.Description);
                }
                else
                {
                    // We found an appropriate match; select its tree node.
                    _lc.SelectedObject = matchingLabelSource;
                }
            }
            else
            {
                // There are NO LabelSource nodes that use the specified table.
                // The user must have right-clicked a FeatureLayer node
                // and then clicked Find Labels, but we could not find any.
                // Ask the user if we should create a new LabelSource.
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult      dr      = MessageBox.Show(
                    null,
                    "There are no labels for the selected layer: \n\n"
                    + sourceTable.TableInfo.Description + "\n\n"
                    + "Do you want to create a new label source?",
                    "No Labels Found", buttons);

                if (dr == DialogResult.Yes)
                {
                    if (_firstLabelLayer == null)
                    {
                        // There are NO LabelLayers in the map; build one.
                        _firstLabelLayer = new LabelLayer("Label Layer");
                        _lc.Map.Layers.Insert(0, _firstLabelLayer);
                    }
                    LabelSource newSource = new LabelSource(sourceTable);
                    if (sourceTable.TableInfo.TableType == TableType.Wms ||
                        sourceTable.TableInfo.TableType == TableType.Grid ||
                        sourceTable.TableInfo.TableType == TableType.Raster)
                    {
                        // For a Raster Image layer, just label with the layer name.
                        newSource.DefaultLabelProperties.Caption =
                            "'" + sourceTable.TableInfo.Description + "'";
                    }

                    _firstLabelLayer.Sources.Append(newSource);

                    if (!_lc.UpdateWhenCollectionChanges)
                    {
                        // The LayerControl is currently configured to NOT update
                        // automatically when a new node is added to the tree;
                        // so we will force the LayerTree to regenerate, so that
                        // the new LabelSource node appears.
                        Map map = _lc.Map;
                        _lc.Map = null;
                        _lc.Map = map;
                    }

                    _lc.SelectedObject = newSource;
                }
            }
        }
Exemple #22
0
        public static List <IFeature> RenderStackedLabelLayer(IViewport viewport, LabelLayer layer)
        {
            var renderedFeatures = new List <IFeature> ();
            var canvas           = new CALayer();

            canvas.Opacity = (float)layer.Opacity;

            //todo: take into account the priority
            var features = layer.GetFeaturesInView(viewport.Extent, viewport.Resolution);
            var margin   = viewport.Resolution * 50;

            if (layer.Style != null)
            {
                var clusters = new List <Cluster>();
                //todo: repeat until there are no more merges
                ClusterFeatures(clusters, features, margin, layer.Style, viewport.Resolution);

                foreach (var cluster in clusters)
                {
                    var feature = cluster.Features.OrderBy(f => f.Geometry.GetBoundingBox().GetCentroid().Y).FirstOrDefault();
                    //SetFeatureOutline (feature, layer.Name, cluster.Features.Count);
                    //var bb = RenderBox(cluster.Box, viewport);

                    //Zorg dat dit ALTIJD decimal zelfde ISet als ViewChanged is
                    //var feature = cluster.Features.FirstOrDefault ();

                    var styles = feature.Styles ?? Enumerable.Empty <IStyle>();
                    foreach (var style in styles)
                    {
                        if (feature.Styles != null && style.Enabled)
                        {
                            var styleKey         = layer.Name;                     //feature.GetHashCode ().ToString ();
                            var renderedGeometry = (feature[styleKey] != null) ? (CALayer)feature[styleKey] : null;
                            var labelText        = layer.GetLabelText(feature);

                            if (renderedGeometry == null)
                            {
                                //Mapsui.Geometries.Point point, Offset stackOffset, LabelStyle style, IFeature feature, IViewport viewport, string text)
                                renderedGeometry = RenderLabel(feature.Geometry as Mapsui.Geometries.Point,
                                                               style as LabelStyle, feature, viewport, labelText);

                                feature [styleKey] = renderedGeometry;
                                feature ["first"]  = true;
                            }
                            else
                            {
                                feature ["first"] = false;
                            }
                        }
                    }
                    renderedFeatures.Add(feature);

                    /*
                     * Offset stackOffset = null;
                     *
                     * foreach (var feature in cluster.Features.OrderBy(f => f.Geometry.GetBoundingBox().GetCentroid().Y))
                     * {
                     *      if (layerStyle is IThemeStyle) style = (layerStyle as IThemeStyle).GetStyle(feature);
                     *      if ((style == null) || (style.Enabled == false) || (style.MinVisible > viewport.Resolution) || (style.MaxVisible < viewport.Resolution)) continue;
                     *
                     *      if (stackOffset == null) //first time
                     *      {
                     *              stackOffset = new Offset();
                     *              if (cluster.Features.Count > 1)
                     *                      canvas.AddSublayer (RenderBox(cluster.Box, viewport));
                     *      }
                     *      else stackOffset.Y += 18; //todo: get size from text, (or just pass stack nr)
                     *
                     *      if (!(style is LabelStyle)) throw new Exception("Style of label is not a LabelStyle");
                     *      var labelStyle = style as LabelStyle;
                     *      string labelText = layer.GetLabel(feature);
                     *      var position = new Mapsui.Geometries.Point(cluster.Box.GetCentroid().X, cluster.Box.Bottom);
                     *      canvas.AddSublayer(RenderLabel(position, stackOffset, labelStyle, feature, viewport, labelText));
                     * }
                     */
                }
            }

            return(renderedFeatures);
        }
Exemple #23
0
        /// <summary>
        /// Find a LabelSource in the map which uses the
        /// specified table, and return it, or return null
        /// if no suitable LabelSource exists.
        /// </summary>
        /// <param name="map">The Map object to search</param>
        /// <param name="sourceTable">
        /// A table which may or may not be labeled currently</param>
        /// <param name="currentLabelSource">
        /// If null is passed, we will return the first LabelSource we find
        /// that uses the specified table; if currentLabelSource is not
        /// null, we will search for the next LabelSource that uses
        /// the same table.
        /// </param>
        /// <param name="wrapAround">true if you want a "find next" search
        /// to wrap around to the beginning of the layer tree, if necessary,
        /// to find the next LabelSource; false if you do not the search to wrap.
        /// </param>
        /// <returns>A LabelSource object (which may be identical to
        /// the currentLabelSource param, e.g. if the currentLabelSource
        /// param represents the only LabelSource in the map); or null if
        /// the map does not contain any LabelSource based on the specified table.
        /// </returns>
        private LabelSource LocateNextLabelSource(
            Map map, Table sourceTable, LabelSource currentLabelSource, bool wrapAround)
        {
            // Get a collection of all LabelLayers in the map
            FilterByLayerType labelLayerFilter =
                new FilterByLayerType(LayerType.Label);

            MapLayerEnumerator mapLayerEnum =
                map.Layers.GetMapLayerEnumerator(
                    labelLayerFilter, MapLayerEnumeratorOptions.Recurse);

            _firstLabelLayer = null;
            LabelSource matchingLabelSource       = null;
            LabelSource firstMatchingLabelSource  = null;
            bool        bPassedCurrentLabelSource = false;

            // Given the set of all LabelLayers in the layer tree,
            // search each LabelLayer to try to find a LabelSource
            // child node that is based on the specified table
            // (the sourceTable param).
            // OR: If a non-null currentLabelSource param
            // was passed in, then it represents an existing
            // LabelSource, and our job is to find the NEXT
            // LabelSource that uses the same table.
            foreach (LabelLayer ll in mapLayerEnum)
            {
                if (_firstLabelLayer == null)
                {
                    // Make a note of the first LabelLayer we find;
                    // later, if we decide to create a new LabelSource,
                    // it will go into this first LabelLayer.
                    _firstLabelLayer = ll;
                }

                // Look through this LabelLayer's collection of LabelSources
                foreach (LabelSource lblSource in ll.Sources)
                {
                    if (lblSource.Table == sourceTable)
                    {
                        // This LabelSource uses the correct table
                        if (firstMatchingLabelSource == null)
                        {
                            // We found our first match, so make a note of it,
                            // even though it may not be ideal (i.e. it may not
                            // be the "next" LabelSource that was requested).
                            firstMatchingLabelSource = lblSource;
                        }

                        // Now determine whether this match is an ideal match.
                        // We may have been passed a LabelSource, and asked
                        // to find the "next" LabelSource.  So we may need
                        // to skip over the current LabelSource if it's
                        // the same as the LabelSource that was passed in.
                        if (currentLabelSource != null &&
                            !bPassedCurrentLabelSource)
                        {
                            // We WERE asked to find the "next" LabelSource,
                            // which means that our first task is to find
                            // the LabelSource that the user right-clicked.
                            // But according to the flag, we have not yet
                            // looped past the currently-selected LabelSource.
                            // So we will continue the loop instead of
                            // assigning  matchingLabelSource.
                            if (lblSource == currentLabelSource)
                            {
                                // We were asked to find the next LabelSource,
                                // and this LabelSource is the same one that
                                // was passed in.  In this case, just set the
                                // flag, so that the next match will be used.
                                bPassedCurrentLabelSource = true;
                            }
                            continue;
                        }

                        // We found a LabelSource that is a perfect match.
                        matchingLabelSource = lblSource;
                        break;
                    }
                }                 // This ends the "for each LabelSource in this LabelLayer" loop

                if (matchingLabelSource != null)
                {
                    // We found an ideal match, so we can skip searching
                    // the other LabelLayers.  Break the outer foreach loop:
                    break;
                }
            }             // This ends the "for each LabelLayer" loop

            if (matchingLabelSource == null)
            {
                // We end up here if we did not find an ideal match; for
                // example, if we were asked to find the "next" node, and
                // we did not find a next matching node, but we did find a
                // previous matching node, we end up here.
                // At this point, since we did not find a perfect match,
                // we will consider a less-than-perfect match.
                if (wrapAround)
                {
                    // Wrapping is On, meaning that when we search for
                    // the next LabelSource, we should wrap around to the top of
                    // the layer list, if necessary
                    matchingLabelSource = firstMatchingLabelSource;
                }
                else
                {
                    // Wrap is Off, meaning: if we did not find a Next LabelSource,
                    // return the LabelSource that was originally specified,
                    // which will tell the caller, "there IS no Next LabelSource."
                    matchingLabelSource = currentLabelSource;
                }
            }
            return(matchingLabelSource);
        }
Exemple #24
0
        private static Map InitializeMapWithSymbolizerLayers(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            var layCountries = new SharpMap.Layers.Symbolizer.PolygonalVectorLayer(
                "Countries",
                new ShapeFile("GeoData/World/countries.shp", true),
                new BasicPolygonSymbolizer {
                Fill = new SolidBrush(Color.Green), Outline = Pens.Black,
            }
                )
            {
                SRID = 4326
            };

            //Set up a river layer
            var symbolizer = new CachedLineSymbolizer();

            symbolizer.LineSymbolizeHandlers.AddRange(new [] {
                new PlainLineSymbolizeHandler {
                    Line = new Pen(Color.Blue, 3)
                    {
                        LineJoin = LineJoin.Round
                    }
                },
                new PlainLineSymbolizeHandler {
                    Line = new Pen(Color.Aqua, 1)
                },
            });

            var layRivers = new SharpMap.Layers.Symbolizer.LinealVectorLayer("Rivers")
            {
                //Set the datasource to a shapefile in the App_data folder
                DataSource = new ShapeFile("GeoData/World/rivers.shp", true),
                //Define a blue 2px wide pen
                Symbolizer = symbolizer,
                SRID       = 4326
            };

            //Set up a cities layer
            var layCities = new SharpMap.Layers.Symbolizer.PuntalVectorLayer("Cities")
            {
                //Set the datasource to a shapefile in the App_data folder
                DataSource = new ShapeFile("GeoData/World/cities.shp", true),
                Symbolizer = new RasterPointSymbolizer()
                {
                    Scale = 0.8f
                },
                MaxVisible = 40
            };

            //Set up a country label layer
            var layLabel = new LabelLayer("Country labels")
            {
                DataSource  = layCountries.DataSource,
                Enabled     = true,
                LabelColumn = "Name",
                Style       =
                    new LabelStyle
                {
                    ForeColor           = Color.White,
                    Font                = new Font(FontFamily.GenericSerif, 12),
                    BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0)),
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center
                },
                MaxVisible = 90,
                MinVisible = 30,
                SRID       = 4326,
                MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest,
            };

            //Set up a city label layer
            var layCityLabel = new LabelLayer("City labels")
            {
                DataSource        = layCities.DataSource,
                Enabled           = true,
                LabelColumn       = "Name",
                TextRenderingHint = TextRenderingHint.AntiAlias,
                SmoothingMode     = SmoothingMode.AntiAlias,
                SRID        = 4326,
                LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection,
                Style       =
                    new LabelStyle
                {
                    ForeColor           = Color.Black,
                    Font                = new Font(FontFamily.GenericSerif, 11),
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                    VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom,
                    Offset              = new PointF(3, 3),
                    CollisionDetection  = true,
                    Halo                = new Pen(Color.Yellow, 2)
                },
                MaxVisible = layLabel.MinVisible,
            };

            //Setup River label
            var layRiverLabel = new LabelLayer("River labels")
            {
                DataSource        = layRivers.DataSource,
                Enabled           = true,
                LabelColumn       = "Name",
                TextRenderingHint = TextRenderingHint.AntiAlias,
                SmoothingMode     = SmoothingMode.AntiAlias,
                SRID        = 4326,
                LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection,
                MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.All,
                Style =
                    new LabelStyle
                {
                    ForeColor           = Color.DarkBlue,
                    Font                = new Font(FontFamily.GenericSansSerif, 11),
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                    VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Middle,
                    //CollisionDetection = true,
                    Halo         = new Pen(Color.Azure, 2),
                    IgnoreLength = true
                },
            };

            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            map.Layers.Add(layCountries);
            map.Layers.Add(layRivers);
            map.Layers.Add(layCities);
            map.Layers.Add(layRiverLabel);
            map.Layers.Add(layLabel);
            map.Layers.Add(layCityLabel);


            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.Zoom   = 360;
            map.Center = new Point(0, 0);

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            return(map);
        }
Exemple #25
0
        private void _InitialLayers()
        {
            m_layers = new Dictionary <string, TileLayer>();
            TileAsyncLayer bingLayer = new TileAsyncLayer(new BingTileSource(BingRequest.UrlBing, "", BingMapType.Aerial), "TileLayer - Bing");
            //TileAsyncLayer googleLayer = new TileAsyncLayer(new BingTileSource(BingRequest.UrlBing, "", BingMapType.Roads), "TileLayer - Bing");
            TileAsyncLayer googleLayer = new TileAsyncLayer(new GoogleTileSource(new GoogleRequest(GoogleMapType.GoogleMap), new BruTile.Cache.MemoryCache <byte[]>(100, 1000)), "TileLayer-Google");
            //TileAsyncLayer bingLayer = new TileAsyncLayer(new GoogleTileSource(new GoogleRequest(GoogleMapType.GoogleSatellite), new BruTile.Cache.MemoryCache<byte[]>(100, 1000)), "Satellite-Google");
            TileAsyncLayer hybrid = new TileAsyncLayer(new BingTileSource(BingRequest.UrlBing, "", BingMapType.Hybrid), "TileLayer - Bing Hybrid");

            m_layers.Add("Bing", bingLayer);
            m_layers.Add("Google", googleLayer);
            m_layers.Add("Hybrid", hybrid);

            //Marker layer
            markerLayer = new VectorLayer("Fixed Marker");
            markerLayer.Style.Symbol = GISAppDemo.Properties.Resources.OutfallSmall;
            markerLayer.DataSource   = markerProvider;
            Color tRed = Color.FromArgb(50, Color.Red);

            markerLayer.Style.Fill = new SolidBrush(tRed);

            //output layer
            outputLayer = new VectorLayer("Output");
            outputLayer.Style.Symbol     = GISAppDemo.Properties.Resources.g_arrow;
            outputLayer.Style.Line.Color = Color.FromArgb(255, Color.Crimson);
            outputLayer.Style.Line.Width = 3.0F;
            Color tRed2 = Color.FromArgb(128, Color.Red);

            outputLayer.Style.Fill = new SolidBrush(tRed2);
            outputLayer.DataSource = outputProvider;


            //standard output layer
            stdOutputLayer = new VectorLayer("StdOutput");
            stdOutputLayer.Style.Symbol     = GISAppDemo.Properties.Resources.r_arrow;
            stdOutputLayer.Style.Line.Color = Color.FromArgb(85, Color.Red);
            stdOutputLayer.Style.Line.Width = 3.0F;
            stdOutputLayer.DataSource       = stdOutputProvider;

            // green point layer
            greenPointLayer = new VectorLayer("GreenPoint");
            greenPointLayer.Style.PointColor = new SolidBrush(Color.FromArgb(200, Color.Green));
            greenPointLayer.Style.PointSize  = 6;
            greenPointLayer.DataSource       = greenPointProvider;

            // red point layer
            redPointLayer = new VectorLayer("RedPoint");
            redPointLayer.Style.PointColor = new SolidBrush(Color.FromArgb(200, Color.Red));
            redPointLayer.Style.PointSize  = 10;
            redPointLayer.DataSource       = redPointProvider;


            //Shape Layer
            shapeLayer            = new SharpMap.Layers.VectorLayer("Shape");
            shapeLayer.DataSource = new SharpMap.Data.Providers.ShapeFile(shpFileName, true);
            //Set fill-style to green
            shapeLayer.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            shapeLayer.Style.Outline = Pens.Black;
            //shapeLayer.Style.Line.Color = Color.Navy;
            //shapeLayer.Style.Line.Color = Color.FromArgb(200, Color.Gray);
            shapeLayer.Style.Line.Color         = Color.FromArgb(200, Color.Navy);
            shapeLayer.Style.Line.Width         = 1;
            shapeLayer.Style.PointSize          = 2;
            shapeLayer.Style.PointColor         = new SolidBrush(Color.Blue);
            shapeLayer.SRID                     = 4326;
            shapeLayer.CoordinateTransformation = LayerTools.Wgs84toGoogleMercator;

            // Shape Layer 2
            shapeLayer2            = new SharpMap.Layers.VectorLayer("Shape_2");
            shapeLayer2.DataSource = new SharpMap.Data.Providers.ShapeFile(shpFileName, true);
            //Set fill-style to green
            shapeLayer2.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            shapeLayer2.Style.Outline = Pens.Black;
            //shapeLayer.Style.Line.Color = Color.Navy;
            //shapeLayer.Style.Line.Color = Color.FromArgb(200, Color.Gray);
            shapeLayer2.Style.Line.Color         = Color.FromArgb(200, Color.Navy);
            shapeLayer2.Style.Line.Width         = 2;
            shapeLayer2.Style.PointSize          = 5;
            shapeLayer2.Style.PointColor         = new SolidBrush(Color.FromArgb(200, Color.Green));
            shapeLayer2.SRID                     = 4326;
            shapeLayer2.CoordinateTransformation = LayerTools.Wgs84toGoogleMercator;

            // Shape Layer 3
            shapeLayer3            = new SharpMap.Layers.VectorLayer("Shape_3");
            shapeLayer3.DataSource = new SharpMap.Data.Providers.ShapeFile(shpFileName, true);
            //Set fill-style to red
            shapeLayer3.Style.Fill = new SolidBrush(Color.FromArgb(128, Color.Red));
            //Set the polygons to have a black outline
            shapeLayer3.Style.Outline            = Pens.Black;
            shapeLayer3.Style.Line.Color         = Color.FromArgb(255, Color.Crimson);
            shapeLayer3.Style.Line.Width         = 3.0F;
            shapeLayer3.Style.PointSize          = 5;
            shapeLayer3.Style.PointColor         = new SolidBrush(Color.Green);
            shapeLayer3.SRID                     = 4326;
            shapeLayer3.CoordinateTransformation = LayerTools.Wgs84toGoogleMercator;

            //edgeid layer
            edgeIdLayer                          = new LabelLayer("EdgeId");
            edgeIdLayer.DataSource               = shapeLayer.DataSource;
            edgeIdLayer.LabelColumn              = "ID";
            edgeIdLayer.Style.ForeColor          = Color.Navy;
            edgeIdLayer.Style.Font               = new Font(FontFamily.GenericSerif, 16);
            edgeIdLayer.CoordinateTransformation = LayerTools.Wgs84toGoogleMercator;
        }
Exemple #26
0
 private void mnuAddTheme_Click(object sender, System.EventArgs e)
 {
     try
     {
         CreateThemeWizard createTheme = new CreateThemeWizard(mapControl1.Map,this);
         _thm = createTheme.CreateTheme("theme1");
         MapLayer themedLayer = createTheme.SelectedLayer;
         if (themedLayer is FeatureLayer)
         {
             _themedFeatureLayer = (FeatureLayer)themedLayer;
         }
         else
         {
             _themedLabelLayer = (LabelLayer)themedLayer;
         }
         if (createTheme.WizardResult == WizardStepResult.Done)
         {
             // Update the controls
             //mnuAddTheme.Enabled = false;
             mnuRemoveTheme.Enabled = true;
             mnuModifyTheme.Enabled = true;
         }
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show("Error creating theme: " + ex.Message);
     }
 }
Exemple #27
0
        public static Map InitializeMap(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layCountries = new VectorLayer("Countries");

            //Set the datasource to a shapefile in the App_data folder
            layCountries.DataSource = new SpatiaLite(
                DataSource, "countries", "geom", "PK_UID");

            //Set fill-style to green
            layCountries.Style.Fill = new SolidBrush(Color.Green);
            //Set the polygons to have a black outline
            layCountries.Style.Outline       = Pens.Black;
            layCountries.Style.EnableOutline = true;

            //Set up a river layer
            VectorLayer layRivers = new VectorLayer("Rivers");

            //Set the datasource to a shapefile in the App_data folder
            layRivers.DataSource = new SpatiaLite(
                DataSource, "rivers", "geom", "PK_UID");
            //Define a blue 3px wide pen
            layRivers.Style.Line = new Pen(Color.LightBlue, 2);
            layRivers.Style.Line.CompoundArray = new[] { 0.2f, 0.8f };
            layRivers.Style.Outline            = new Pen(Color.DarkBlue, 3);
            layRivers.Style.EnableOutline      = true;

            //Set up a cities layer
            VectorLayer layCities = new VectorLayer("Cities");

            //Set the datasource to the spatialite table
            layCities.DataSource = new SpatiaLite(
                DataSource, "cities", "geom", "PK_UID");
            layCities.Style.SymbolScale = 0.8f;
            layCities.MaxVisible        = 40;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Country labels")
            {
                DataSource  = layCountries.DataSource,
                LabelColumn = "NAME",
                MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest,
                LabelFilter    = LabelCollisionDetection.ThoroughCollisionDetection,
                PriorityColumn = "POPDENS",
                Style          = new LabelStyle
                {
                    ForeColor           = Color.White,
                    Font                = new Font(FontFamily.GenericSerif, 12),
                    BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0)),
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                    MaxVisible          = 90,
                    MinVisible          = 30,
                    CollisionDetection  = true
                }
            };

            //Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels")
            {
                DataSource       = layCities.DataSource,
                LabelColumn      = "name",
                PriorityColumn   = "population",
                PriorityDelegate = delegate(IFeature fdr)
                {
                    Int32 retVal = 10000000 * ((String)fdr.Attributes["capital"] == "Y" ? 1 : 0);
                    return(retVal + Convert.ToInt32(fdr.Attributes["population"]));
                },
                TextRenderingHint = TextRendering.AntiAlias,
                SmoothingMode     = Smoothing.AntiAlias,
                LabelFilter       = LabelCollisionDetection.ThoroughCollisionDetection,
                Style             = new LabelStyle
                {
                    ForeColor           = Color.Black,
                    Font                = new Font(FontFamily.GenericSerif, 11),
                    MaxVisible          = layLabel.MinVisible,
                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                    VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom,
                    Offset              = new PointF(3, 3),
                    Halo                = new Pen(Color.Yellow, 2),
                    CollisionDetection  = true
                }
            };

            LabelLayer layRiverLabels = new LabelLayer("RiverLabels");

            layRiverLabels.DataSource       = layRivers.DataSource;
            layRiverLabels.LabelColumn      = "Name";
            layRiverLabels.PriorityDelegate = GetRiverLength;
            layRiverLabels.Style            = new LabelStyle
            {
                Font               = new Font("Arial", 10, FontStyle.Bold),
                Halo               = new Pen(Color.Azure, 2),
                ForeColor          = Color.DarkCyan,
                IgnoreLength       = true,
                Enabled            = true,
                CollisionDetection = true,
            };
            layRiverLabels.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;

            //Add the layers to the map object.
            //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
            map.Layers.Add(layCountries);
            map.Layers.Add(layRivers);
            map.Layers.Add(layCities);
            map.Layers.Add(layRiverLabels);
            map.Layers.Add(layLabel);
            map.Layers.Add(layCityLabel);

            //limit the zoom to 360 degrees width
            map.MaximumZoom = 360;
            map.BackColor   = Color.LightBlue;

            map.ZoomToExtents(); // = 360;

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;
            return(map);
        }
Exemple #28
0
        private void SetupMap()
        {
            lifelines = new FeatureDataTable();
            lifelines.Columns.Add("MapLifeLine", typeof(MapLifeLine));
            lifelines.Columns.Add("LineCap", typeof(string));
            lifelines.Columns.Add("Label", typeof(string));
            lifelines.Columns.Add("ViewPort", typeof(Envelope));

            GeometryFeatureProvider lifelinesGFP = new GeometryFeatureProvider(lifelines);

            VectorStyle linestyle = new VectorStyle
            {
                Line = new Pen(Color.Green, 2f)
            };

            linestyle.Line.MiterLimit = 0;
            linesLayer = new VectorLayer("LifeLines")
            {
                DataSource = lifelinesGFP,
                Style      = linestyle
            };

            Dictionary <string, IStyle> styles = new Dictionary <string, IStyle>();
            VectorStyle line = new VectorStyle
            {
                PointColor = new SolidBrush(Color.Green),
                PointSize  = 2
            };

            styles.Add(MapLifeLine.LINE, line);

            VectorStyle startPoint = new VectorStyle
            {
                PointColor = new SolidBrush(Color.Green),
                PointSize  = 2,
                Symbol     = Image.FromFile(Path.Combine(Application.StartupPath, @"Resources\Icons\arrow-right.png"))
            };

            styles.Add(MapLifeLine.START, startPoint);

            VectorStyle endPoint = new VectorStyle
            {
                PointColor = new SolidBrush(Color.Green),
                PointSize  = 2,
                Symbol     = Image.FromFile(Path.Combine(Application.StartupPath, @"Resources\Icons\arrow-left.png"))
            };

            styles.Add(MapLifeLine.END, endPoint);

            linesLayer.Theme = new SharpMap.Rendering.Thematics.UniqueValuesTheme <string>("LineCap", styles, line);

            mapBox1.Map.Layers.Add(linesLayer);

            labelLayer = new LabelLayer("Label")
            {
                DataSource = lifelinesGFP,
                Enabled    = true,
                //Specifiy field that contains the label string.
                LabelColumn       = "Label",
                TextRenderingHint = TextRenderingHint.AntiAlias,
                SmoothingMode     = SmoothingMode.AntiAlias
            };
            LabelStyle style = new LabelStyle
            {
                ForeColor           = Color.Black,
                Font                = new Font(FontFamily.GenericSerif, 14, FontStyle.Bold),
                HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
                VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom,
                CollisionDetection  = true,
                Offset              = new PointF(0, 25),
                Halo                = new Pen(Color.Yellow, 3)
            };

            labelLayer.Style = style;
            mapBox1.Map.Layers.Add(labelLayer);

            points = new TearDropLayer("Points");
            mapBox1.Map.Layers.Add(points);
            selections = new TearDropLayer("Selections");
            mapBox1.Map.VariableLayers.Add(selections);

            mh.AddParishLayers(mapBox1.Map);
            mh.SetScaleBar(mapBox1);
            mapBox1.Map.MinimumZoom = 500;
            mapBox1.Map.MaximumZoom = 50000000;
            mapBox1.QueryGrowFactor = 30;
            mapBox1.Map.ZoomToExtents();
            mapBox1.ActiveTool = SharpMap.Forms.MapBox.Tools.Pan;
        }
Exemple #29
0
 public static LabelLayer CreateLabelLayer(VectorLayer src, string column)
 {
     string name = String.Format("{0}:Labels", src.LayerName);
     LabelLayer layer = new LabelLayer(name);
     layer.DataSource = src.DataSource;
     layer.LabelColumn = column;
     layer.Style.CollisionDetection = true;
     layer.Style.CollisionBuffer = new SizeF(10F, 10F);
     layer.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
     layer.Style.Offset = new PointF(0, -5F);
     layer.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.CommonCenter;
     layer.Style.Font = new Font(FontFamily.GenericSansSerif, 12);
     layer.MaxVisible = src.MaxVisible;
     layer.MinVisible = src.MinVisible;
     layer.Style.Halo = new Pen(Color.White, 2);
     layer.SmoothingMode = SmoothingMode.HighQuality;
     layer.CoordinateTransformation = src.CoordinateTransformation;
     return layer;
 }
Exemple #30
0
        public static Map InitializeMap(float angle)
        {
            try
            {
                // WARNING
                // This sample needs the GeoServer WFS running on your local machine.
                // It uses the GeoServer default sample data. Installing and starting it is all you need to do
                // http://docs.codehaus.org/display/GEOS/Download

                // Sample by Peter Robineau

                const string getCapabilitiesURI = "http://localhost:8080/geoserver/wfs";
                const string serviceURI         = "http://localhost:8080/geoserver/wfs";

                Map map = new Map(new Size(600, 600));
                map.MinimumZoom = 0.005;
                map.BackColor   = Color.White;

                VectorLayer layer1 = new VectorLayer("States");
                VectorLayer layer2 = new VectorLayer("SelectedStatesAndHousholds");
                VectorLayer layer3 = new VectorLayer("New Jersey");
                VectorLayer layer4 = new VectorLayer("Roads");
                VectorLayer layer5 = new VectorLayer("Landmarks");
                VectorLayer layer6 = new VectorLayer("Poi");

                // Demo data from Geoserver 1.5.3 and Geoserver 1.6.0

                WFS prov1 = new WFS(getCapabilitiesURI, "topp", "states", WFS.WFSVersionEnum.WFS1_0_0);

                // Bypass 'GetCapabilities' and 'DescribeFeatureType', if you know all necessary metadata.
                WfsFeatureTypeInfo featureTypeInfo = new WfsFeatureTypeInfo(serviceURI, "topp", null, "states",
                                                                            "the_geom");
                // 'WFS.WFSVersionEnum.WFS1_1_0' supported by Geoserver 1.6.x
                WFS prov2 = new WFS(featureTypeInfo, WFS.WFSVersionEnum.WFS1_1_0);
                // Bypass 'GetCapabilities' and 'DescribeFeatureType' again...
                // It's possible to specify the geometry type, if 'DescribeFeatureType' does not...(.e.g 'GeometryAssociationType')
                // This helps to accelerate the initialization process in case of unprecise geometry information.
                WFS prov3 = new WFS(serviceURI, "topp", "http://www.openplans.org/topp", "states", "the_geom",
                                    GeometryTypeEnum.MultiSurfacePropertyType, WFS.WFSVersionEnum.WFS1_1_0);

                // Get data-filled FeatureTypeInfo after initialization of dataprovider (useful in Web Applications for caching metadata.
                WfsFeatureTypeInfo info = prov1.FeatureTypeInfo;

                // Use cached 'GetCapabilities' response of prov1 (featuretype hosted by same service).
                // Compiled XPath expressions are re-used automatically!
                // If you use a cached 'GetCapabilities' response make sure the data provider uses the same version of WFS as the one providing the cache!!!
                WFS prov4 = new WFS(prov1.GetCapabilitiesCache, "tiger", "tiger_roads", WFS.WFSVersionEnum.WFS1_0_0);
                WFS prov5 = new WFS(prov1.GetCapabilitiesCache, "tiger", "poly_landmarks", WFS.WFSVersionEnum.WFS1_0_0);
                WFS prov6 = new WFS(prov1.GetCapabilitiesCache, "tiger", "poi", WFS.WFSVersionEnum.WFS1_0_0);
                // Clear cache of prov1 - data providers do not have any cache, if they use the one of another data provider
                prov1.GetCapabilitiesCache = null;

                //Filters
                IFilter filter1 = new PropertyIsEqualToFilter_FE1_1_0("STATE_NAME", "California");
                IFilter filter2 = new PropertyIsEqualToFilter_FE1_1_0("STATE_NAME", "Vermont");
                IFilter filter3 = new PropertyIsBetweenFilter_FE1_1_0("HOUSHOLD", "600000", "4000000");
                IFilter filter4 = new PropertyIsLikeFilter_FE1_1_0("STATE_NAME", "New*");

                // SelectedStatesAndHousholds: Green
                OGCFilterCollection filterCollection1 = new OGCFilterCollection();
                filterCollection1.AddFilter(filter1);
                filterCollection1.AddFilter(filter2);
                OGCFilterCollection filterCollection2 = new OGCFilterCollection();
                filterCollection2.AddFilter(filter3);
                filterCollection1.AddFilterCollection(filterCollection2);
                filterCollection1.Junctor = OGCFilterCollection.JunctorEnum.Or;
                prov2.OGCFilter           = filterCollection1;

                // Like-Filter('New*'): Bisque
                prov3.OGCFilter = filter4;

                // Layer Style
                layer1.Style.Fill = new SolidBrush(Color.IndianRed); // States
                layer2.Style.Fill = new SolidBrush(Color.Green);     // SelectedStatesAndHousholds
                layer3.Style.Fill = new SolidBrush(Color.Bisque);    // e.g. New York, New Jersey,...
                layer5.Style.Fill = new SolidBrush(Color.LightBlue);

                // Labels
                // Labels are collected when parsing the geometry. So there's just one 'GetFeatureByOid' call necessary.
                // Otherwise (when calling twice for retrieving labels) there may be an inconsistent read...
                // If a label property is set, the quick geometry option is automatically set to 'false'.
                prov3.Label = "STATE_NAME";
                LabelLayer layLabel = new LabelLayer("labels");
                layLabel.DataSource  = prov3;
                layLabel.Enabled     = true;
                layLabel.LabelColumn = prov3.Label;
                layLabel.Style       = new LabelStyle();
                layLabel.Style.CollisionDetection = false;
                layLabel.Style.CollisionBuffer    = new SizeF(5, 5);
                layLabel.Style.ForeColor          = Color.Black;
                layLabel.Style.Font = new Font(FontFamily.GenericSerif, 10);
                layLabel.MaxVisible = 90;
                layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
                // Options
                // Defaults: MultiGeometries: true, QuickGeometries: false, GetFeatureGETRequest: false
                // Render with validation...
                prov1.QuickGeometries = false;
                // Important when connecting to an UMN MapServer
                prov1.GetFeatureGETRequest = true;
                // Ignore multi-geometries...
                prov1.MultiGeometries = false;

                // Quick geometries
                // We need this option for prov2 since we have not passed a featuretype namespace
                prov2.QuickGeometries = true;
                prov4.QuickGeometries = true;
                prov5.QuickGeometries = true;
                prov6.QuickGeometries = true;

                layer1.DataSource = prov1;
                layer2.DataSource = prov2;
                layer3.DataSource = prov3;
                layer4.DataSource = prov4;
                layer5.DataSource = prov5;
                layer6.DataSource = prov6;

                map.Layers.Add(layer1);
                map.Layers.Add(layer2);
                map.Layers.Add(layer3);
                map.Layers.Add(layer4);
                map.Layers.Add(layer5);
                map.Layers.Add(layer6);
                map.Layers.Add(layLabel);

                map.Center = new Point(-74.0, 40.7);
                map.Zoom   = 10;
                // Alternatively zoom closer
                // demoMap.Zoom = 0.2;

                Matrix mat = new Matrix();
                mat.RotateAt(angle, map.WorldToImage(map.Center));
                map.MapTransform = mat;

                return(map);
            }
            catch (WebException ex)
            {
                if ((ex.Message.Contains("(502) Bad Gateway")) ||
                    (ex.Message.Contains("Unable to connect to the remote server")))
                {
                    throw new Exception(
                              "The Wfs sample threw an exception. You probably need to install the GeoServer WFS to your local machine. You can get it from here: http://docs.codehaus.org/display/GEOS/Download. The exception message was: " +
                              ex.Message);
                }
                else
                {
                    throw;
                }
            }
        }
Exemple #31
0
        //初始化地图,更换地图
        private void InitMap(MapFile mapFile)
        {
            currentMap = mapFile;
            if (preMap == mapFile.File)
            {
                return;
            }
            mapControl.Map.Clear();
            mapControl.Map.Load(MapInfo.Mapping.MapLoader.CreateFromFile(mapFile.File));
            mapControlOver.Map.Load(MapInfo.Mapping.MapLoader.CreateFromFile(mapFile.File));
            initZoom = mapControl.Map.Zoom;

            initCenter = mapControl.Map.Bounds.Center();
            ClearDistanceLayer();
            preMap = mapFile.File;

            comboBoxLayers.Items.Clear();
            listBoxLayerPlace.Items.Clear();
            for (int i = 1; i < mapControl.Map.Layers.Count; i++)
            {
                if (mapControl.Map.Layers[i].Name != "Watching" && mapControl.Map.Layers[i].Name != "Place" &&
                    mapControl.Map.Layers[i].Name != "HisPos" && mapControl.Map.Layers[i].Name != "HisLine" &&
                    mapControl.Map.Layers[i].Name != "HisAlarm" && mapControl.Map.Layers[i].Name != "Alarm" &&
                    mapControl.Map.Layers[i].Name != "DisLine" && mapControl.Map.Layers[i].Name != "Temp" &&
                    mapControl.Map.Layers[i].Name != "HisPlayPos" && mapControl.Map.Layers[i].Name != "HisPlayLine" &&
                    mapControl.Map.Layers[i].Name != "Watching_L" && mapControl.Map.Layers[i].Name != "Place_L" &&
                    mapControl.Map.Layers[i].Name != "HisPos_L" && mapControl.Map.Layers[i].Name != "HisAlarm_L" &&
                    mapControl.Map.Layers[i].Name != "Alarm_L" && mapControl.Map.Layers[i].Name != "HisPlayPos_L" &&
                    mapControl.Map.Layers[i].Name != "Administrative")
                {
                    comboBoxLayers.Items.Add(mapControl.Map.Layers[i].Name);
                }
            }
            if (comboBoxLayers.Items.Count > 0)
            {
                comboBoxLayers.SelectedIndex = 0;
            }

            if (tableWatching == null)
            {
                //监控点图层
                TableInfo ti = TableInfoFactory.CreateTemp("Watching");
                ti.Columns.Add(ColumnFactory.CreateStringColumn("ID", 10));
                ti.Columns.Add(ColumnFactory.CreateStringColumn("Label", 20));
                tableWatching = Session.Current.Catalog.CreateTable(ti);
                TextStyle ts = new TextStyle();
                ts.Font.Size       = 8;
                ts.Font.FontWeight = FontWeight.Bold;
                ts.Font.ForeColor  = Color.Green;
                labLayWatching     = new LabelLayer("Watching_L", "Watching_L");
                LabelSource source = new LabelSource(tableWatching);
                source.DefaultLabelProperties.Caption                 = "Label";
                source.DefaultLabelProperties.Style                   = ts;
                source.DefaultLabelProperties.CalloutLine.Use         = false;
                source.DefaultLabelProperties.Layout.Alignment        = MapInfo.Text.Alignment.CenterRight;
                source.DefaultLabelProperties.Layout.Offset           = 10;
                source.DefaultLabelProperties.Visibility.AllowOverlap = true;
                //labLayWatching = (LabelLayer)mapControl.Map.Layers["Watching_L"];
                labLayWatching.Sources.Append(source);
                //自定义标注点图层
                TableInfo ti2 = TableInfoFactory.CreateTemp("Place");
                ti2.Columns.Add(ColumnFactory.CreateStringColumn("Label", 20));
                tablePlace = Session.Current.Catalog.CreateTable(ti2);
                TextStyle ts2 = new TextStyle();
                ts2.Font.Size       = 8;
                ts2.Font.FontWeight = FontWeight.Bold;
                ts2.Font.ForeColor  = Color.Blue;
                labLayPlace         = new LabelLayer("Place_L", "Place_L");
                LabelSource source2 = new LabelSource(tablePlace);
                source2.DefaultLabelProperties.Caption                 = "Label";
                source2.DefaultLabelProperties.Style                   = ts2;
                source2.DefaultLabelProperties.CalloutLine.Use         = false;
                source2.DefaultLabelProperties.Layout.Alignment        = MapInfo.Text.Alignment.CenterRight;
                source2.DefaultLabelProperties.Layout.Offset           = 10;
                source2.DefaultLabelProperties.Visibility.AllowOverlap = false;
                //labLayPlace = (LabelLayer)mapControl.Map.Layers["Place_L"];
                labLayPlace.Sources.Append(source2);
                //历史轨迹点图层
                TableInfo ti3 = TableInfoFactory.CreateTemp("HisPos");
                ti3.Columns.Add(ColumnFactory.CreateStringColumn("Label", 20));
                tableHisPos = Session.Current.Catalog.CreateTable(ti3);
                TextStyle ts3 = new TextStyle();
                ts3.Font.Size       = 8;
                ts3.Font.FontWeight = FontWeight.Bold;
                ts3.Font.ForeColor  = Color.Navy;
                labLayHisPos        = new LabelLayer("HisPos_L", "HisPos_L");
                LabelSource source3 = new LabelSource(tableHisPos);
                source3.DefaultLabelProperties.Caption                 = "Label";
                source3.DefaultLabelProperties.Style                   = ts3;
                source3.DefaultLabelProperties.CalloutLine.Use         = false;
                source3.DefaultLabelProperties.Layout.Alignment        = MapInfo.Text.Alignment.CenterRight;
                source3.DefaultLabelProperties.Layout.Offset           = 10;
                source3.DefaultLabelProperties.Visibility.AllowOverlap = false;
                //labLayHisPos = (LabelLayer)mapControl.Map.Layers["HisPos_L"];
                labLayHisPos.Sources.Append(source3);
                //历史轨迹线图层
                TableInfo ti4 = TableInfoFactory.CreateTemp("HisLine");
                tableHisLine = Session.Current.Catalog.CreateTable(ti4);
                //历史报警点图层
                TableInfo ti5 = TableInfoFactory.CreateTemp("HisAlarm");
                ti5.Columns.Add(ColumnFactory.CreateStringColumn("Label", 20));
                tableHisAlarm = Session.Current.Catalog.CreateTable(ti5);
                TextStyle ts5 = new TextStyle();
                ts5.Font.Size       = 8;
                ts5.Font.FontWeight = FontWeight.Bold;
                ts5.Font.ForeColor  = Color.Red;
                labLayHisAlarm      = new LabelLayer("HisAlarm_L", "HisAlarm_L");
                LabelSource source5 = new LabelSource(tableHisAlarm);
                source5.DefaultLabelProperties.Caption                 = "Label";
                source5.DefaultLabelProperties.Style                   = ts5;
                source5.DefaultLabelProperties.CalloutLine.Use         = false;
                source5.DefaultLabelProperties.Layout.Alignment        = MapInfo.Text.Alignment.CenterRight;
                source5.DefaultLabelProperties.Layout.Offset           = 10;
                source5.DefaultLabelProperties.Visibility.AllowOverlap = false;
                //labLayHisAlarm = (LabelLayer)mapControl.Map.Layers["HisAlarm_L"];
                labLayHisAlarm.Sources.Append(source5);
                //报警点图层
                TableInfo ti6 = TableInfoFactory.CreateTemp("Alarm");
                ti6.Columns.Add(ColumnFactory.CreateStringColumn("Label", 20));
                tableAlarm = Session.Current.Catalog.CreateTable(ti6);
                TextStyle ts6 = new TextStyle();
                ts6.Font.Size       = 8;
                ts6.Font.FontWeight = FontWeight.Bold;
                ts6.Font.ForeColor  = Color.Red;
                labLayAlarm         = new LabelLayer("Alarm_L", "Alarm_L");
                LabelSource source6 = new LabelSource(tableAlarm);
                source6.DefaultLabelProperties.Caption                 = "Label";
                source6.DefaultLabelProperties.Style                   = ts6;
                source6.DefaultLabelProperties.CalloutLine.Use         = false;
                source6.DefaultLabelProperties.Layout.Alignment        = MapInfo.Text.Alignment.CenterRight;
                source6.DefaultLabelProperties.Layout.Offset           = 10;
                source6.DefaultLabelProperties.Visibility.AllowOverlap = false;
                //labLayAlarm = (LabelLayer)mapControl.Map.Layers["Alarm_L"];
                labLayAlarm.Sources.Append(source6);
                //测距线图层
                TableInfo ti7 = TableInfoFactory.CreateTemp("DisLine");
                tableDisLine = Session.Current.Catalog.CreateTable(ti7);
                //临时图层
                TableInfo ti8 = TableInfoFactory.CreateTemp("Temp");
                tableTemp = Session.Current.Catalog.CreateTable(ti8);
                //轨迹回放点图层
                TableInfo ti9 = TableInfoFactory.CreateTemp("HisPlayPos");
                ti9.Columns.Add(ColumnFactory.CreateStringColumn("Label", 20));
                tableHisPlay = Session.Current.Catalog.CreateTable(ti9);
                TextStyle ts9 = new TextStyle();
                ts9.Font.Size       = 8;
                ts9.Font.FontWeight = FontWeight.Bold;
                ts9.Font.ForeColor  = Color.Black;
                labLayHisPlayPos    = new LabelLayer("HisPlayPos_L", "HisPlayPos_L");
                LabelSource source9 = new LabelSource(tableHisPlay);
                source9.DefaultLabelProperties.Caption                 = "Label";
                source9.DefaultLabelProperties.Style                   = ts9;
                source9.DefaultLabelProperties.CalloutLine.Use         = false;
                source9.DefaultLabelProperties.Layout.Alignment        = MapInfo.Text.Alignment.CenterRight;
                source9.DefaultLabelProperties.Layout.Offset           = 10;
                source9.DefaultLabelProperties.Visibility.AllowOverlap = false;
                labLayHisPlayPos.Sources.Append(source9);
                //轨迹回放线图层
                TableInfo ti10 = TableInfoFactory.CreateTemp("HisPlayLine");
                tableHisPlayLine = Session.Current.Catalog.CreateTable(ti10);
            }

            FeatureLayer lyr = new FeatureLayer(tableWatching);

            mapControl.Map.Layers.Insert(0, lyr);
            FeatureLayer lyr2 = new FeatureLayer(tablePlace);

            mapControl.Map.Layers.Insert(0, lyr2);

            FeatureLayer lyr3 = new FeatureLayer(tableHisPos);

            mapControl.Map.Layers.Insert(0, lyr3);
            FeatureLayer lyr4 = new FeatureLayer(tableHisLine);

            mapControl.Map.Layers.Insert(0, lyr4);

            FeatureLayer lyr5 = new FeatureLayer(tableHisAlarm);

            mapControl.Map.Layers.Insert(0, lyr5);

            FeatureLayer lyr6 = new FeatureLayer(tableAlarm);

            mapControl.Map.Layers.Insert(0, lyr6);
            FeatureLayer lyr7 = new FeatureLayer(tableDisLine);

            mapControl.Map.Layers.Insert(0, lyr7);

            FeatureLayer lyr8 = new FeatureLayer(tableTemp);

            mapControl.Map.Layers.Insert(0, lyr8);

            FeatureLayer lyr9 = new FeatureLayer(tableHisPlay);

            mapControl.Map.Layers.Insert(0, lyr9);
            FeatureLayer lyr10 = new FeatureLayer(tableHisPlayLine);

            mapControl.Map.Layers.Insert(0, lyr10);

            //标注图层
            mapControl.Map.Layers.Add(labLayWatching);
            mapControl.Map.Layers.Add(labLayPlace);
            mapControl.Map.Layers.Add(labLayHisPos);
            mapControl.Map.Layers.Add(labLayHisAlarm);
            mapControl.Map.Layers.Add(labLayAlarm);
            mapControl.Map.Layers.Add(labLayHisPlayPos);
        }
Exemple #32
0
    public static Map InitializeMapOgr(Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

        //Initialize a new map of size 'imagesize'
        Map map = new Map(size);

        //Set up the countries layer
        VectorLayer layCountries = new VectorLayer("Countries");

        //Set the datasource to a shapefile in the App_data folder
        try
        {
            layCountries.DataSource =
                new Ogr(HttpContext.Current.Server.MapPath(@"~\App_data\MapInfo\countriesMapInfo.tab"));
        }
        catch (TypeInitializationException ex)
        {
            if (ex.GetType() == typeof(TypeInitializationException))
            {
                throw new Exception(
                          "Please copy the umanaged dll's into your bin folder from javascript:window.location.href='http://www.codeplex.com/SharpMap/Wiki/View.aspx?title=Extensions';.");
            }
        }
        catch (Exception ex)
        {
            throw;
        }

        //Set fill-style to green
        layCountries.Style.Fill = new SolidBrush(Color.Green);
        //Set the polygons to have a black outline
        layCountries.Style.Outline       = Pens.Black;
        layCountries.Style.EnableOutline = true;
        layCountries.SRID = 4326;

        //Set up a river layer
        VectorLayer layRivers = new VectorLayer("Rivers");

        //Set the datasource to a shapefile in the App_data folder
        layRivers.DataSource = new Ogr(HttpContext.Current.Server.MapPath(@"~\App_data\MapInfo\riversMapInfo.tab"));
        //Define a blue 1px wide pen
        layRivers.Style.Line = new Pen(Color.Blue, 1);
        layRivers.SRID       = 4326;

        //Set up a river layer
        VectorLayer layCities = new VectorLayer("Cities");

        //Set the datasource to a shapefile in the App_data folder
        layCities.DataSource = new Ogr(HttpContext.Current.Server.MapPath(@"~\App_data\MapInfo\citiesMapInfo.tab"));
        //Define a blue 1px wide pen
        //layCities.Style.Symbol = new Bitmap(HttpContext.Current.Server.MapPath(@"~\App_data\icon.png"));
        layCities.Style.SymbolScale = 0.8f;
        layCities.MaxVisible        = 40;
        layCities.SRID = 4326;

        //Set up a country label layer
        LabelLayer layLabel = new LabelLayer("Country labels");

        layLabel.DataSource                = layCountries.DataSource;
        layLabel.Enabled                   = true;
        layLabel.LabelColumn               = "Name";
        layLabel.Style                     = new LabelStyle();
        layLabel.Style.ForeColor           = Color.White;
        layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
        layLabel.Style.BackColor           = new SolidBrush(Color.FromArgb(128, 255, 0, 0));
        layLabel.MaxVisible                = 90;
        layLabel.MinVisible                = 30;
        layLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
        layLabel.SRID = 4326;
        layLabel.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;

        //Set up a city label layer
        LabelLayer layCityLabel = new LabelLayer("City labels");

        layCityLabel.DataSource                = layCities.DataSource;
        layCityLabel.Enabled                   = true;
        layCityLabel.LabelColumn               = "Name";
        layCityLabel.Style                     = new LabelStyle();
        layCityLabel.Style.ForeColor           = Color.Black;
        layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
        layCityLabel.MaxVisible                = layLabel.MinVisible;
        layCityLabel.Style.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
        layCityLabel.Style.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
        layCityLabel.Style.Offset              = new PointF(3, 3);
        layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
        layCityLabel.TextRenderingHint         = TextRenderingHint.AntiAlias;
        layCityLabel.SmoothingMode             = SmoothingMode.AntiAlias;
        layCityLabel.SRID        = 4326;
        layCityLabel.LabelFilter = LabelCollisionDetection.ThoroughCollisionDetection;
        layCityLabel.Style.CollisionDetection = true;

        //Add the layers to the map object.
        //The order we add them in are the order they are drawn, so we add the rivers last to put them on top
        map.Layers.Add(layCountries);
        map.Layers.Add(layRivers);
        map.Layers.Add(layCities);
        map.Layers.Add(layLabel);
        map.Layers.Add(layCityLabel);


        //limit the zoom to 360 degrees width
        map.MaximumZoom = 360;
        map.BackColor   = Color.LightBlue;

        map.ZoomToExtents(); // = 360;
        map.Center = new Point(0, 0);

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
Exemple #33
0
        public static Map InitializeMap()
        {
            //Initialize a new map based on the simple map
            var map = new Map();

            //Layer osm = new Layer("OSM");
            //string url = "http://labs.metacarta.com/wms-c/tilecache.py?version=1.1.1&amp;request=GetCapabilities&amp;service=wms-c";
            //var tileSources = TileSourceWmsC.TileSourceBuilder(new Uri(url), null);
            //var tileSource = new List<ITileSource>(tileSources).Find(source => source.Schema.Name == "osm-map");
            //osm.DataSource = new TileProvider(tileSource, "OSM");
            //map.Layers.Add(osm);

            //Set up countries layer
            var countryLayer = new Layer("Countries");

            //Set the datasource to a shapefile in the App_data folder
            countryLayer.DataSource      = new ShapeFile("GeoData/World/countries.shp", true);
            countryLayer.DataSource.SRID = 4326;

            var style = new VectorStyle
            {
                Fill = new Brush {
                    Color = Color.Green
                },
                Outline = new Pen {
                    Color = Color.Black
                }
            };

            countryLayer.Styles.Add(style);
            map.Layers.Add(countryLayer);

            //set up cities layer
            var cityLayer = new Layer("Cities");

            //Set the datasource to a shapefile in the App_data folder
            cityLayer.DataSource      = new ShapeFile("GeoData/World/cities.shp", true);
            cityLayer.DataSource.SRID = 4326;
            cityLayer.MaxVisible      = 0.09;
            map.Layers.Add(cityLayer);

            //Set up a country label layer
            var countryLabelLayer = new LabelLayer("Country labels");

            countryLabelLayer.DataSource      = countryLayer.DataSource;
            countryLabelLayer.DataSource.SRID = 4326;
            countryLabelLayer.Enabled         = true;
            countryLabelLayer.MaxVisible      = 0.18;
            countryLabelLayer.MinVisible      = 0.054;
            countryLabelLayer.LabelColumn     = "NAME";
            var labelStyle = new LabelStyle();

            labelStyle.ForeColor = Color.Black;
            labelStyle.Font      = new Font {
                FontFamily = "GenericSerif", Size = 12
            };
            labelStyle.BackColor = new Brush {
                Color = new Color {
                    A = 128, R = 255, G = 255, B = 255
                }
            };
            labelStyle.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center;
            countryLabelLayer.MultipartGeometryBehaviour = LabelLayer.MultipartGeometryBehaviourEnum.Largest;
            countryLabelLayer.Styles.Add(labelStyle);
            map.Layers.Add(countryLabelLayer);

            //Set up a city label layer
            var cityLabelLayer = new LabelLayer("City labels");

            cityLabelLayer.DataSource      = cityLayer.DataSource;
            cityLabelLayer.DataSource.SRID = 4326;
            cityLabelLayer.Enabled         = true;
            cityLabelLayer.LabelColumn     = "NAME";
            cityLabelLayer.MaxVisible      = countryLabelLayer.MinVisible;
            cityLabelLayer.MinVisible      = 0;
            cityLabelLayer.LabelFilter     = LabelCollisionDetection.ThoroughCollisionDetection;
            var cityLabelStyle = new LabelStyle();

            cityLabelStyle.ForeColor = Color.Black;
            cityLabelStyle.Font      = new Font {
                FontFamily = "GenericSerif", Size = 11
            };
            cityLabelStyle.HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left;
            cityLabelStyle.VerticalAlignment   = LabelStyle.VerticalAlignmentEnum.Bottom;
            cityLabelStyle.Offset = new Offset {
                X = 3, Y = 3
            };
            cityLabelStyle.Halo = new Pen {
                Color = Color.Yellow, Width = 2
            };
            cityLabelStyle.CollisionDetection = true;
            cityLabelLayer.Styles.Add(cityLabelStyle);
            map.Layers.Add(cityLabelLayer);

            //Set a gradient theme on the countries layer, based on Population density
            //First create two styles that specify min and max styles
            //In this case we will just use the default values and override the fill-colors
            //using a colorblender. If different line-widths, line- and fill-colors where used
            //in the min and max styles, these would automatically get linearly interpolated.
            IStyle min = new Style();
            IStyle max = new Style();
            //Create theme using a density from 0 (min) to 400 (max)
            var popdens = new GradientTheme("PopDens", 0, 400, min, max);

            //We can make more advanced coloring using the ColorBlend'er.
            //Setting the FillColorBlend will override any fill-style in the min and max fills.
            //In this case we just use the predefined Rainbow colorscale
            popdens.FillColorBlend = ColorBlend.Rainbow5;
            countryLayer.Styles.Add(popdens);

            //Lets scale the labels so that big countries have larger texts as well
            var lblMin = new LabelStyle();
            var lblMax = new LabelStyle();

            lblMin.ForeColor = Color.Black;
            lblMin.Font      = new Font {
                FontFamily = "Sans Serif", Size = 6
            };
            lblMax.ForeColor = Color.Black;
            lblMax.BackColor = new Brush {
                Color = new Color {
                    A = 128, R = 255, G = 255, B = 255
                }
            };
            lblMin.BackColor = lblMax.BackColor;
            lblMax.Font      = new Font {
                FontFamily = "Sans Serif", Size = 9
            };
            countryLabelLayer.Styles.Add(new GradientTheme("PopDens", 0, 400, lblMin, lblMax));

            //Lets scale city icons based on city population
            //cities below 1.000.000 gets the smallest symbol, and cities with more than 5.000.000 the largest symbol
            var          citymin  = new SymbolStyle();
            var          citymax  = new SymbolStyle();
            const string iconPath = "Images/icon.png";

            if (!File.Exists(iconPath))
            {
                throw new Exception(
                          String.Format("Error file '{0}' could not be found, make sure it is at the expected location",
                                        iconPath));
            }

            citymin.Symbol = new Bitmap {
                Data = new FileStream(iconPath, FileMode.Open, FileAccess.Read)
            };
            citymin.SymbolScale = 0.5f;
            citymax.Symbol      = new Bitmap {
                Data = new FileStream(iconPath, FileMode.Open, FileAccess.Read)
            };
            citymax.SymbolScale = 1f;
            cityLayer.Styles.Add(new GradientTheme("Population", 1000000, 5000000, citymin, citymax));

            var geodanLayer = new Layer("Geodan");

            geodanLayer.DataSource = new MemoryProvider(new Point(4.9130567, 52.3422033));
            geodanLayer.Styles.Add(new SymbolStyle {
                Symbol = new Bitmap {
                    Data = new FileStream(iconPath, FileMode.Open, FileAccess.Read)
                }
            });
            map.Layers.Add(geodanLayer);

            //limit the zoom to 360 degrees width
            map.BackColor = Color.White;

            return(map);
        }
Exemple #34
0
 /// <summary>
 /// ���þݵ��ע�ļ�
 /// </summary>
 private void LabelLayer()
 {
     LabelLayer layer = new LabelLayer("LabelLayer" + strTempMapPointTable, "LabelLayer" + strTempMapPointTable);
     mapControl1.Map.Layers.Add(layer);
     LabelSource source = new LabelSource(MapInfo.Engine.Session.Current.Catalog.GetTable(strTempMapPointTable));
     source.DefaultLabelProperties.Caption = "Caption";        //��ע�õ����Ǹ��ֶ�����
     source.DefaultLabelProperties.Layout.Offset = 5;
     layer.Sources.Append(source);
 }
 public LayerModel(VectorLayer vectorLayer, LabelLayer labelLayer, LayerRecord layerRecord)
 {
     this.vectorLayer = vectorLayer;
     this.labelLayer  = labelLayer;
     this.layerRecord = layerRecord;
 }