示例#1
1
        public static Map InitializeMap()
        {
            HttpContext context = HttpContext.Current;
            Map map = new Map(new Size(1, 1));
            foreach (string layer in layers.Keys)
            {
                string format = String.Format("~/App_Data/nyc/{0}.shp", layer);
                string path = context.Server.MapPath(format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                LayerData data = layers[layer];
                ShapeFile dataSource = new ShapeFile(path, true) { SRID = 900913 };
                VectorLayer item = new VectorLayer(layer, dataSource)
                {
                    CoordinateTransformation = data.Transformation,
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = SmoothingMode.AntiAlias
                };
                map.Layers.Add(item);

                // LabelLayer labels = CreateLabelLayer(item, data.LabelColumn);
                // map.Layers.Add(labels);
            }
            return map;
        }
        public static async void UpdateVisWithGridEvent(this MapView map, string url, Action<string> error = null)
        {
            await ThreadPool.RunAsync(delegate
            {
                map.Layers.Clear();

                // Create overlay layer for Popups
                Projection projection = map.Options.BaseProjection;
                LocalVectorDataSource source = new LocalVectorDataSource(projection);
                VectorLayer layer = new VectorLayer(source);

                // Create VIS loader
                CartoVisLoader loader = new CartoVisLoader();
                loader.DefaultVectorLayerMode = true;
                CartoVisBuilderWithGridEvent builder = new CartoVisBuilderWithGridEvent(map, layer);

                try
                {
                    loader.LoadVis(builder, url);
                }
                catch (Exception e)
                {
                    if (error != null)
                    {
                        error(e.Message);
                    }
                }

                map.Layers.Add(layer);
            });
        }
示例#3
0
        public static Map OpenLayers()
        {
            ICoordinateTransformation transformation = LatLonToGoogle();
            HttpContext context = HttpContext.Current;
            Map map = new Map(new Size(1, 1));

            IDictionary<string, LayerData> dict = Nyc;
            foreach (string layer in dict.Keys)
            {
                string format = String.Format("~/App_Data/nyc/{0}.shp", layer);
                string path = context.Server.MapPath(format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                LayerData data = dict[layer];
                ShapeFile dataSource = new ShapeFile(path, true) { SRID = 900913 };
                VectorLayer item = new VectorLayer(layer, dataSource)
                {
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = SmoothingMode.AntiAlias,
                    CoordinateTransformation = transformation
                };
                map.Layers.Add(item);
            }
            return map;
        }
        public static async void AddMarkerToPosition(this MapView map, MapPos position)
        {
            await ThreadPool.RunAsync(delegate
            {
                // Initialize a local vector data source
                Projection projection = map.Options.BaseProjection;
                LocalVectorDataSource datasource = new LocalVectorDataSource(projection);

                // Initialize a vector layer with the previous data source
                VectorLayer layer = new VectorLayer(datasource);

                // Add layer to map
                map.Layers.Add(layer);

                MarkerStyleBuilder builder = new MarkerStyleBuilder();
                builder.Size = 15;
                builder.Color = new Carto.Graphics.Color(0, 255, 0, 255);
                
                MarkerStyle style = builder.BuildStyle();

                // Create marker and add it to the source
                Marker marker = new Marker(position, style);
                datasource.Add(marker);
            });
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Add default base layer
            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStyleDefault);

            LocationManager = new LocationManager();
            LocationManager.Start();

            // Create layer and add object to the layer, finally add layer to the map.
            // All overlay layers must be same projection as base layer, so we reuse it
            markerSource = new LocalVectorDataSource(MapView.Options.BaseProjection);
            var _markerLayer = new VectorLayer(markerSource);
            MapView.Layers.Add(_markerLayer);
        }
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStyleDefault);

            // Initialize a local vector data source
            LocalVectorDataSource source = new LocalVectorDataSource(BaseProjection);

            // Initialize a vector layer with the previous data source
            VectorLayer layer = new VectorLayer(source);

            // Add the previous vector layer to the map
            MapView.Layers.Add(layer);
            // Set visible zoom range for the vector layer
            layer.VisibleZoomRange = new MapRange(0, 18);

            // Create marker style
            Android.Graphics.Bitmap image = Android.Graphics.BitmapFactory.DecodeResource(Resources, Resource.Drawable.marker);
            Carto.Graphics.Bitmap markerBitmap = BitmapUtils.CreateBitmapFromAndroidBitmap(image);

            MarkerStyleBuilder builder = new MarkerStyleBuilder();
            builder.Bitmap = markerBitmap;
            builder.Size = 30;
            MarkerStyle style = builder.BuildStyle();

            // Add marker
            MapPos washington = BaseProjection.FromWgs84(new MapPos(-77.0369, 38.9072));
            Marker marker = new Marker(washington, style);
            source.Add(marker);

            // Animate map to the marker
            MapView.SetFocusPos(washington, 1);
            MapView.SetZoom(8, 1);

            listener = new RenderListener();
            MapView.MapRenderer.CaptureRendering(listener, true);
        }
示例#7
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);
    }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "mainGPS" layout resource, reload MapView
            SetContentView(Resource.Layout.MainGPS);
            MapView = (MapView)FindViewById(Resource.Id.mapView);

            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStyleDefault);

            // Create layer and add object to the layer, finally add layer to the map.
            // All overlay layers must be same projection as base layer, so we reuse it
            markerSource = new LocalVectorDataSource(MapView.Options.BaseProjection);
            var markerLayer = new VectorLayer(markerSource);

            MapView.Layers.Add(markerLayer);

            if (((int)Build.VERSION.SdkInt) >= Marshmallow)
            {
                // Ask runtime location permission
                RequestLocationPermission();
            }
            else {
                // Initialize the location manager to get the current position
                InitializeLocationManager();
            }
        }
示例#9
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 PostGIS(Settings.Default.PostGisConnectionString, "countries", "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 shapefile in the App_data folder
            layRivers.DataSource = new PostGIS(Settings.Default.PostGisConnectionString, "rivers", "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 shapefile in the App_data folder
            layCities.DataSource        = new PostGIS(Settings.Default.PostGisConnectionString, "cities", "ogc_fid");
            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",
                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,
                    CollisionDetection  = true,
                    MaxVisible          = 90,
                    MinVisible          = 30
                }
            };

            //Set up a city label layer
            LabelLayer layCityLabel = new LabelLayer("City labels")
            {
                DataSource       = layCities.DataSource,
                Enabled          = true,
                LabelColumn      = "name",
                PriorityColumn   = "population",
                PriorityDelegate = delegate(IFeature fdr)
                {
                    Int32 retVal = 10000000 * (Int32)((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.White,
                    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.Black, 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;
            map.Center = new Coordinate(0, 0);

            Matrix mat = new Matrix();

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

            return(map);
        }
示例#10
0
        private void AddCharts()
        {
            if (CLB_Fields.CheckedItems.Count < 1)
            {
                return;
            }

            VectorLayer aLayer = (VectorLayer)_mapLayer;

            aLayer.ChartSet.ChartType = (ChartTypes)Enum.Parse(typeof(ChartTypes), CB_ChartType.Text);
            List <string> fieldNames = new List <string>();
            int           i, j;

            for (i = 0; i < CLB_Fields.CheckedItems.Count; i++)
            {
                fieldNames.Add(CLB_Fields.CheckedItems[i].ToString());
            }

            aLayer.ChartSet.FieldNames     = fieldNames;
            aLayer.ChartSet.LegendScheme   = legendView_Chart.LegendScheme;
            aLayer.ChartSet.MinSize        = int.Parse(TB_MinSize.Text);
            aLayer.ChartSet.MaxSize        = int.Parse(TB_MaxSize.Text);
            aLayer.ChartSet.BarWidth       = int.Parse(TB_BarWidth.Text);
            aLayer.ChartSet.XShift         = int.Parse(TB_XShift.Text);
            aLayer.ChartSet.YShift         = int.Parse(TB_YShift.Text);
            aLayer.ChartSet.AvoidCollision = CHB_Collision.Checked;
            aLayer.ChartSet.AlignType      = (AlignType)Enum.Parse(typeof(AlignType), CB_Align.Text);
            aLayer.ChartSet.View3D         = CHB_View3D.Checked;
            aLayer.ChartSet.Thickness      = int.Parse(TB_Thickness.Text);

            List <List <float> > values  = new List <List <float> >();
            List <float>         minList = new List <float>();
            List <float>         maxList = new List <float>();
            List <float>         sumList = new List <float>();

            for (i = 0; i < aLayer.ShapeNum; i++)
            {
                List <float> vList = new List <float>();
                float        sum   = 0;
                float        v;
                for (j = 0; j < fieldNames.Count; j++)
                {
                    v = float.Parse(aLayer.GetCellValue(fieldNames[j], i).ToString());
                    vList.Add(v);
                    sum += v;
                }
                values.Add(vList);
                minList.Add(vList.Min());
                maxList.Add(vList.Max());
                sumList.Add(sum);
            }

            switch (aLayer.ChartSet.ChartType)
            {
            case ChartTypes.BarChart:
                aLayer.ChartSet.MinValue = minList.Min();
                aLayer.ChartSet.MaxValue = maxList.Max();
                break;

            case ChartTypes.PieChart:
                aLayer.ChartSet.MinValue = sumList.Min();
                aLayer.ChartSet.MaxValue = sumList.Max();
                break;
            }

            aLayer.AddCharts();
        }
示例#11
0
        protected void Application_Start(object sender, EventArgs e)
        {
            string        settingsfile = Server.MapPath("~/App_Data/settings.xml");
            XmlSerializer serializer   = new XmlSerializer(typeof(SharpMapContext));

            if (!System.IO.File.Exists(settingsfile))
            {
                /*create default settings*/
                SharpMapContext ctx = new SharpMapContext();
                ctx.Capabilities = new WmsCapabilities()
                {
                    Title    = "SharpMap Demo Server",
                    Abstract = "This is an example SharpMap server",
                    Keywords = "SharpMap,WMS"
                };

                ctx.Users = new List <User>();
                ctx.Users.Add(new User {
                    UserName = "******", Password = "******"
                });

                /*add default layer*/
                ctx.Layers = new List <SharpMapServer.Model.WmsLayer>();
                ctx.Layers.Add(new SharpMapServer.Model.WmsLayer()
                {
                    Name = "States", Description = "Demo data over US States", Provider = "Shapefile", DataSource = "states.shp"
                });
                FileStream fs = File.Create(settingsfile);
                serializer.Serialize(fs, ctx);
                fs.Close();
            }

            FileStream settingsStream = File.OpenRead(settingsfile);
            var        settings       = (SharpMapContext)serializer.Deserialize(settingsStream);

            settingsStream.Close();

            WMSServer.m_Capabilities = new SharpMap.Web.Wms.Capabilities.WmsServiceDescription
            {
                Abstract          = settings.Capabilities.Abstract,
                AccessConstraints = settings.Capabilities.AccessConstraints,
                Fees           = settings.Capabilities.Fees,
                Keywords       = settings.Capabilities.Keywords.Split(','),
                LayerLimit     = settings.Capabilities.LayerLimit,
                MaxHeight      = settings.Capabilities.MaxHeight,
                MaxWidth       = settings.Capabilities.MaxWidth,
                OnlineResource = settings.Capabilities.OnlineResource,
                Title          = settings.Capabilities.Title
            };

            WMSServer.m_Map = new SharpMap.Map();
            foreach (var l in settings.Layers)
            {
                switch (l.Provider)
                {
                case "Shapefile":
                    VectorLayer lay = new VectorLayer(l.Name);
                    string      ds  = l.DataSource;
                    if (!Path.IsPathRooted(ds))
                    {
                        ds = Server.MapPath(ds);
                    }

                    lay.DataSource = new SharpMap.Data.Providers.ShapeFile(ds);
                    lay.SRID       = 4326;
                    WMSServer.m_Map.Layers.Add(lay);
                    break;
                }
            }
        }
示例#12
0
        private static Map InitializeMapOrig(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            map.SRID = 4326;

            //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.QuickAccurateCollisionDetectionMethod,
                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);
        }
示例#13
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;

            //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.BackgroundLayer.Add(AsyncLayerProxyLayer.Create(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);
        }
示例#14
0
        public static Map ExportCiml()
        {
            var map    = new Map();
            var layer1 = new VectorLayer("elevation_points", VectorLayer.GEOTYPE_POINT);
            var layer2 = new VectorLayer("contours", VectorLayer.GEOTYPE_LINEAR);
            var layer3 = new VectorLayer("points", VectorLayer.GEOTYPE_POINT);
            var layer4 = new VectorLayer("lines", VectorLayer.GEOTYPE_LINEAR);
            var layer5 = new VectorLayer("regions", VectorLayer.GEOTYPE_REGION);

            var ids = QuickSelection.SelectAll().QWhere(x => x.GetCode() != null).ToList();

            ids.QForEach <Entity>(ent =>
            {
                var code = ent.GetCode();
                var def  = EntityManager.Entities.FirstOrDefault(x => x.Value.EntityCode == code).Value;
                if (def != null)
                {
                    var points = new List <Dreambuild.Geometry.Point2D>();
                    if (ent is BlockReference)
                    {
                        var pos = (ent as BlockReference).Position;
                        points.Add(new Dreambuild.Geometry.Point2D(pos.X, pos.Y));
                    }
                    else if (ent is Polyline)
                    {
                        var pts = (ent as Polyline).GetPoints().ToList();
                        pts.ForEach(pt => points.Add(new Dreambuild.Geometry.Point2D(pt.X, pt.Y)));
                    }
                    else if (ent is Polyline2d)
                    {
                        var poly = new Polyline();
                        poly.ConvertFrom(ent, true);
                        var pts = poly.GetPoints().ToList();
                        pts.ForEach(pt => points.Add(new Dreambuild.Geometry.Point2D(pt.X, pt.Y)));
                    }
                    var feature      = new Feature(points);
                    feature["code"]  = code;
                    feature["name"]  = ent.GetFirstXData(Consts.AppNameForName);
                    feature["layer"] = def.Layer;
                    feature["color"] = def.ColorIndex.ToString();

                    if (def.EntityType == "Block")
                    {
                        feature["block"] = def.BlockName;
                        if (code == "110102" || code == "110202" || code == "110302")
                        {
                            feature["height"] = (ent as BlockReference).GetBlockAttributes()["height"];
                            layer1.Features.Add(feature);
                        }
                        else
                        {
                            layer3.Features.Add(feature);
                        }
                    }
                    else if (def.EntityType == "Line")
                    {
                        feature["linetype"] = def.Linetype;
                        feature["cwidth"]   = def.ConstantWidth.ToString();
                        if (code == "730101" || code == "730102")
                        {
                            feature["height"] = ent.Id.GetData(DictName.CmDrawing, KeyName.Elevation);
                            layer2.Features.Add(feature);
                        }
                        else
                        {
                            layer4.Features.Add(feature);
                        }
                    }
                    else if (def.EntityType == "Region")
                    {
                        feature["linetype"] = def.Linetype;
                        feature["cwidth"]   = def.ConstantWidth.ToString();
                        layer5.Features.Add(feature);
                    }
                }
            });

            map.Layers.AddRange(new List <ILayer> {
                layer1, layer2, layer3, layer4, layer5
            });
            return(map);
        }
        public void ProcessRequest(HttpContext context)
        {
            // tile keys
            int x, y, z;

            //Parse request parameters
            if (!int.TryParse(context.Request.Params["x"], out x))
            {
                throw (new ArgumentException("Invalid parameter"));
            }
            if (!int.TryParse(context.Request.Params["y"], out y))
            {
                throw (new ArgumentException("Invalid parameter"));
            }
            if (!int.TryParse(context.Request.Params["z"], out z))
            {
                throw (new ArgumentException("Invalid parameter"));
            }
            string layer = context.Request.Params["layer"]; // not used here
            string style = context.Request.Params["style"]; // not used here

            // set response type to png
            context.Response.ContentType = "image/png";

            // check if already rendered, rendered tiles are cached within HttpContext
            string cacheKey = string.Format("Tile/{0}/{1}/{2}/{3}/{4}", layer, style, x, y, z);

            byte[] buffer = context.Cache[cacheKey] as byte[];
            if (buffer != null)
            {
                context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                return;
            }

            // create a transparent sharpmap map with a size of 256x256
            using (var sharpMap = new Map(new Size(256, 256))
            {
                BackColor = Color.Transparent
            })
            {
                // the map contains only one layer
                var countries = new VectorLayer("WorldCountries")
                {
                    // set tranform to WGS84->Spherical_Mercator
                    CoordinateTransformation = TransformToMercator(GeographicCoordinateSystem.WGS84),

                    // set the sharpmap provider for shape files as data source
                    DataSource = new ShapeFile(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data") +
                        @"\world_countries_boundary_file_world_2002.shp"),

                    // use a dynamic style for thematic mapping
                    // the lambda also takes the map instance into account (to scale the border width)
                    Theme = new CustomTheme(row => GetPopDensStyle(sharpMap, row)),
                };

                // add the layer to the map
                sharpMap.Layers.Add(countries);

                // calculate the bbox for the tile key and zoom the map
                sharpMap.ZoomToBox(TileToMercatorAtZoom(x, y, z));

                // render the map image
                using (var img = sharpMap.GetMap())
                {
                    // stream the image to the client
                    using (var memoryStream = new MemoryStream())
                    {
                        // Saving a PNG image requires a seekable stream, first save to memory stream
                        // http://forums.asp.net/p/975883/3646110.aspx#1291641
                        img.Save(memoryStream, ImageFormat.Png);
                        buffer = memoryStream.ToArray();

                        // write response
                        context.Response.OutputStream.Write(buffer, 0, buffer.Length);

                        // add to cache
                        context.Cache[cacheKey] = buffer;
                    }
                }
            }
        }
示例#16
0
        public override void OnMouseUp(ICoordinate worldPosition, MouseEventArgs e)
        {
            if (IsMultiSelect)
            {
                StopMultiSelect();
                List <IFeature> selectedFeatures = null;
                if (!KeyExtendSelection)
                {
                    selectedFeatures = new List <IFeature>(FeatureEditors.Select(fe => fe.SourceFeature).ToArray());
                    Clear();
                }
                IPolygon selectionPolygon = CreateSelectionPolygon(worldPosition);
                if (null != selectionPolygon)
                {
                    foreach (ILayer layer in MapHelper.GetAllMapLayers(Map.Layers, false))
                    {
                        if ((!layer.ReadOnly) && (layer is VectorLayer))
                        {
                            // do not use the maptool provider but the datasource of each layer.
                            VectorLayer vectorLayer = (VectorLayer)layer;
                            if (vectorLayer.IsVisible)
                            {
                                IList multiFeatures = vectorLayer.DataSource.GetFeatures(selectionPolygon);
                                for (int i = 0; i < multiFeatures.Count; i++)
                                {
                                    IFeature feature = (IFeature)multiFeatures[i];
                                    if ((null != selectedFeatures) && (selectedFeatures.Contains(feature)))
                                    {
                                        continue;
                                    }
                                    AddSelection(vectorLayer, feature, -1, false);
                                }
                            }
                        }
                    }
                }
                else
                {
                    // if mouse hasn't moved handle as single select. A normal multi select uses the envelope
                    // of the geometry and this has as result that unwanted features will be selected.
                    ILayer   selectedLayer;
                    float    limit   = (float)MapControlHelper.ImageToWorld(Map, 4);
                    IFeature nearest = FindNearestFeature(worldPosition, limit, out selectedLayer, ol => ol.IsVisible);
                    if (null != nearest) //&& (selectedLayer.IsVisible))
                    {
                        AddSelection(selectedLayer, nearest, -1, false);
                    }
                }
                // synchronize with map selection, possible check if selection is already set; do not remove
                UpdateMapControlSelection();
                //MapControl.Refresh();
                //IsMultiSelect = false;
            }
            else
            {
                if ((null != orgMouseDownLocation) && (orgMouseDownLocation.X == worldPosition.X) &&
                    (orgMouseDownLocation.Y == worldPosition.Y) && (e.Button == MouseButtons.Left))
                {
                    // check if mouse was pressed at a selected object without moving the mouse. The default behaviour
                    // should be to select 'the next' object
                    TimeSpan timeSpan = DateTime.Now - orgClickTime;
                    int      dc       = SystemInformation.DoubleClickTime;
                    if (dc < timeSpan.TotalMilliseconds)
                    {
                        if (1 == FeatureEditors.Count)
                        {
                            // check if selection exists; could be toggled
                            Layer    outLayer;
                            IFeature nextFeature = GetNextFeatureAtPosition(worldPosition,
                                                                            // set limit from 4 to 10: TOOLS-1499
                                                                            (float)MapControlHelper.ImageToWorld(Map, 10),
                                                                            out outLayer,
                                                                            FeatureEditors[0].SourceFeature,
                                                                            ol => ol.IsVisible);
                            if (null != nextFeature)
                            {
                                Clear();
                                SetSelection(nextFeature, outLayer, 0); //-1 for ILineString
                                //MapControl.Refresh();
                            }
                        }
                    }
                }
                UpdateMapControlSelection();
            }
            IsBusy       = false;
            orgClickTime = DateTime.Now;

            //for (int i=0; i<FeatureEditors.Count; i++)
            //{
            //    IFeatureEditor featureEditor = FeatureEditors[i];

            //    if (featureEditor.Layer.CustomRenderers.Count > 0)
            //    {
            //        // todo move to IFeatureEditor
            //        featureEditor.Layer.CustomRenderers[0].
            //            UpdateRenderedFeatureGeometry(FeatureEditors[i].SourceFeature, FeatureEditors[i].Layer);
            //        IGeometry g = featureEditor.Layer.CustomRenderers[0].
            //            GetRenderedFeatureGeometry(FeatureEditors[i].SourceFeature, FeatureEditors[i].Layer);
            //        FeatureEditors[i].UpdateTracker(g);
            //    }
            //    //featureEditor.Stop();
            //}
        }
示例#17
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);
        }
示例#18
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);
        }
示例#20
0
        public static Map PolyMaps()
        {            
            HttpContext context = HttpContext.Current;
            Map map = new Map(new Size(1, 1));
            foreach (string layer in layers.Keys)
            {
                string format = String.Format("~/App_Data/nyc/{0}.shp", layer);
                string path = context.Server.MapPath(format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                LayerData data = layers[layer];
                ShapeFile dataSource = new ShapeFile(path, true) { SRID = 4326 };
                VectorLayer item = new VectorLayer(layer, dataSource)
                {                    
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = SmoothingMode.AntiAlias
                };
                map.Layers.Add(item);
            }
            return map;
        }
示例#21
0
        private void tsbJoin_Click(object sender, EventArgs e)
        {
            if (dgvMultiLineString.SelectedRows.Count > 1)
            {
                List <LineStringPriority> priortiesToAdd = new List <LineStringPriority>();
                Dictionary <string, List <LineStringPriority> > binnedPriorities = new Dictionary <string, List <LineStringPriority> >();
                foreach (DataGridViewRow selectedRows in dgvMultiLineString.SelectedRows)
                {
                    string facilityID   = selectedRows.Cells["ID_"].Value.ToString();
                    string lineString   = selectedRows.Cells["LINESTRING"].Value.ToString();
                    string joinPriority = selectedRows.Cells["JOIN_PRIORITY"].Value.ToString();

                    try
                    {
                        LineStringPriority priorityToAdd = new LineStringPriority(lineString, Int32.Parse(joinPriority), facilityID);
                        if (binnedPriorities.ContainsKey(facilityID))
                        {
                            List <LineStringPriority> temp = binnedPriorities[facilityID];
                            temp.Add(priorityToAdd);
                        }
                        else
                        {
                            List <LineStringPriority> toCreate = new List <LineStringPriority>();
                            toCreate.Add(priorityToAdd);
                            binnedPriorities.Add(facilityID, toCreate);
                        }
                    }
                    catch (Exception exc)
                    {
                        Global.WriteOutput("Could not find or create LINESTRING priorities. " + exc.Message);
                    }
                }
                // bNoError is checking to make sure the user has selected at least two linestring
                // values foreach facilityID.  If they havent then the user has made an error.
                bool bNoError = true;
                foreach (string key in binnedPriorities.Keys)
                {
                    List <LineStringPriority> temp = binnedPriorities[key];
                    if (temp.Count < 2)
                    {
                        bNoError = false;
                    }
                }

                if (bNoError)
                {
                    List <string> newLineStrings = new List <string>();
                    List <LineStringPriorityGroup> binnedResults = new List <LineStringPriorityGroup>();
                    foreach (string key in binnedPriorities.Keys)
                    {
                        LineStringPriorityGroup priorityGroup = new LineStringPriorityGroup(binnedPriorities[key]);
                        priorityGroup.SortLineStringList();

                        string newLineString = JoinLineStrings(priorityGroup.sortedLineStrings);
                        newLineStrings.Add(newLineString);

                        priorityGroup.joinedLineString = newLineString;
                        priorityGroup.facilityID       = key;
                        binnedResults.Add(priorityGroup);
                    }



                    // Now loop through the joined linestrings and add a new layer to the map.
                    List <Geometry> geomColl = CreateJoinedLineStringLayer(newLineStrings);
                    PopulateResultGrid(binnedResults);
                    VectorLayer joinedMultiLines = new VectorLayer("JOINEDMLS");
                    joinedMultiLines.DataSource = new GeometryProvider(geomColl);

                    mapImageResults.Map.Layers.Clear();
                    mapImageResults.Map.Layers.Insert(0, joinedMultiLines);
                    mapImageResults.Refresh();
                    mapImageResults.Map.ZoomToExtents();
                }
                else
                {
                    Global.WriteOutput("Error: LINESTRING selection error.  Make sure you have selected at least two linestrings with matching facility ID's. ");
                }
            }
        }
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStyleDefault);

            // Initialize a local vector data source
            LocalVectorDataSource source = new LocalVectorDataSource(BaseProjection);

            // Initialize a vector layer with the previous data source
            VectorLayer layer = new VectorLayer(source);

            // Add the previous vector layer to the map
            MapView.Layers.Add(layer);

            // Create marker style
            Android.Graphics.Bitmap androidMarkerBitmap = Android.Graphics.BitmapFactory.DecodeResource(Resources, Resource.Drawable.marker);
            Carto.Graphics.Bitmap markerBitmap = Carto.Utils.BitmapUtils.CreateBitmapFromAndroidBitmap(androidMarkerBitmap);

            MarkerStyleBuilder markerStyleBuilder = new MarkerStyleBuilder();
            markerStyleBuilder.Bitmap = markerBitmap;
            markerStyleBuilder.Size = 30;
            MarkerStyle markerStyle = markerStyleBuilder.BuildStyle();

            // Add marker
            MapPos berlin = MapView.Options.BaseProjection.FromWgs84(new MapPos(13.38933, 52.51704));
            Marker marker = new Marker(berlin, markerStyle);
            source.Add(marker);

            // Add popup
            PopupStyleBuilder builder = new PopupStyleBuilder();
            builder.SetAttachAnchorPoint(0.5f, 0);
            PopupStyle popupStyle = builder.BuildStyle();

            BasicCustomPopupHandler popupHandler = new BasicCustomPopupHandler("custom popup");

            CustomPopup popup = new CustomPopup(marker, popupStyle, popupHandler);
            popup.SetAnchorPoint(-1, 0);
            source.Add(popup);

            // Animate map to the marker
            MapView.SetFocusPos(berlin, 1);
            MapView.SetZoom(12, 1);
        }
示例#23
0
    public static SharpMap.Map InitializeMap(Size size, string colors, string colorsLine)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

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

        var blackPen       = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
        var blackPen2      = new Pen(Color.FromArgb(255, 0, 0, 0), 2);
        var greenPen       = new Pen(Color.FromArgb(255, 0, 255, 0), 1);
        var greenPenTransp = new Pen(Color.FromArgb(255, 0, 255, 0), 1);

        greenPenTransp.Color = Color.FromArgb(100, greenPenTransp.Color.R, greenPenTransp.Color.G, greenPenTransp.Color.B);
        var redPen            = new Pen(Color.FromArgb(255, 255, 0, 0), 1);
        var bluePen           = new Pen(Color.FromArgb(255, 0, 0, 255), 1);
        var violetPen         = new Pen(Color.FromArgb(255, 255, 0, 255), 1);
        var cyanPen           = new Pen(Color.FromArgb(255, 0, 255, 255), 1);
        var yellowPen         = new Pen(Color.FromArgb(255, 255, 255, 0), 1);
        var darkGrayPen       = new Pen(Color.DarkGray, 1);
        var darkGrayPenTransp = new Pen(Color.DarkGray, 1);

        darkGrayPenTransp.Color = Color.FromArgb(100, darkGrayPenTransp.Color.R, darkGrayPenTransp.Color.G, darkGrayPenTransp.Color.B);
        var lightBluePen            = new Pen(Color.LightBlue, 1);
        var lightGreenPen           = new Pen(Color.LightGreen, 1);
        var lightGrayPen            = new Pen(Color.FromArgb(255, 234, 234, 234));
        var darkGreenPen            = new Pen(Color.DarkGreen);
        var azurePen                = new Pen(Color.DarkKhaki);
        var lightGoldenrodYellowPen = new Pen(Color.LightGoldenrodYellow);

        Dictionary <string, Color> colorFill = new Dictionary <string, Color>();


        if (colors != null)
        {
            colors = colors.Replace(",", "");
            string[] parts = colors.Split('|');

            for (int i = 0; i < parts.Length; i++)
            {
                if (parts[i] != "")
                {
                    string[] pair = parts[i].Split('=');

                    try
                    {
                        colorFill.Add(pair[0], Color.FromName(pair[1]));
                    }
                    catch { }
                }
            }
        }
        else
        {
            colorFill["Lviv"]         = Color.FromArgb(255, 234, 234, 234);
            colorFill["Suburbs2"]     = lightGrayPen.Color;
            colorFill["Parks"]        = darkGreenPen.Color;
            colorFill["Suburbs1"]     = lightGrayPen.Color;
            colorFill["Homes"]        = azurePen.Color;
            colorFill["Proms"]        = darkGrayPen.Color;
            colorFill["FuelStations"] = Color.FromArgb(255, 234, 234, 234);
        }

        Dictionary <string, Color> colorLineDict = new Dictionary <string, Color>();


        if (colors != null)
        {
            colorsLine = colorsLine.Replace(",", "");
            string[] parts = colorsLine.Split('|');

            for (int i = 0; i < parts.Length; i++)
            {
                if (parts[i] != "")
                {
                    string[] pair = parts[i].Split('=');

                    try
                    {
                        colorLineDict.Add(pair[0], Color.FromName(pair[1]));
                    }
                    catch { }
                }
            }
        }
        else
        {
            colorLineDict["Lviv"]         = blackPen.Color;
            colorLineDict["Suburbs2"]     = blackPen.Color;
            colorLineDict["Parks"]        = blackPen.Color;
            colorLineDict["Suburbs1"]     = blackPen.Color;
            colorLineDict["Homes"]        = blackPen.Color;
            colorLineDict["Proms"]        = blackPen.Color;
            colorLineDict["FuelStations"] = blackPen.Color;
        }

        bool town = true;

        if (town)
        {
            var lvivBlockLayer = new VectorLayer("Lviv");
            lvivBlockLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\maps_lviv_new\block.shp"), true);
            lvivBlockLayer.Style.Outline       = new Pen(colorLineDict["Lviv"]);
            lvivBlockLayer.Style.Fill          = new SolidBrush(colorFill["Lviv"]);
            lvivBlockLayer.Style.EnableOutline = true;
            map.Layers.Add(lvivBlockLayer);

            var suburbsLayer2 = new VectorLayer("Suburbs2");
            suburbsLayer2.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(@"~\App_Data\maps_lviv_new\LLSITY12.shp"), true);
            suburbsLayer2.Style.Outline       = new Pen(colorLineDict["Suburbs2"]);
            suburbsLayer2.Style.Fill          = new SolidBrush(colorFill["Suburbs2"]);
            suburbsLayer2.Style.EnableOutline = true;
            map.Layers.Add(suburbsLayer2);

            var parksLayer = new VectorLayer("Parks");
            parksLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(@"~\App_Data\maps_lviv_new\LLVGREN1.shp"),
                true);
            parksLayer.Style.Outline       = new Pen(colorLineDict["Parks"]);
            parksLayer.Style.Fill          = new SolidBrush(colorFill["Parks"]);
            parksLayer.Style.EnableOutline = true;
            map.Layers.Add(parksLayer);

            var suburbsLayer1 = new VectorLayer("Suburbs1");
            suburbsLayer1.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(@"~\App_Data\maps_lviv_new\LLVELL12.shp"),
                true);
            suburbsLayer1.Style.Outline       = new Pen(colorLineDict["Suburbs1"]);
            suburbsLayer1.Style.Fill          = new SolidBrush(colorFill["Suburbs1"]);
            suburbsLayer1.Style.EnableOutline = true;
            map.Layers.Add(suburbsLayer1);

            //homes
            var homesLayer = new VectorLayer("Homes");
            homesLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(@"~\App_Data\maps_lviv_new\LLVHOM12.shp"),
                true);
            homesLayer.Style.Outline       = new Pen(colorLineDict["Homes"]);
            homesLayer.Style.Fill          = new SolidBrush(colorFill["Homes"]);
            homesLayer.Style.EnableOutline = true;
            map.Layers.Add(homesLayer);

            //proms
            var promLayer = new VectorLayer("Proms");
            promLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(@"~\App_Data\maps_lviv_new\LLVPROM.shp"), true);
            promLayer.Style.Outline       = new Pen(colorLineDict["Proms"]);
            promLayer.Style.Fill          = new SolidBrush(colorFill["Proms"]);
            promLayer.Style.EnableOutline = true;
            map.Layers.Add(promLayer);

            VectorLayer fuelStationLayer = new VectorLayer("FuelStations");
            fuelStationLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\FuelStationsLayers\LvivCityCorr\fuel_stations_lviv.shp"),
                true);
            fuelStationLayer.Style.Outline       = new Pen(colorLineDict["FuelStations"]);
            fuelStationLayer.Style.Fill          = new SolidBrush(colorFill["FuelStations"]);
            fuelStationLayer.Style.EnableOutline = true;
            //fuelStationLayer.Style.PointColor = Brushes.AliceBlue;
            SharpMap.Rendering.Thematics.CustomTheme myTheme = new SharpMap.Rendering.Thematics.CustomTheme(GetFullStationStyle);
            fuelStationLayer.Theme = myTheme;
            map.Layers.Add(fuelStationLayer);

            //var tmp6 = new VectorLayer("Lviv"){DataSource = new ShapeFile(HttpContext.Current.Server.MapPath(@"~\App_Data\maps_lviv_new\LROAD12.shp"), true)};
            //tmp6.Style.Outline = waPen6;
            //tmp6.Style.Fill = new SolidBrush(Color.FromArgb(255, 234, 234, 234));
            //tmp6.Style.EnableOutline = true;
            //map.Layers.Add(tmp6);
        }
        else
        {
            var lvivRegioonLayer = new VectorLayer("Region");
            lvivRegioonLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\Lviv_Region_Romik\lv_line.shp"), true);
            lvivRegioonLayer.Style.Outline       = blackPen2;
            lvivRegioonLayer.Style.Fill          = new SolidBrush(Color.FromArgb(255, 234, 234, 234));
            lvivRegioonLayer.Style.EnableOutline = true;
            map.Layers.Add(lvivRegioonLayer);

            var territoryLayer = new VectorLayer("Regions");
            territoryLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\Lviv_Region_Romik\terrytor.shp"), true);
            territoryLayer.Style.Outline       = darkGrayPenTransp;
            territoryLayer.Style.Fill          = new SolidBrush(lightGoldenrodYellowPen.Color);
            territoryLayer.Style.EnableOutline = true;
            map.Layers.Add(territoryLayer);

            var lakesLayer = new VectorLayer("Lakes");
            lakesLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\Lviv_Region_Romik\vodoimy.shp"), true);
            lakesLayer.Style.Outline       = blackPen;
            lakesLayer.Style.Fill          = new SolidBrush(bluePen.Color);
            lakesLayer.Style.EnableOutline = true;
            map.Layers.Add(lakesLayer);

            var punkLayer = new VectorLayer("Punks");
            punkLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\Lviv_Region_Romik\nas_punk.shp"), true);
            punkLayer.Style.Outline       = blackPen;
            punkLayer.Style.Fill          = new SolidBrush(darkGrayPen.Color);
            punkLayer.Style.EnableOutline = true;
            map.Layers.Add(punkLayer);

            var railsLayer = new VectorLayer("Rails");
            railsLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\Lviv_Region_Romik\zal_kol.shp"), true);
            //map.Layers.Add(railsLayer);

            var fuelStationLayer = new VectorLayer("FuelStations");
            fuelStationLayer.DataSource = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\FuelStationsLayers\LvivObl\fuel_stations.shp"),
                true);
            fuelStationLayer.Style.PointColor = Brushes.AliceBlue;
            map.Layers.Add(fuelStationLayer);

            var roadsLayer = new VectorLayer("Roads");
            roadsLayer.Style.Outline = blackPen;
            roadsLayer.DataSource    = new ShapeFile(
                HttpContext.Current.Server.MapPath(
                    @"~\App_Data\Lviv_Region_Romik\meregi.shp"), true);
            map.Layers.Add(roadsLayer);
        }

        GeoAPI.Geometries.Envelope mapExtents = map.GetExtents();
        //SharpMap.Geometries.BoundingBox mapExtents = map.GetExtents();
        map.Zoom        = mapExtents.Width;
        map.MaximumZoom = mapExtents.Width;
        map.MinimumZoom = 2000;
        map.Center      = mapExtents.Centre;
        map.BackColor   = Color.White;
        map.ZoomToExtents();

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
示例#24
0
 private void RemoveDrawingLayer()
 {
     newLineLayer = null;
 }
示例#25
0
        public async Task <Measurement> StartMeasurement(Geometry geometry, Measurement measurement, bool sketch, long?objectId, VectorLayer vectorLayer)
        {
            if (GlobeSpotterConfiguration.MeasurePermissions)
            {
                bool measurementExists          = false;
                ArcGISGeometryType geometryType = geometry?.GeometryType ?? ArcGISGeometryType.Unknown;

                if (geometryType == ArcGISGeometryType.Point || geometryType == ArcGISGeometryType.Polygon ||
                    geometryType == ArcGISGeometryType.Polyline)
                {
                    if (measurement?.IsGeometryType(geometryType) ?? false)
                    {
                        measurementExists = true;
                        measurement.OpenMeasurement();
                    }
                    else
                    {
                        measurement?.RemoveMeasurement();
                    }

                    if (!measurementExists)
                    {
                        CloseOpenMeasurement();
                        _lastObjectId    = objectId;
                        _lastVectorLayer = vectorLayer;
                        _lastSketch      = sketch;
                        await CreateMeasurement(geometryType);
                    }
                }
            }

            return(measurement);
        }
        public static void Update(this MapView MapView, bool withListener, byte[] data, Action completed, Action <string> failed = null)
        {
            System.Threading.Tasks.Task.Run(delegate
            {
                var sourceId = Parser.GetSourceFromData(data);

                BinaryData styleAsset = new BinaryData(data);

                var package  = new ZippedAssetPackage(styleAsset);
                var styleSet = new CompiledStyleSet(package);

                // UWP doesn't have a version released where simply changing the style set is supported,
                // need to clear layers and recreate the entire thing
#if __UWP__
                MapView.Layers.Clear();

                var source  = new CartoOnlineTileDataSource(OSM);
                var decoder = new MBVectorTileDecoder(styleSet);

                var layer = new VectorTileLayer(source, decoder);
                Device.BeginInvokeOnMainThread(delegate
                {
                    MapView.Layers.Add(layer);
                    if (completed != null)
                    {
                        completed();
                    }
                });
#else
                if (MapView.Layers.Count == 0)
                {
                    if (sourceId == null)
                    {
                        sourceId = DefaultSourceId;
                    }

                    var source = new CartoOnlineTileDataSource(sourceId);

                    MBVectorTileDecoder decoder = null;

                    try
                    {
                        decoder = new MBVectorTileDecoder(styleSet);
                    }
                    catch (System.ApplicationException e)
                    {
                        if (failed != null)
                        {
                            failed(e.Message);
                            return;
                        }
                    }

                    var layer = new VectorTileLayer(source, decoder);

                    if (withListener)
                    {
                        var popupSource = new LocalVectorDataSource(MapView.Options.BaseProjection);
                        var popupLayer  = new VectorLayer(popupSource);
                        MapView.Layers.Add(popupLayer);
                        layer.VectorTileEventListener = new VectorEventListener(popupSource);
                    }

                    Device.BeginInvokeOnMainThread(delegate
                    {
                        MapView.Layers.Add(layer);
                        if (completed != null)
                        {
                            completed();
                        }
                    });
                }
                else
                {
                    var decoder = (MBVectorTileDecoder)(MapView.Layers[MapView.Layers.Count - 1] as VectorTileLayer).TileDecoder;

                    Device.BeginInvokeOnMainThread(delegate
                    {
                        decoder.CompiledStyle = styleSet;

                        if (completed != null)
                        {
                            completed();
                        }
                    });
                }
#endif
            });
        }
示例#27
0
 public EntradaLeyendaInformacion(string uid, VectorLayer capa, string titulo)
     : base(uid, capa, titulo)
 {
 }
示例#28
0
        /// <summary>
        ///     Gets the current map.
        /// </summary>
        /// <returns>The map.</returns>
        private SharpMap.Map GetMap()
        {
            var map = new SharpMap.Map(new Size(1, 1))
            {
                BackColor = Color.FromArgb(255, 246, 243, 236)
            };
            var disclaimer = new Disclaimer
            {
                Font   = new Font("Arial", 7f, FontStyle.Italic),
                Text   = "Geodata from OpenStreetMap (CC-by-SA)\nTransformed to Shapefile by geofabrik.de",
                Anchor = MapDecorationAnchor.CenterBottom
            };

            map.Decorations.Add(disclaimer);
            var encoding         = Encoding.UTF8;
            var transparentStyle = new VectorStyle
            {
                Fill          = Brushes.Transparent,
                EnableOutline = true,
                Line          = { Brush = Brushes.Transparent },
                Outline       = { Brush = Brushes.Transparent },
                Symbol        = null
            };

            #region cuba

            var cubaLayer = new VectorLayer("cuba",
                                            new ShapeFile(Path.Combine(ShapeDir, "admin.shp"), true, false, 4326)
            {
                Encoding = encoding
            })
            {
                Style = new VectorStyle
                {
                    EnableOutline = true,
                    Fill          = Brushes.FloralWhite
                },
                SmoothingMode   = SmoothingMode.AntiAlias,
                ClippingEnabled = true
            };
            map.Layers.Add(cubaLayer);

            #endregion

            #region landuse layer

            var landuseStyle = transparentStyle.Clone();
            landuseStyle.Fill = new SolidBrush(Color.FromArgb(255, 246, 243, 236));
            var landuseLayer = new VectorLayer("landuse",
                                               new ShapeFile(Path.Combine(ShapeDir, "gis.osm_landuse_a_free_1.shp"), true, false, 4326)
            {
                Encoding = encoding
            })
            {
                Style           = landuseStyle,
                SmoothingMode   = SmoothingMode.AntiAlias,
                ClippingEnabled = true
            };
            var landuseTheme = new CustomTheme(row =>
            {
                var caseVal     = (string)row["fclass"];
                caseVal         = caseVal.ToLowerInvariant();
                var returnStyle = landuseStyle.Clone();

                switch (caseVal)
                {
                case "forest":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 221, 230, 213));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 221, 230, 213));
                    break;

                case "park":
                case "grass":
                case "national_park":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 200, 225, 175));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 200, 225, 175));
                    break;

                case "residential":
                case "commercial":
                case "retail":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 231, 227, 216));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 231, 227, 216));
                    break;

                case "industrial":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 221, 216, 210));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 221, 216, 210));
                    break;

                case "military":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 221, 220, 215));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 221, 220, 215));
                    break;

                case "wood":
                case "nature_reserve":
                case "farm":
                case "cemetery":
                case "water":
                case "riverbank":
                case "allotments":
                case "meadow":
                case "recreation_ground":
                case "quarry":
                case "orchard":
                case "vineyard":
                case "heath":
                case "scrub":
                    returnStyle = null;
                    break;

                default:
                    returnStyle = null;
                    break;
                }
                return(returnStyle);
            });
            landuseLayer.Theme = landuseTheme;
            map.Layers.Add(landuseLayer);

            #endregion

            #region road layer

            var roadsLayer = new VectorLayer("roads",
                                             new ShapeFile(Path.Combine(ShapeDir, "gis.osm_roads_free_1.shp"), true, false, 4326)
            {
                Encoding = encoding
            })
            {
                SmoothingMode   = SmoothingMode.AntiAlias,
                ClippingEnabled = true,
                Style           = transparentStyle
            };
            roadsLayer.DataSource.Open();
            var roadsExtents = roadsLayer.DataSource.GetExtents();
            var themeRoads   = new CustomTheme(row =>
            {
                var returnStyle = new VectorStyle
                {
                    Line          = new Pen(new SolidBrush(Color.FromArgb(255, 240, 240, 160))),
                    EnableOutline = true,
                    Outline       = new Pen(new SolidBrush(Color.Black), 1)
                };

                switch ((string)row["fclass"])
                {
                case "rail":
                    returnStyle.Fill             = Brushes.White;
                    returnStyle.Line.DashPattern = new[] { 4f, 4f };
                    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.025d;
                    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.075d;
                    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.15d;
                    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.3d;
                    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.0125d;
                    break;

                default:
                    returnStyle = null;
                    break;
                }
                return(returnStyle);
            });
            roadsLayer.Theme = themeRoads;
            map.Layers.Add(roadsLayer);

            #endregion

            #region water layer

            var waterLayer = new VectorLayer("water",
                                             new ShapeFile(Path.Combine(ShapeDir, "gis.osm_water_a_free_1.shp"), true, false, 4326)
            {
                Encoding = encoding
            })
            {
                Style           = transparentStyle.Clone(),
                SmoothingMode   = SmoothingMode.AntiAlias,
                ClippingEnabled = true
            };
            waterLayer.DataSource.Open();
            var waterExtents = waterLayer.DataSource.GetExtents();
            var waterTheme   = new CustomTheme(row =>
            {
                var returnStyle = new VectorStyle
                {
                    EnableOutline = true,
                    MaxVisible    = waterExtents.Width * 0.05
                };
                switch ((string)row["fclass"])
                {
                case "water":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 165, 190, 220));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 165, 190, 220));
                    break;

                case "river":
                    returnStyle.Fill          = new SolidBrush(Color.FromArgb(255, 165, 190, 220));
                    returnStyle.Outline.Brush = new SolidBrush(Color.FromArgb(255, 165, 190, 220));
                    returnStyle.Outline.Width = 2;
                    break;

                default:
                    returnStyle = null;
                    break;
                }
                return(returnStyle);
            });
            waterLayer.Theme = waterTheme;
            map.Layers.Add(waterLayer);

            #endregion

            #region waterways layer

            var waterwaysLayer = new VectorLayer("waterways",
                                                 new ShapeFile(Path.Combine(ShapeDir, "gis.osm_waterways_free_1.shp"), true, false, 4326)
            {
                Encoding = encoding
            })
            {
                Style           = transparentStyle.Clone(),
                SmoothingMode   = SmoothingMode.AntiAlias,
                ClippingEnabled = true
            };
            waterwaysLayer.DataSource.Open();
            var waterwaysExtents = waterwaysLayer.DataSource.GetExtents();
            var waterwaysTheme   = new CustomTheme(row =>
            {
                var returnStyle = new VectorStyle
                {
                    EnableOutline = false,
                    MaxVisible    = waterwaysExtents.Width * 0.05
                };
                switch ((string)row["fclass"])
                {
                case "river":
                    returnStyle.Line.Brush = new SolidBrush(Color.FromArgb(255, 165, 190, 220));
                    returnStyle.Line.Width = 2;
                    break;

                default:
                    returnStyle = null;
                    break;
                }
                return(returnStyle);
            });
            waterwaysLayer.Theme = waterwaysTheme;
            map.Layers.Add(waterwaysLayer);

            #endregion

            #region points

            var pointsLayer = new VectorLayer("points",
                                              new ShapeFile(Path.Combine(ShapeDir, "gis.osm_pois_free_1.shp"), true, false, 4326)
            {
                Encoding = encoding
            })
            {
                Style = transparentStyle.Clone()
            };
            pointsLayer.DataSource.Open();
            var pointsExtents = pointsLayer.DataSource.GetExtents();
            var pointsTheme   = new CustomTheme(row =>
            {
                var returnStyle = new VectorStyle
                {
                    SymbolScale = 0.3f,
                    MaxVisible  = pointsExtents.Width * 0.0125d
                };
                switch ((string)row["fclass"])
                {
                case "bank":
                    returnStyle.Symbol = GetBitmap("bank");
                    break;

                case "hospital":
                    returnStyle.Symbol = GetBitmap("hospital-o");
                    break;

                case "bar":
                    returnStyle.Symbol = GetBitmap("beer");
                    break;

                case "embassy":
                    returnStyle.Symbol = GetBitmap("town");
                    break;

                case "parking":
                    returnStyle.Symbol = GetBitmap("parking");
                    break;

                case "pub":
                    returnStyle.Symbol = GetBitmap("restaurant");
                    break;

                case "cinema":
                    returnStyle.Symbol = GetBitmap("cinema");
                    break;

                case "zoo":
                    returnStyle.Symbol = GetBitmap("zoo");
                    break;

                case "theatre":
                    returnStyle.Symbol = GetBitmap("theatre");
                    break;

                case "monument":
                case "memorial":
                    returnStyle.Symbol = GetBitmap("monument");
                    break;

                case "restaurant":
                    returnStyle.Symbol = GetBitmap("restaurant");
                    break;

                case "sport":
                    returnStyle.Symbol = GetBitmap("pitch");
                    break;

                case "airport":
                    returnStyle.Symbol = GetBitmap("airport");
                    break;

                case "college":
                case "university":
                    returnStyle.Symbol = GetBitmap("college");
                    break;

                case "cafe":
                    returnStyle.Symbol = GetBitmap("cafe");
                    break;

                case "fire":
                    returnStyle.Symbol = GetBitmap("fire");
                    break;

                case "police":
                    returnStyle.Symbol = GetBitmap("police");
                    break;

                case "fuel":
                    returnStyle.Symbol = GetBitmap("fuel");
                    break;

                case "nightclub":
                    returnStyle.Symbol = GetBitmap("music");
                    break;

                case "museum":
                    returnStyle.Symbol = GetBitmap("museum");
                    break;

                case "hotel":
                case "hostel":
                case "guesthouse":
                    returnStyle.Symbol = GetBitmap("hotel");
                    break;

                case "fast_food":
                    returnStyle.Symbol = GetBitmap("food");
                    break;

                case "pharmacy":
                    returnStyle.Symbol = GetBitmap("pharmacy");
                    break;

                default:
                    returnStyle.Symbol = GetBitmap("map-marker");
                    break;
                }
                return(returnStyle);
            });
            pointsLayer.Theme = pointsTheme;
            map.Layers.Add(pointsLayer);

            #endregion

            return(map);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            AddBaseLayer(CartoBaseMapStyle.CartoBasemapStyleDefault);

            // Create PackageManager instance for dealing with offline packages
            string folder = Utils.GetDocumentDirectory("routingpackages");

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
                Console.WriteLine("Directory: Does not exist... Creating");
            }
            else
            {
                Console.WriteLine("Directory: Exists");
            }

            packageManager  = new CartoPackageManager(ROUTING_PACKAGEMANAGER_SOURCE, folder);
            PackageListener = new RoutingPackageListener(packageManager, downloadablePackages);

            packageManager.PackageManagerListener = PackageListener;

            // Fetch list of available packages from server.
            // Note that this is asynchronous operation
            // and listener will be notified via onPackageListUpdated when this succeeds.
            packageManager.StartPackageListDownload();

            // Create offline routing service connected to package manager
            offlineRoutingService = new PackageManagerRoutingService(packageManager);

            // Create additional online routing service that will be used
            // when offline package is not yet downloaded or offline routing fails
            onlineRoutingService = new CartoOnlineRoutingService(ROUTING_SERVICE_SOURCE);

            // Define layer and datasource for route line and instructions
            routeDataSource = new LocalVectorDataSource(BaseProjection);
            VectorLayer routeLayer = new VectorLayer(routeDataSource);

            MapView.Layers.Add(routeLayer);

            // Define layer and datasource for route start and stop markers
            routeStartStopDataSource = new LocalVectorDataSource(BaseProjection);

            // Initialize a vector layer with the previous data source
            VectorLayer vectorLayer = new VectorLayer(routeStartStopDataSource);

            // Add the previous vector layer to the map
            MapView.Layers.Add(vectorLayer);

            // Set visible zoom range for the vector layer
            vectorLayer.VisibleZoomRange = new MapRange(0, 22);

            MapListener = new RouteMapEventListener();
            MapView.MapEventListener = MapListener;

            // Create markers for start & end, and a layer for them
            MarkerStyleBuilder markerStyleBuilder = new MarkerStyleBuilder();

            markerStyleBuilder.Bitmap           = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/olmarker.png"));
            markerStyleBuilder.HideIfOverlapped = false;
            markerStyleBuilder.Size             = 30;

            markerStyleBuilder.Color = new Carto.Graphics.Color(0, 255, 0, 255);

            startMarker         = new Marker(new MapPos(0, 0), markerStyleBuilder.BuildStyle());
            startMarker.Visible = false;

            markerStyleBuilder.Color = new Carto.Graphics.Color(255, 0, 0, 255);

            stopMarker         = new Marker(new MapPos(0, 0), markerStyleBuilder.BuildStyle());
            stopMarker.Visible = false;

            routeStartStopDataSource.Add(startMarker);
            routeStartStopDataSource.Add(stopMarker);

            markerStyleBuilder.Color  = new Carto.Graphics.Color(255, 255, 255, 255);
            markerStyleBuilder.Bitmap = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/direction_up.png"));
            instructionUp             = markerStyleBuilder.BuildStyle();

            markerStyleBuilder.Bitmap = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/direction_upthenleft.png"));
            instructionLeft           = markerStyleBuilder.BuildStyle();

            markerStyleBuilder.Bitmap = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/direction_upthenright.png"));

            instructionRight = markerStyleBuilder.BuildStyle();

            // Style for instruction balloons
            balloonPopupStyleBuilder = new BalloonPopupStyleBuilder();
            balloonPopupStyleBuilder.TitleMargins = new BalloonPopupMargins(4, 4, 4, 4);

            // Finally animate map to Estonia
            MapView.FocusPos = BaseProjection.FromWgs84(new MapPos(25.662893, 58.919365));
            MapView.Zoom     = 7;

            Alert("Long-press on map to set route start and finish");
        }
示例#30
0
        void SetupMap()
        {
            try
            {
                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);
            }
            catch (Exception) { }
        }
示例#31
0
        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;
        }
示例#32
0
        private void Initialize()
        {
            PG_General.SelectedObject = _mapLayer.GetPropertyObject();
            TabControl_Prop.TabPages.Clear();
            TabControl_Prop.TabPages.Add(TabPage_General);
            switch (_mapLayer.LayerType)
            {
            case LayerTypes.VectorLayer:
            case LayerTypes.RasterLayer:
                TabControl_Prop.TabPages.Add(TabPage_Legend);
                _legendScheme = (LegendScheme)_mapLayer.LegendScheme.Clone();
                legendSchemeControl1.Update(_mapLayer, _mapLayer.LegendScheme);
                break;

            case LayerTypes.ImageLayer:

                break;
            }

            if (_mapLayer.LayerType == LayerTypes.VectorLayer)
            {
                switch (_mapLayer.ShapeType)
                {
                case ShapeTypes.Point:
                case ShapeTypes.PointZ:
                case ShapeTypes.Polygon:
                    TabControl_Prop.TabPages.Add(TabPage_Chart);
                    VectorLayer aLayer = (VectorLayer)_mapLayer;
                    if (_mapLayer.ShapeType == ShapeTypes.Polygon)
                    {
                        CB_ChartType.Items.Clear();
                        CB_ChartType.Items.Add(ChartTypes.BarChart.ToString());
                        CB_ChartType.Items.Add(ChartTypes.PieChart.ToString());
                    }
                    else
                    {
                        CB_ChartType.Items.Clear();
                        CB_ChartType.Items.Add(ChartTypes.BarChart.ToString());
                        CB_ChartType.Items.Add(ChartTypes.PieChart.ToString());
                        //CB_ChartType.Items.Add(ChartTypes.WindVector.ToString());
                        //CB_ChartType.Items.Add(ChartTypes.WindBarb.ToString());
                        //CB_ChartType.Items.Add(ChartTypes.StationModel.ToString());
                    }
                    CB_ChartType.Text = aLayer.ChartSet.ChartType.ToString();

                    //Add fields
                    CLB_Fields.Items.Clear();
                    for (int i = 0; i < aLayer.NumFields; i++)
                    {
                        if (MIMath.IsNumeric(aLayer.GetField(i)))
                        {
                            string fn = aLayer.GetFieldName(i);
                            CLB_Fields.Items.Add(fn);
                            if (aLayer.ChartSet.FieldNames.Contains(fn))
                            {
                                CLB_Fields.SetItemChecked(CLB_Fields.Items.Count - 1, true);
                            }
                        }
                    }

                    TB_BarWidth.Text      = aLayer.ChartSet.BarWidth.ToString();
                    TB_MaxSize.Text       = aLayer.ChartSet.MaxSize.ToString();
                    TB_MinSize.Text       = aLayer.ChartSet.MinSize.ToString();
                    TB_XShift.Text        = aLayer.ChartSet.XShift.ToString();
                    TB_YShift.Text        = aLayer.ChartSet.YShift.ToString();
                    CHB_Collision.Checked = aLayer.ChartSet.AvoidCollision;
                    //Set align type
                    CB_Align.Items.Clear();
                    foreach (string align in Enum.GetNames(typeof(AlignType)))
                    {
                        CB_Align.Items.Add(align);
                    }
                    CB_Align.Text      = aLayer.ChartSet.AlignType.ToString();
                    CHB_View3D.Checked = aLayer.ChartSet.View3D;
                    TB_Thickness.Text  = aLayer.ChartSet.Thickness.ToString();

                    legendView_Chart.LegendScheme = aLayer.ChartSet.LegendScheme;
                    break;
                }
            }
        }
示例#33
0
        public virtual void SetData(VectorLayer layer)
        {
            LayerData       = layer;
            LayerStyle      = GetLayerStyle(layer);
            LayerLableStyle = GetLabelStyle(layer);
            Features.Clear();
            Overlays.Clear();
            Children.Clear();
            LabelLayer = new MapLayer();

            if (layer.GeoType == VectorLayer.GEOTYPE_POINT)
            {
                foreach (Feature feature in layer.Features)
                {
                    var pos = feature.GeoData[0];
                    AddSpot(new Point(pos.X, pos.Y), feature);
                    AddLable(new Point(pos.X, pos.Y), LayerLableStyle.GetLable(feature));
                }
            }
            else if (layer.GeoType == VectorLayer.GEOTYPE_LINEAR)
            {
                if (IsRoad())
                {
                    foreach (Feature feature in layer.Features)
                    {
                        var polyline = new PointString(feature.GeoData);
                        AddRoadStroke(polyline.Points.Select(p => new Point(p.X, p.Y)).ToArray(), feature);
                    }
                }
                foreach (Feature feature in layer.Features)
                {
                    var poly = new PointString(feature.GeoData);
                    if (!IsRoad())
                    {
                        AddPolyline(poly.Points.Select(p => new Point(p.X, p.Y)).ToArray(), feature);
                    }
                    else
                    {
                        AddRoadFill(poly.Points.Select(p => new Point(p.X, p.Y)).ToArray(), feature);
                    }
                }
                foreach (Feature feature in layer.Features) // mod 20130516 最后统一加标签
                {
                    var    poly = new PointString(feature.GeoData);
                    string text = LayerLableStyle.GetLable(feature);
                    double linearRepeatInterval = LayerLableStyle.LinearRepeatInterval;
                    double length = poly.Length();
                    //double scale = 4;  // 这个时候出现主窗口的Scale是不合适的。
                    List <double> positions = new List <double>(); // mod 20130528 与SVG同步
                    if (length > 0 && length < 2 * linearRepeatInterval)
                    {
                        positions.Add(length / 2);
                    }
                    else
                    {
                        int index = 1;
                        while (index * linearRepeatInterval < length)
                        {
                            positions.Add(index * linearRepeatInterval);
                            index++;
                        }
                    }
                    foreach (double position in positions)
                    {
                        var    tempPt   = poly.GetPointAtDist(position);
                        double rotation = poly.Dir(position).Heading();
                        double angle    = 180 / Math.PI * rotation;
                        AddLable(new Point(tempPt.X, tempPt.Y), text, angle);
                    }
                }
            }
            else if (layer.GeoType == VectorLayer.GEOTYPE_REGION)
            {
                foreach (Feature feature in layer.Features)
                {
                    var poly   = new PointString(feature.GeoData);
                    var center = poly.Centroid();
                    AddPolygon(poly.Points.Select(p => new Point(p.X, p.Y)).ToArray(), feature);
                    AddLable(new Point(center.X, center.Y), LayerLableStyle.GetLable(feature));
                }
            }
        }
示例#34
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);
    }
示例#35
0
        public static void AddOverlyingLines(MapView map, LocalVectorDataSource source, Projection projection)
        {
            // Initialize a second vector data source and vector layer
            // This secondary vector layer will be used for drawing borders for
            // line elements (by drawing the same line twice, with different widths)
            // Drawing order withing a layer is currently undefined
            // Using multiple layers is the only way to guarantee
            // that point, line and polygon elements are drawn in a specific order
            LocalVectorDataSource source2 = new LocalVectorDataSource(projection);
            VectorLayer vectorLayer2 = new VectorLayer(source2);
            map.Layers.Add(vectorLayer2);

            vectorLayer2.VisibleZoomRange = new MapRange(10, 24);

            // Create line style, and line poses
            LineStyleBuilder lineStyleBuilder = new LineStyleBuilder();
            lineStyleBuilder.Color = new Color(255, 255, 255, 255); // White
            lineStyleBuilder.Width = 8;

            MapPosVector linePoses = new MapPosVector();

            linePoses.Add(projection.FromWgs84(new MapPos(24.645565, 59.422074)));
            linePoses.Add(projection.FromWgs84(new MapPos(24.643076, 59.420502)));
            linePoses.Add(projection.FromWgs84(new MapPos(24.645351, 59.419149)));
            linePoses.Add(projection.FromWgs84(new MapPos(24.648956, 59.420393)));
            linePoses.Add(projection.FromWgs84(new MapPos(24.650887, 59.422707)));

            // Add first line
            Line line1 = new Line(linePoses, lineStyleBuilder.BuildStyle());
            line1.SetMetaDataElement("ClickText", new Variant("Line nr 1"));
            source2.Add(line1);

            // Create another line style, use the same lines poses
            lineStyleBuilder = new LineStyleBuilder();
            lineStyleBuilder.Color = new Color(204, 15, 0, 255);
            lineStyleBuilder.Width = 12;

            // Add second line to the second layer.
            Line line2 = new Line(linePoses, lineStyleBuilder.BuildStyle());
            line2.SetMetaDataElement("ClickText", new Variant("Line nr 2"));
            source.Add(line2);
        }
示例#36
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;
 }
示例#37
0
        private static Map InitializeS57(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set the datasource to a shapefile in the App_data folder
            Ogr provider;

            try
            {
                provider = new Ogr("GeoData/S57/US5TX51M.000");
            }
            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;
            }

            VectorLayer lay;
            Random      rnd = new Random(9);

            for (Int32 i = provider.NumberOfLayers - 1; i >= 0; i--)
            {
                Ogr prov = new Ogr("GeoData/S57/US5TX51M.000", i);
                if (!prov.IsFeatureDataLayer)
                {
                    continue;
                }
                string name = prov.LayerName;
                System.Diagnostics.Debug.WriteLine(string.Format("Layer {0}: {1}", i, name));
                //if (provider.GeometryType )
                lay = new VectorLayer(string.Format("Layer_{0}", name), prov);
                if (prov.OgrGeometryTypeString.IndexOf("Polygon") > 0)
                {
                    lay.Style.Fill =
                        new SolidBrush(Color.FromArgb(150, Convert.ToInt32(rnd.NextDouble() * 255),
                                                      Convert.ToInt32(rnd.NextDouble() * 255),
                                                      Convert.ToInt32(rnd.NextDouble() * 255)));
                    lay.Style.Outline =
                        new Pen(
                            Color.FromArgb(150, Convert.ToInt32(rnd.NextDouble() * 255),
                                           Convert.ToInt32(rnd.NextDouble() * 255),
                                           Convert.ToInt32(rnd.NextDouble() * 255)),
                            Convert.ToInt32(rnd.NextDouble() * 3));
                    lay.Style.EnableOutline = true;
                }
                else
                {
                    lay.Style.Line =
                        new Pen(
                            Color.FromArgb(150, Convert.ToInt32(rnd.NextDouble() * 255),
                                           Convert.ToInt32(rnd.NextDouble() * 255), Convert.ToInt32(rnd.NextDouble() * 255)),
                            Convert.ToInt32(rnd.NextDouble() * 3));
                }
                map.Layers.Add(lay);
            }
            _ogrSampleDataset = "S-57";
            map.ZoomToExtents();

            Matrix mat = new Matrix();

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

            return(map);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStyleGray);

            Projection projection = BaseProjection;

            // Initialize an local vector data source
            LocalVectorDataSource source = new LocalVectorDataSource(projection);

            // Initialize a vector layer with the previous data source
            VectorLayer vectorLayer = new VectorLayer(source);

            // Add the previous vector layer to the map
            MapView.Layers.Add(vectorLayer);

            // Set visible zoom range for the vector layer
            vectorLayer.VisibleZoomRange = new MapRange(10, 24);

            // Add a bunch of vector elements
            // As elements can be shared across platforms, they are in a shared project

            Overlays.AddPoint1(source, projection);
            Overlays.AddPoint2(source, projection);

            Overlays.AddOverlyingLines(MapView, source, projection);

            Overlays.Add2DPolygon(source, projection);

            Overlays.AddText1(source, projection);
            Overlays.AddText2(source, projection);
            Overlays.AddText3(source, projection);

            Bitmap info = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/info.png"));
            Bitmap arrow = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/arrow.png"));
            Bitmap marker = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/marker.png"));

            Overlays.AddBalloonPopup1(source, projection, info, arrow);
            Overlays.AddBalloonPopup2(source, projection, info, arrow, marker);
            Overlays.AddBalloonPopup3(source, projection);

            Overlays.Add3DCar(source, projection);
            Overlays.Add3DPolygon(source, projection);

            // Animate map to Tallinn where the objects are
            MapView.SetFocusPos(projection.FromWgs84(new MapPos(24.662893, 59.419365)), 1);
            MapView.SetZoom(12, 1);

            // Add maplistener to detect click on model

            listener = new VectorElementListener(source);
            for (int i = 0; i < MapView.Layers.Count; i++)
            {
                Layer layer = MapView.Layers[i];

                if (layer is VectorLayer)
                {
                    (layer as VectorLayer).VectorElementEventListener = listener;
                }
            }
        }
 public CartoVisBuilderWithGridEvent(MapView mapView, VectorLayer vectorLayer)
 {
     this.mapView = mapView;
     this.vectorLayer = vectorLayer;
 }
示例#40
0
        public void SetSourcesAndElements(Bitmap olmarker, Bitmap up, Bitmap upleft, Bitmap upright, Color green, Color red, Color white)
        {
            // Define layer and datasource for route line and instructions
            routeDataSource = new LocalVectorDataSource(BaseProjection);
            VectorLayer routeLayer = new VectorLayer(routeDataSource);
            MapView.Layers.Add(routeLayer);

            // Define layer and datasource for route start and stop markers
            routeStartStopDataSource = new LocalVectorDataSource(BaseProjection);

            // Initialize a vector layer with the previous data source
            VectorLayer vectorLayer = new VectorLayer(routeStartStopDataSource);

            // Add the previous vector layer to the map
            MapView.Layers.Add(vectorLayer);

            // Set visible zoom range for the vector layer
            vectorLayer.VisibleZoomRange = new MapRange(0, 22);

            // Create markers for start & end and a layer for them
            MarkerStyleBuilder markerBuilder = new MarkerStyleBuilder();
            markerBuilder.Bitmap = olmarker;
            markerBuilder.HideIfOverlapped = false;
            markerBuilder.Size = 30;
            markerBuilder.Color = green;

            startMarker = new Marker(new MapPos(0, 0), markerBuilder.BuildStyle());
            startMarker.Visible = false;

            markerBuilder.Color = red;

            stopMarker = new Marker(new MapPos(0, 0), markerBuilder.BuildStyle());
            stopMarker.Visible = false;

            routeStartStopDataSource.Add(startMarker);
            routeStartStopDataSource.Add(stopMarker);

            markerBuilder.Color = white;
            markerBuilder.Bitmap = up;
            instructionUp = markerBuilder.BuildStyle();

            markerBuilder.Bitmap = upleft;
            instructionLeft = markerBuilder.BuildStyle();

            markerBuilder.Bitmap = upright;
            instructionRight = markerBuilder.BuildStyle();

            // Style for instruction balloons
            balloonBuilder = new BalloonPopupStyleBuilder();
            balloonBuilder.TitleMargins = new BalloonPopupMargins(4, 4, 4, 4);
        }
 public ShapefileExporter(VectorLayer layer)
 {
     _layer = layer;
 }
示例#42
0
 private void RemoveDrawingLayer()
 {
     newNodeGeometry.Clear();
     newNodeLayer = null;
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStylePositron);

            Projection projection = BaseProjection;

            // Initialize an local vector data source
            LocalVectorDataSource source = new LocalVectorDataSource(projection);

            // Initialize a vector layer with the previous data source
            VectorLayer vectorLayer = new VectorLayer(source);

            // Add the previous vector layer to the map
            MapView.Layers.Add(vectorLayer);

            // Set visible zoom range for the vector layer
            vectorLayer.VisibleZoomRange = new MapRange(10, 24);

            // Add a bunch of vector elements
            // As elements can be shared across platforms, they are in a shared project

            Overlays.AddPoint1(source, projection);
            Overlays.AddPoint2(source, projection);

            Overlays.AddOverlyingLines(MapView, source, projection);

            Overlays.Add2DPolygon(source, projection);

            Overlays.AddText1(source, projection);
            Overlays.AddText2(source, projection);
            Overlays.AddText3(source, projection);

            Bitmap info   = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/info.png"));
            Bitmap arrow  = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/arrow.png"));
            Bitmap marker = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/marker.png"));

            Overlays.AddBalloonPopup1(source, projection, info, arrow);
            Overlays.AddBalloonPopup2(source, projection, info, arrow, marker);
            Overlays.AddBalloonPopup3(source, projection);

            Overlays.Add3DCar(source, projection);
            Overlays.Add3DPolygon(source, projection);

            // Animate map to Tallinn where the objects are
            MapView.SetFocusPos(projection.FromWgs84(new MapPos(24.662893, 59.419365)), 1);
            MapView.SetZoom(12, 1);

            // Add maplistener to detect click on model

            listener = new VectorElementListener(source);
            for (int i = 0; i < MapView.Layers.Count; i++)
            {
                Layer layer = MapView.Layers[i];

                if (layer is VectorLayer)
                {
                    (layer as VectorLayer).VectorElementEventListener = listener;
                }
            }
        }
 public MyUTFGridEventListener(VectorLayer vectorLayer, Variant infoWindow = null)
 {
     this.vectorLayer = vectorLayer;
 }
示例#45
0
文件: MainForm.cs 项目: jzChia/demo
        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            switch (m.Msg)
            {
            case WM_COPYDATA:
            {
                COPYDATASTRUCT mystr  = new COPYDATASTRUCT();
                Type           mytype = mystr.GetType();
                mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                TransferTask currentTask = transferTaskListControl1.GetTaskByID(new Guid(mystr.lpData.Substring(0, mystr.cbData)));
                if (currentTask != null)
                {
                    transferTaskListControl1.CompleteTask(currentTask);

                    //写入元数据
                    TemplateMetaData metaData;
                    MetaDts.TryGetValue(currentTask.ID, out metaData);

                    if (currentTask.Type == TaskType.Upload)
                    {
                        switch (metaData.MetaDataType)
                        {
                        case EnumMetaDataType.Raster:
                        {
                            Demo.Entities.RasterLayer rstLyr = metaData.LayerData as Demo.Entities.RasterLayer;
                            rstLyr.LAYERSIZE = (long)currentTask.Size;
                            if (Demo.Entities.RasterLayer.ImportRasterIndex(rstLyr) == 1)
                            {
                                //MessageBox.Show("元数据保存成功!");
                            }
                            else
                            {
                                MessageBox.Show("元数据保存失败!");
                            }
                            break;
                        }

                        case EnumMetaDataType.Features:
                        {
                            VectorLayer vecLyr = metaData.LayerData as VectorLayer;
                            vecLyr.LAYERSIZE = (long)currentTask.Size;
                            if (VectorLayer.ImportVectorIndex(vecLyr) == 1)
                            {
                                //MessageBox.Show("元数据保存成功!");
                            }
                            else
                            {
                                MessageBox.Show("元数据保存失败!");
                            }
                            break;
                        }

                        case EnumMetaDataType.Files:
                        {
                            FileLayer fileLyr = metaData.LayerData as FileLayer;
                            fileLyr.LAYERSIZE = (long)currentTask.Size;
                            if (FileLayer.ImportFileIndex(fileLyr) == 1)
                            {
                                //MessageBox.Show("元数据保存成功!");
                            }
                            else
                            {
                                MessageBox.Show("元数据保存失败!");
                            }
                            break;
                        }
                        }
                    }
                    else
                    {
                    }
                }
                break;
            }

            default:
                base.DefWndProc(ref m);
                break;
            }
        }