Inheritance: Layer, ICanQueryLayer
示例#1
0
        public void SetAttributes()
        {
            Collection<IGeometry> geometries = new Collection<IGeometry>();
            
            geometries.Add(GeometryFromWKT.Parse("LINESTRING (20 20, 20 30, 30 30, 30 20, 40 20)"));
            geometries.Add(GeometryFromWKT.Parse("LINESTRING (21 21, 21 31, 31 31, 31 21, 41 21)"));
            geometries.Add(GeometryFromWKT.Parse("LINESTRING (22 22, 22 32, 32 32, 32 22, 42 22)"));

            DataTableFeatureProvider dataTableFeatureFeatureProvider = new DataTableFeatureProvider(geometries);


            VectorLayer vectorLayer = new VectorLayer();
            vectorLayer.DataSource = dataTableFeatureFeatureProvider;

            // add column
            FeatureDataRow r = (FeatureDataRow)vectorLayer.DataSource.GetFeature(0);
            r.Table.Columns.Add("Value", typeof(float));

            // set value attribute
            for (int i = 0; i < dataTableFeatureFeatureProvider.GetFeatureCount(); i++)
            {
                r = (FeatureDataRow)dataTableFeatureFeatureProvider.GetFeature(i);
                r[0] = i;
            }

            FeatureDataRow row = (FeatureDataRow)dataTableFeatureFeatureProvider.GetFeature(2);
            Assert.AreEqual(2, row[0], "Attribute 0 in the second feature must be set to 2");
        }
示例#2
0
        public void ClearSelectionOnParentGroupLayerRemove()
        {
            var featureProvider = new DataTableFeatureProvider();
            featureProvider.Add(new WKTReader().Read("POINT(0 0)"));
            var layer = new VectorLayer { DataSource = featureProvider };
            var groupLayer = new GroupLayer { Layers = { layer } };

            using (var mapControl = new MapControl { Map = { Layers = { groupLayer } }, AllowDrop = false })
            {
                var selectTool = mapControl.SelectTool;

                selectTool.Select(featureProvider.Features.Cast<IFeature>());

                WindowsFormsTestHelper.Show(mapControl);

                mapControl.Map.Layers.Remove(groupLayer);

                mapControl.WaitUntilAllEventsAreProcessed();

                selectTool.Selection
                    .Should("selection is cleared on layer remove").Be.Empty();
            }

            WindowsFormsTestHelper.CloseAll();
        }
示例#3
0
文件: Form2.cs 项目: lishxi/_SharpMap
        private void Form2_Load(object sender, EventArgs e)
        {

            
            //TileAsyncLayer osmLayer= new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM");
            TileAsyncLayer bingLayer = new TileAsyncLayer(new BingTileSource(BingRequest.UrlBing, "",BingMapType.Roads), "TileLayer - Bing" );
            
            this.mapBox1.Map.BackgroundLayer.Add(bingLayer);

#if DotSpatialProjections
            var mathTransform = LayerTools.Wgs84toGoogleMercator;
            SharpMap.Geometries.BoundingBox geom = GeometryTransform.TransformBox(
                new SharpMap.Geometries.BoundingBox(-9.205626, 38.690993, -9.123736, 38.740837), 
                mathTransform.Source, mathTransform.Target);
#else
            var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;
            SharpMap.Geometries.BoundingBox geom = GeometryTransform.TransformBox(
                new SharpMap.Geometries.BoundingBox(-9.205626, 38.690993, -9.123736, 38.740837), 
                mathTransform);
#endif

            //Adds a pushpin layer
            VectorLayer pushPinLayer = new VectorLayer("PushPins");
            List<SharpMap.Geometries.Geometry> geos = new List<SharpMap.Geometries.Geometry>();
            geos.Add(geom.GetCentroid());
            SharpMap.Data.Providers.GeometryProvider geoProvider = new SharpMap.Data.Providers.GeometryProvider(geos);
            pushPinLayer.DataSource = geoProvider;
            //this.mapBox1.Map.Layers.Add(pushPinLayer);

            this.mapBox1.Map.ZoomToBox(geom);
            this.mapBox1.Map.Zoom = 8500;
           
            this.mapBox1.Refresh();
            
        }
示例#4
0
        public void GetMap_GeometryProvider_ReturnImage()
        {
            Map map = new Map(new System.Drawing.Size(400, 200));

            SharpMap.Layers.VectorLayer vLayer = new SharpMap.Layers.VectorLayer("Geom layer", CreateTestFeatureProvider());
            vLayer.Style.Outline       = new System.Drawing.Pen(System.Drawing.Color.Red, 2f);
            vLayer.Style.EnableOutline = true;
            vLayer.Style.Line          = new System.Drawing.Pen(System.Drawing.Color.Green, 2f);
            vLayer.Style.Fill          = System.Drawing.Brushes.Yellow;
            map.Layers.Add(vLayer);

            SharpMap.Layers.VectorLayer vLayer2 = new SharpMap.Layers.VectorLayer("Geom layer 2", vLayer.DataSource);
            vLayer.Style.SymbolOffset   = new System.Drawing.PointF(3, 4);
            vLayer.Style.SymbolRotation = 45;
            vLayer.Style.SymbolScale    = 0.4f;
            map.Layers.Add(vLayer2);

            SharpMap.Layers.VectorLayer vLayer3 = new SharpMap.Layers.VectorLayer("Geom layer 3", vLayer.DataSource);
            vLayer3.Style.SymbolOffset   = new System.Drawing.PointF(3, 4);
            vLayer3.Style.SymbolRotation = 45;
            map.Layers.Add(vLayer3);

            SharpMap.Layers.VectorLayer vLayer4 = new SharpMap.Layers.VectorLayer("Geom layer 4", vLayer.DataSource);
            vLayer4.Style.SymbolOffset = new System.Drawing.PointF(3, 4);
            vLayer4.Style.SymbolScale  = 0.4f;
            vLayer4.ClippingEnabled    = true;
            map.Layers.Add(vLayer4);

            map.ZoomToExtents();

            var img = map.Render();

            Assert.IsNotNull(img);
        }
示例#5
0
        public void CreateFromCollection()
        {
            EventedList<SampleFeature> features = new EventedList<SampleFeature>();

            features.Add(new SampleFeature());
            features.Add(new SampleFeature());
            features.Add(new SampleFeature());

            features[0].Geometry = GeometryFromWKT.Parse("LINESTRING (20 20, 20 30, 30 30, 30 20, 40 20)");
            features[1].Geometry = GeometryFromWKT.Parse("LINESTRING (30 30, 30 40, 40 40, 40 30, 50 30)");
            features[2].Geometry = GeometryFromWKT.Parse("LINESTRING (40 40, 40 50, 50 50, 50 40, 60 40)");

            FeatureCollection featureCollection = new FeatureCollection {Features = features};

            Map map = new Map();
            
            VectorLayer vectorLayer = new VectorLayer();
            vectorLayer.DataSource = featureCollection;
            
            map.Layers.Add(vectorLayer);

            Assert.AreEqual(3, vectorLayer.DataSource.GetFeatureCount());
            Assert.AreEqual("LineString", vectorLayer.DataSource.GetGeometryByID(0).GeometryType);

            // ShowMap(map);
        }
示例#6
0
        public CoverageProfileTool()
        {

            GridProfiles = new List<IFeature>();

            profileLayer = new VectorLayer("Profile Layer")
                                           {
                                               DataSource = new FeatureCollection(GridProfiles, typeof(CoverageProfile)),
                                               Visible = true,
                                               Style = new VectorStyle
                                                           {
                                                               Fill = new SolidBrush (Color.Tomato),
                                                               Symbol = null,
                                                               Line = new Pen(Color.Tomato, 2),
                                                               Outline = new Pen(Color.FromArgb(50, Color.Tomato), 2)
                                                           },
                                               ShowInTreeView = true,
                                               FeatureEditor = new CoverageProfileEditor()
                                           };
            
            LayerFilter = l => l.Equals(profileLayer);

            newLineTool = new NewLineTool(l => l.Equals(profileLayer), "new coverage profile")
                              {
                                  AutoCurve = false,
                                  MinDistance = 0,
                                  IsActive = false
                              };
        }
示例#7
0
        public static FeatureDataRow FindGeoNearPoint(GeoAPI.Geometries.IPoint point, VectorLayer layer, double amountGrow)
        {
            var box = new Envelope(point.Coordinate);
            box.ExpandBy(amountGrow);

            var fds = new FeatureDataSet();
            layer.DataSource.ExecuteIntersectionQuery(box, fds);

            FeatureDataRow result = null;
            var minDistance = double.MaxValue;

            foreach (FeatureDataTable fdt in fds.Tables)
            {
                foreach (FeatureDataRow fdr in fdt.Rows)
                {
                    if (fdr.Geometry != null)
                    {
                        var distance = point.Distance(fdr.Geometry);
                        if (distance < minDistance)
                        {
                            result = fdr;
                            minDistance = distance;
                        }
                    }
                }
            }

            return result;
        }
示例#8
0
        public void ShowMapWithPointLayerBasedOnFeatureDataTable()
        {
            var table = new FeatureDataTable();
            table.Columns.Add("X", typeof(double));
            table.Columns.Add("Y", typeof(double));
            table.Columns.Add("Category", typeof(string));
            DataRow row = table.NewRow();
            table.Rows.Add(row);
            row.ItemArray = new object[] { 100000, 400000, "testCategory" };
            row = table.NewRow();
            table.Rows.Add(row);
            row.ItemArray = new object[] { 200000, 400000, "TestCategory" };

            var dataTablePoint = new DataTablePoint(table, "Category", "X", "Y");
            var vectorLayer = new VectorLayer("test", dataTablePoint);


            vectorLayer.Theme =ThemeFactory.CreateSingleFeatureTheme(vectorLayer.Style.GeometryType, Color.Blue, 10);
            var map = new Map { Name = "testmap" };

            map.Layers.Add(vectorLayer);
            map.Center = new Coordinate(150000, 400000);

            map.Zoom = 200000;
            //map.ZoomToExtents();
            //map.ZoomToBox(map.Envelope);
            
            MapTestHelper.Show(map);
        }
示例#9
0
 public void MutatingAGroupLayerWithHasReadonlyLayerCollectionThrows()
 {
     var layerGroup = new GroupLayer {HasReadOnlyLayersCollection = true};
     var childLayer = new VectorLayer();
     layerGroup.Layers.Add(childLayer);
     
 }
示例#10
0
        /// <summary>
        /// little util wich just adds one vector layer to the map and assigns it a random theme.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="m"></param>
        public static void SetupMap(HttpContext context, Map m)
        {
            var l = new VectorLayer(
                "Countries",
                new ShapeFile(context.Server.MapPath(ConfigurationManager.AppSettings["shpfilePath"])));

            l.Style = RandomStyle.RandomVectorStyleNoSymbols();
            l.Theme = new CustomTheme<IVectorStyle>(
                delegate { return RandomStyle.RandomVectorStyleNoSymbols(); });
            m.Layers.Add(l);

            FeatureDataTable labelData = new FeatureDataTable();
            labelData.Columns.Add("Name", typeof (string));
            FeatureDataRow r = labelData.NewRow();
            r["Name"] = "My Lair";
            r.Geometry = new Point(5, 5);
            labelData.AddRow(r);

            LabelLayer labelLayer = new LabelLayer("labelLayer")
                            {
                                DataSource = new GeometryFeatureProvider(labelData),
                                Enabled = true,
                                LabelColumn = "Name",
                                Style = new LabelStyle
                                            {
                                                BackColor = new SolidBrush(Color.Black),
                                                ForeColor = Color.White,
                                                Halo = new Pen(Color.Yellow, 0.1F),
                                                CollisionDetection = false,
                                                Font = new Font("Arial", 10, GraphicsUnit.Point)
                                            }
                            };

            m.Layers.Add(labelLayer);
        }
示例#11
0
        public static Map Spherical()
        {
            ICoordinateTransformation transformation = ProjHelper.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/{0}", layer);
                string path = context.Server.MapPath(format);
                if (!File.Exists(path))
                    throw new FileNotFoundException("file not found", path);

                string name = Path.GetFileNameWithoutExtension(layer);
                LayerData data = dict[layer];
                ShapeFile source = new ShapeFile(path, true);
                VectorLayer item = new VectorLayer(name, source)
                {
                    SRID = 4326,
                    TargetSRID = 900913,
                    CoordinateTransformation = transformation,
                    Style = (VectorStyle)data.Style,
                    SmoothingMode = SmoothingMode.AntiAlias
                };
                map.Layers.Add(item);
            }
            return map;
        }
示例#12
0
        private static Map InitializeDXF(float angle)
        {
            Map map = new Map();
            //Set the datasource to a shapefile in the App_data folder
            Ogr provider;
            try
            {
                provider = new Ogr("GeoData/SampleDXF.dxf",0);
            }
            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 = new VectorLayer("SampleDXF", provider);
            map.Layers.Add(lay);
            map.ZoomToExtents();
            Matrix mat = new Matrix();
            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;

            _ogrSampleDataset = "SampleDXF";
            return map;

        }
示例#13
0
        void ShowSelectLayer(SharpMap.Data.FeatureDataTable data)
        {
            Layer layer = null;

            foreach (Layer tmplayer in this.mapBox1.Map.Layers)
            {
                if (tmplayer.LayerName == "selectedLyr")
                {
                    layer = tmplayer;
                }
            }

            if (layer != null)
            {
                this.mapBox1.Map.Layers.Remove(layer);
            }

            SharpMap.Layers.VectorLayer selectedLyr = new SharpMap.Layers.VectorLayer("selectedLyr");
            foreach (FeatureDataRow row in data.Rows)
            {
                selectedLyr.DataSource          = new SharpMap.Data.Providers.GeometryProvider(row as SharpMap.Data.FeatureDataRow);
                selectedLyr.Style.EnableOutline = true;
                selectedLyr.Style.Outline       = new Pen(Color.FromArgb(50, 255, 255), 4);
                selectedLyr.Style.Fill          = new SolidBrush(Color.Transparent);
                mapBox1.Map.Layers.Add(selectedLyr);
                this.mapBox1.Refresh();
            }
        }
示例#14
0
文件: Form2.cs 项目: lishxi/_SharpMap
        private void Form2_Load(object sender, EventArgs e)
        {
            //TileAsyncLayer osmLayer= new TileAsyncLayer(new OsmTileSource(), "TileLayer - OSM");
            TileAsyncLayer bingLayer = new TileAsyncLayer(new BingTileSource(BingRequest.UrlBing, "", BingMapType.Roads), "TileLayer - Bing");

            this.mapBox1.Map.BackgroundLayer.Add(bingLayer);
            GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 3857);

#if DotSpatialProjections
            var mathTransform = LayerTools.Wgs84toGoogleMercator;
            var geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837), 
                mathTransform.Source, mathTransform.Target);
#else
            IMathTransform mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;
            Envelope geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837),
                mathTransform);
#endif

            //Adds a pushpin layer
            VectorLayer pushPinLayer = new VectorLayer("PushPins");
            List<IGeometry> geos = new List<IGeometry>();
            geos.Add(gf.CreatePoint(geom.Centre));
            var geoProvider = new FeatureProvider(geos);
            pushPinLayer.DataSource = geoProvider;
            //this.mapBox1.Map.Layers.Add(pushPinLayer);

            this.mapBox1.Map.ZoomToBox(geom);
            this.mapBox1.Map.Zoom = 8500;
            this.mapBox1.Refresh();
        }
示例#15
0
        private void FormAnimation_Load(object sender, EventArgs e)
        {

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

            this.mapBox1.Map.Layers.Add(layCountries);

            

            this.mapBox1.Map.ZoomToExtents(); 
            this.mapBox1.Refresh();


            
            
        }
        public void NewNodeToolShouldWorkWithoutSnapRules()
        {
            // Create map and map control
            Map map = new Map();
            var nodeList = new List<Node>();

            var nodeLayer = new VectorLayer
                {
                    DataSource = new FeatureCollection(nodeList, typeof (Node)),
                    Visible = true,
                    Style = new VectorStyle
                        {
                            Fill = new SolidBrush(Color.Tomato),
                            Symbol = null,
                            Line = new Pen(Color.Turquoise, 3)
                        }
                };
            map.Layers.Add(nodeLayer);

            var mapControl = new MapControl {Map = map};
            mapControl.Resize += delegate { mapControl.Refresh(); };
            mapControl.Dock = DockStyle.Fill;

            var newNodeTool = new NewNetworkFeatureTool(l => true, "new node");
            mapControl.Tools.Add(newNodeTool);

            var args = new MouseEventArgs(MouseButtons.Left, 1, -1, -1, -1);

            newNodeTool.OnMouseDown(new Coordinate(0, 20), args);
            newNodeTool.OnMouseMove(new Coordinate(0, 20), args);
            newNodeTool.OnMouseUp(new Coordinate(0, 20), args);

            Assert.IsFalse(newNodeTool.IsBusy);
            Assert.AreEqual(1, nodeList.Count);
        }
示例#17
0
        private bool LoadTheBasicLayerIntoSharpMap(string p)
        {
            try
            {
                SharpMap.Layers.VectorLayer temp = null;

                foreach (SharpMap.Layers.VectorLayer tLayer in mapBox1.Map.Layers)
                {
                    if (tLayer.LayerName == Main.BASEMAPLAYERNAME)
                        temp = tLayer;
                }

                mapBox1.Map.Layers.Remove(temp);

                SharpMap.Layers.VectorLayer TheLayer = new SharpMap.Layers.VectorLayer(Main.BASEMAPLAYERNAME);
                TheLayer.DataSource = new SharpMap.Data.Providers.ShapeFile(p);

                mapBox1.Map.Layers.Add(TheLayer);
                mapBox1.Map.ZoomToExtents();
                mapBox1.Refresh();
                mapBox1.Update();

                // The Routing Engine needs a copy of the layer. 
                TheRoutingEngine.AnalysisLayer = TheLayer;

                return true;

            }
            catch (Exception)
            {
                return false;
            }
        }
示例#18
0
        public void NopDeleteDoesNotTriggerBeginEdit()
        {
            MapControl mapControl = new MapControl();

            SelectTool selectTool = mapControl.SelectTool;

            VectorLayer vectorLayer = new VectorLayer();
            FeatureCollection layer2Data = new FeatureCollection();
            vectorLayer.DataSource = layer2Data;
            layer2Data.FeatureType = typeof(Feature);

            layer2Data.Add(new Point(4, 5));
            layer2Data.Add(new Point(0, 1));
            mapControl.Map.Layers.Add(vectorLayer);

            var featureMutator = mocks.StrictMock<IFeatureInteractor>();
            var editableObject = mocks.StrictMock<IEditableObject>();

            featureMutator.Expect(fm => fm.EditableObject).Return(editableObject).Repeat.Any();
            featureMutator.Expect(fm => fm.AllowDeletion()).Return(false).Repeat.Any();
            featureMutator.Expect(fm => fm.Delete()).Repeat.Never();
            editableObject.Expect(eo => eo.BeginEdit(null)).IgnoreArguments().Repeat.Never(); //never expect BeginEdit!
            editableObject.Expect(eo => eo.EndEdit()).IgnoreArguments().Repeat.Never();
            
            mocks.ReplayAll();
            
            selectTool.Select((IFeature)layer2Data.Features[0]);

            selectTool.SelectedFeatureInteractors.Clear();
            selectTool.SelectedFeatureInteractors.Add(featureMutator); //inject our own feature editor

            mapControl.DeleteTool.DeleteSelection();

            mocks.VerifyAll();
        }
示例#19
0
        private void LoadBaseGeometry(Color layerColor)
        {
            Hashtable htGeoIds = new Hashtable();

            // First check to see if the NETWORK_MAP layer already exists in the layers collection.
            // if it does, then we dont want to add it again.
            if (MainMapImage.Map.Layers.Find(delegate(ILayer il) { return(il.LayerName == "NETWORK MAP"); }) == null)
            //if(MainMapImage.Map.Layers["NETWORK MAP"] != null)
            {
                // Get the geometries for defined networks, if they exist.
                DataSet ds;

                String strQuery = "SELECT GEOMETRY, SECTIONID FROM SECTION_" + m_strNetworkID;
                ds = DBMgr.ExecuteQuery(strQuery);

                List <Geometry> GeomColl = new List <Geometry>();
                //LineString lineSeg;
                Geometry lineSeg;

                int iCount = 0;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (row[0] != null && row[0].ToString() != "")
                    {
                        //lineSeg = (LineString)Geometry.GeomFromText(row[0].ToString());
                        lineSeg       = Geometry.GeomFromText(row[0].ToString());
                        lineSeg.Tag   = row["SECTIONID"].ToString();
                        lineSeg.Color = layerColor;
                        GeomColl.Add(lineSeg);
                        htGeoIds.Add(row["SECTIONID"].ToString(), lineSeg);
                    }
                    iCount++;
                }

                SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("NETWORK MAP");
                myLayer.Tag        = "NETWORK MAP";
                myLayer.DataSource = new SharpMap.Data.Providers.GeometryProvider(GeomColl);
                myLayer.GeoIDs     = htGeoIds;

                try
                {
                    MainMapImage.Map.Layers.Insert(0, myLayer);
                    MainMapImage.Map.ZoomToExtents();
                    MainMapImage.Refresh();

                    FormGISLayerManager formGISLayerManager;
                    if (FormManager.IsFormGISLayerManagerOpen(out formGISLayerManager))
                    {
                        formGISLayerManager.AddBaseMap();
                    }
                }
                catch (Exception exc)
                {
                    Global.WriteOutput("Error: Could not get NETWORK MAP from NETWORK_DEFINITION table. " + exc.Message);
                    //MainMapImage.Map.Layers.Remove(MainMapImage.Map.Layers["NETWORK MAP"]);
                    int iRemoveIndex = MainMapImage.Map.Layers.FindIndex(delegate(SharpMap.Layers.ILayer layer) { return(layer.LayerName == "NETWORK MAP"); });
                    MainMapImage.Map.Layers.RemoveAt(iRemoveIndex);
                }
            }
        }
示例#20
0
        private bool LoadTheBasicLayerIntoSharpMap(string p)
        {
            try
            {
                SharpMap.Layers.VectorLayer temp = null;

                foreach (SharpMap.Layers.VectorLayer tLayer in mapBox1.Map.Layers)
                {
                    if (tLayer.LayerName == Main.BASEMAPLAYERNAME)
                    {
                        temp = tLayer;
                    }
                }

                mapBox1.Map.Layers.Remove(temp);

                SharpMap.Layers.VectorLayer TheLayer = new SharpMap.Layers.VectorLayer(Main.BASEMAPLAYERNAME);
                TheLayer.DataSource = new SharpMap.Data.Providers.ShapeFile(p);

                mapBox1.Map.Layers.Add(TheLayer);
                mapBox1.Map.ZoomToExtents();
                mapBox1.Refresh();
                mapBox1.Update();

                // The Routing Engine needs a copy of the layer.
                TheRoutingEngine.AnalysisLayer = TheLayer;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#21
0
        private static VectorLayer CrearCapaInfoEst(VectorLayer capaBase)
        {
            //Layer reservada para consultas con el botón info (vacia)
            VectorLayer capaInfoEst = new SharpMap.Layers.VectorLayer(NOMCAPA_INFO);

            //Atención: si Envelope de capaBase es nulo (i.e. no hay geometrías en la capaBase)
            //proporcionar un punto al proveedor para evitar error en tiempo de ejecución
            SharpMap.Data.Providers.GeometryProvider provGeo;
            if (capaBase.Envelope == null)
            {
                provGeo = new SharpMap.Data.Providers.GeometryProvider(new SharpMap.Geometries.Point(0.0, 0.0));
            }
            else
            {
                provGeo = new SharpMap.Data.Providers.GeometryProvider(capaBase.Envelope.GetCentroid());
            }

            provGeo.SRID           = capaBase.SRID;
            capaInfoEst.DataSource = provGeo;
            SimbLayInfoEst s = new SimbLayInfoEst();

            capaInfoEst.Enabled = s.visible;
            capaInfoEst.Style   = ObtenerEstilo(TipoPaleta.predeterminada, s);
            AsignarEntradaLeyendaInformacion(NOMCAPA_INFO, capaInfoEst, s.titulo);
            return(capaInfoEst);
        }
示例#22
0
        [Test] //not working in UI?
        public void CanRemovePointFromLine()
        {
            var mapControl = new MapControl();

            var vectorLayer = new VectorLayer();
            var layerData = new FeatureCollection();
            vectorLayer.DataSource = layerData;
            layerData.FeatureType = typeof(CloneableFeature);

            layerData.Add(new LineString(new[] { new Coordinate(0, 0), new Coordinate(50, 0), new Coordinate(100, 0) }));

            mapControl.Map.Layers.Add(vectorLayer);

            var firstFeature = (IFeature)layerData.Features[0];
            mapControl.SelectTool.Select(firstFeature);

            var curveTool = mapControl.GetToolByType<CurvePointTool>();

            curveTool.IsActive = true;
            curveTool.Mode = CurvePointTool.EditMode.Remove;
            var args = new MouseEventArgs(MouseButtons.Left, 1, 0, 0, 0);
            curveTool.OnMouseMove(new Coordinate(50, 0), new MouseEventArgs(MouseButtons.None, 1, 0, 0, 0));
            curveTool.OnMouseDown(new Coordinate(50, 0), args); // delete tracker

            Assert.AreEqual(2, firstFeature.Geometry.Coordinates.Length);
            Assert.AreEqual(100.0, firstFeature.Geometry.Coordinates[1].X);
        }
示例#23
0
        public GridProfileTool(MapControl mapControl)
            : base(mapControl)
        {

            GridProfiles = new List<IFeature>();

            VectorLayer profileLayer = new VectorLayer("Profile Layer")
                                           {
                                               DataSource = new FeatureCollection(GridProfiles, typeof(GridProfile)),
                                               Enabled = true,
                                               Style = new VectorStyle
                                                           {
                                                               Fill = new SolidBrush (Color.Tomato),
                                                               Symbol = null,
                                                               Line = new Pen(Color.SteelBlue, 1),
                                                               Outline = new Pen(Color.FromArgb(50, Color.LightGray), 3)
                                                           },
                                               Map = mapControl.Map,
                                               ShowInTreeView = true
                                           };
            Layer = profileLayer;

            newLineTool = new NewLineTool(profileLayer)
                              {
                                  MapControl = mapControl,
                                  Name = "ProfileLine",
                                  AutoCurve = false,
                                  MinDistance = 0,
                                  IsActive = false
                              };
        }
示例#24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Set up the map. We use the method in the App_Code folder for initializing the map and alter it afterwards
        myMap = MapHelper.InitializeMap(new System.Drawing.Size((int)imgMap.Width.Value, (int)imgMap.Height.Value));
        //Remove the river layer and label-layers
        myMap.Layers.RemoveAt(4);
        myMap.Layers.RemoveAt(3);
        myMap.Layers.RemoveAt(1);

        //Create Pie Layer
        SharpMap.Layers.VectorLayer pieLayer = new SharpMap.Layers.VectorLayer("Pie charts");
        pieLayer.DataSource = (myMap.Layers[0] as SharpMap.Layers.VectorLayer).DataSource;
        CustomTheme<IVectorStyle> iTheme = new CustomTheme<IVectorStyle>(GetCountryStyle);
        pieLayer.Theme = iTheme;
        myMap.Layers.Add(pieLayer);

        if (Page.IsPostBack)
        {
            //Page is post back. Restore center and zoom-values from viewstate
            myMap.Center = (SharpMap.Geometries.Point)ViewState["mapCenter"];
            myMap.Zoom = (double)ViewState["mapZoom"];
        }
        else
        {
            //This is the initial view of the map. Zoom to the extents of the map:
            //myMap.ZoomToExtents();
            myMap.Center = new SharpMap.Geometries.Point(10, 50);
            myMap.Zoom = 60;
            //Create the map
            GenerateMap();
        }
    }
示例#25
0
    private HtmlGenericControl LegendDiv(SharpMap.Layers.ILayer myLayer)
    {
        HtmlGenericControl legendDiv = new HtmlGenericControl("div");

        legendDiv.Style.Add("width", "2em");
        legendDiv.Style.Add("overflow", "hidden");
        legendDiv.Style.Add("position", "absolute");
        legendDiv.Style.Add("margin-left", "0.5em");
        legendDiv.Style.Add("margin-bottom", "0px");
        if (myLayer.GetType() == typeof(SharpMap.Layers.VectorLayer))
        {
            SharpMap.Layers.VectorLayer myVectorLayer = (myLayer as SharpMap.Layers.VectorLayer);

            SharpMap.Styles.VectorStyle myStyle = new SharpMap.Styles.VectorStyle();
            if (myVectorLayer.Theme != null)
            {
                if (myVectorLayer.Theme.GetType() == typeof(SharpMap.Rendering.Thematics.CustomTheme))
                {
                    SharpMap.Rendering.Thematics.CustomTheme myTheme = (myVectorLayer.Theme as SharpMap.Rendering.Thematics.CustomTheme);
                    myStyle = (myTheme.DefaultStyle as SharpMap.Styles.VectorStyle);
                }
                else if (myVectorLayer.Theme.GetType() == typeof(SharpMap.Rendering.Thematics.GradientTheme))
                {
                    SharpMap.Rendering.Thematics.GradientTheme myTheme = (myVectorLayer.Theme as SharpMap.Rendering.Thematics.GradientTheme);
                    myStyle = (myTheme.MinStyle as SharpMap.Styles.VectorStyle);
                }
            }
            else
            {
                myStyle = myVectorLayer.Style;
            }

            if (myStyle.Outline.Color.Name.ToString() != "Black")
            {
                string lineStyle = (myStyle.Outline.DashStyle.ToString() == "Dash") ? "dotted" : "solid";
                legendDiv.Style.Add("border", lineStyle + " " + myStyle.Outline.Width.ToString() + "px " + ColorToHex(myStyle.Outline.Color));
                legendDiv.Style.Add("height", "1em");
            }
            else
            {
                string lineStyle = (myStyle.Line.DashStyle.ToString() == "Dash") ? "dotted" : "solid";
                legendDiv.Style.Add("border-bottom", lineStyle + " " + myStyle.Line.Width.ToString() + "px " + ColorToHex(myStyle.Line.Color));
                legendDiv.Style.Add("height", "0.8em");
            }

            System.Drawing.SolidBrush fillBrush = (myVectorLayer.Style.Fill as System.Drawing.SolidBrush);
            if (fillBrush.Color.Name.ToString() != "Black")
            {
                HtmlGenericControl fillDiv = new HtmlGenericControl("div");
                fillDiv.Style.Add("border-left", "solid 2em " + ColorToHex(fillBrush.Color));
                fillDiv.Style.Add("height", "1.2em");
                fillDiv.Style.Add("overflow", "hidden");
                fillDiv.Style.Add("opacity ", ColorAlpha(fillBrush.Color) + "%");
                fillDiv.Style.Add("filter", "ALPHA(opacity=" + ColorAlpha(fillBrush.Color) + ")");
                legendDiv.Controls.Add(fillDiv);
            }
        }
        return(legendDiv);
    }
        public ILayer Create(string layerName, string connectionInfo)
        {
            ShapeFile shapeFileData = new ShapeFile(connectionInfo);

            VectorLayer shapeFileLayer = new VectorLayer(layerName, shapeFileData);

            return shapeFileLayer;
        }
 /// <summary>
 /// Returns style based on theme or if no theme is defined uses the style defined on the layer.
 /// </summary>
 /// <param name="locationLayer">Layer on which the style is defined</param>
 /// <param name="value">Value</param>
 /// <returns></returns>
 private static VectorStyle GetStyle(VectorLayer locationLayer, double value)
 {
     if (locationLayer.Theme != null)
     {
         return (VectorStyle)locationLayer.Theme.GetStyle(value);    
     }
     return locationLayer.Style;
 }
示例#28
0
 public void GetExtents_ValidDatasource()
 {
     Map map = new Map(new Size(400, 200));
     VectorLayer vLayer = new VectorLayer("Geom layer", CreateDatasource());
     map.Layers.Add(vLayer);
     BoundingBox box = map.GetExtents();
     Assert.AreEqual(new BoundingBox(0, 50, 0, 346.3493254), box);
 }
示例#29
0
 public void LoadFromFile()
 {
     string filePath = Path.GetFullPath(TestHelper.GetDataDir() + @"\rivers.shp");
     IFeatureProvider dataSource = new ShapeFile(filePath, false);
     VectorLayer vectorLayer = new VectorLayer("rivers", dataSource);
     Assert.AreEqual("rivers", vectorLayer.Name);
     Assert.AreEqual(dataSource, vectorLayer.DataSource);
 }
示例#30
0
        private void FormGISView_Load(object sender, EventArgs e)
        {
            SecureForm();
            FormLoad(Settings.Default.GIS_VIEW_IMAGE_KEY, Settings.Default.GIS_VIEW_IMAGE_KEY_SELECTED);
            MainMapImage.Map.BackColor = System.Drawing.Color.White;

            // Set the tab text to the name of the associated network
            this.TabText = "GIS-" + m_strNetwork;

            /* TEST CODE */
            //SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries");
            //MainMapImage.Image = Image.FromFile(@"C:\Documents and Settings\cbecker\Desktop\9282_08.tif");

            /* END TEST CODE */



            // We need to load the simulations combo box with all simulations for a given networkID
            String query = "SELECT SIMULATION, SIMULATIONID FROM SIMULATIONS WHERE NETWORKID = '" + m_strNetworkID + "'";

            try
            {
                toolStripComboBoxSimulations.Items.Add("");
                DataSet dsSimulation = DBMgr.ExecuteQuery(query);
                foreach (DataRow dataRow in dsSimulation.Tables[0].Rows)
                {
                    String strSimulationName = dataRow["SIMULATION"].ToString();
                    String strSimulationID   = dataRow["SIMULATIONID"].ToString();
                    m_hashSimulationSimulationID.Add(strSimulationName, strSimulationID);
                    toolStripComboBoxSimulations.Items.Add(strSimulationName);
                }
            }
            catch (Exception exception)
            {
                Global.WriteOutput("Error: Loading simulations." + exception.Message);
            }
            Global.Attributes.Clear();
            Global.LoadAttributes();
            if (this.ImageView)
            {
                geometries                    = new List <SharpMap.Geometries.Geometry>();
                m_layerImageView              = new SharpMap.Layers.VectorLayer("Image View");
                m_layerImageView.Tag          = "ImageView";
                m_layerImageView.DataSource   = new SharpMap.Data.Providers.GeometryProvider(geometries);
                m_layerImageView.Style.Symbol = (Bitmap)imageListDefaultSymbols.Images[1];
                //m_layerImageView.Style.SymbolScale = 2;

                MainMapImage.Map.Layers.Add(m_layerImageView);

                m_formGISLayerManager          = new FormGISLayerManager(m_strNetwork, m_htAttributeYears);
                m_formGISLayerManager.MapImage = this.MainMapImage;
                m_formGISLayerManager.GISView  = this;
            }
            else
            {
                toolStripButtonManager.Visible = false;
            }
        }
示例#31
0
 /// <summary>
 /// Creates an instance of this class
 /// </summary>
 /// <param name="vectorLayer">The base layer</param>
 /// <param name="heatValueColumn">The name of the column that contains the heat value</param>
 /// <param name="heatValueScale">A value that is responsible to scale the heat value to the range &#x211d;[0, 1f]</param>
 public HeatLayer(VectorLayer vectorLayer, string heatValueColumn, float heatValueScale = 1f)
     : this()
 {
     BaseLayer = vectorLayer;
     DataSource = vectorLayer.DataSource;
     HeatValueComputer = GetHeatValueFromColumn;
     HeatValueColumn = heatValueColumn;
     HeatValueScale = heatValueScale;
 }
示例#32
0
        public VectorLayer getPolygonPoints(PointF points, VectorLayer veclayer)
        {
            //VectorLayer veclayer = (VectorLayer)m_viewBox.Map.GetLayerByName("province");
            SharpMap.Layers.VectorLayer laySelected = new SharpMap.Layers.VectorLayer("Selection");;
            CustomTheme myTheme = new CustomTheme(FeatureColoured);
            ShapeFile   vecshp  = (ShapeFile)veclayer.DataSource;
            ShapeFile   shp     = vecshp;

            if (!shp.IsOpen)
            {
                shp.Open();
            }

            FeatureDataSet   featDataSet   = new FeatureDataSet();
            FeatureDataTable featDataTable = null;
            //将point的大地坐标转为经纬度
            Projection pj = new Projection();

            points = pj.GetLatLonFromXY(points, cfg.pjPara);


            //   获取feature数量
            uint featCount = (uint)shp.GetFeatureCount();

            for (uint index = 0; index < featCount; index++)
            {
                FeatureDataRow r = shp.GetFeature(index);
                GeoAPI.Geometries.Coordinate[] geomes = r.Geometry.Coordinates;
                double[] geomsX = new double[geomes.Length];
                double[] geomsY = new double[geomes.Length];
                for (int j = 0; j < geomes.Length; j++)
                {
                    geomsX[j] = geomes[j].X;
                    geomsY[j] = geomes[j].Y;
                }

                if ((points.X < geomsX.Min()) || (points.X > geomsX.Max()) || (points.Y < geomsY.Min()) || (points.Y > geomsY.Max()))
                {
                    continue;
                }

                PointF p1 = new PointF();
                p1.X = points.X;
                p1.Y = points.Y;
                if (InPolygon(geomes, p1))
                {
                    //首先把geomes传出去,供其他使用
                    ContourGeomes = geomes;
                    //如果在某区域内,选中某个区域,放入新图层
                    laySelected.DataSource = new SharpMap.Data.Providers.GeometryProvider(shp.GetFeature(index));
                    polygon = ((NetTopologySuite.Geometries.Polygon)r.Geometry);
                    laySelected.Style.Fill = new System.Drawing.SolidBrush(Color.HotPink);
                    laySelected.CoordinateTransformation = veclayer.CoordinateTransformation;
                }
            }
            return(laySelected);
        }
示例#33
0
        public static Map InitializeMapOrig(float angle)
        {
            //Initialize a new map of size 'imagesize'
            Map map = new Map();

            //Set up the countries layer
            VectorLayer layRoads = new VectorLayer("Roads");
            //Set the datasource to a shapefile in the App_data folder
            layRoads.DataSource = new ShapeFile("GeoData/World/shp_textonpath/DeMo_Quan5.shp", false);
            (layRoads.DataSource as ShapeFile).Encoding = Encoding.UTF8;
            //Set fill-style to green
            layRoads.Style.Fill = new SolidBrush(Color.Yellow);
            layRoads.Style.Line = new Pen(Color.Yellow, 4);
            //Set the polygons to have a black outline
            layRoads.Style.Outline = new Pen(Color.Black, 5); ;
            layRoads.Style.EnableOutline = true;
            layRoads.SRID = 4326;

            //Set up a country label layer
            LabelLayer layLabel = new LabelLayer("Roads labels");
            layLabel.DataSource = layRoads.DataSource;
            layLabel.Enabled = true;
            layLabel.LabelColumn = "tenduong";
            layLabel.LabelFilter = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
            layLabel.Style = new LabelStyle();
            layLabel.Style.ForeColor = Color.White;
            layLabel.Style.Font = new Font(FontFamily.GenericSerif, 9f, FontStyle.Bold);
            layLabel.Style.Halo = new Pen(Color.Black, 2f);
            layLabel.Style.IsTextOnPath = true;
            layLabel.Style.CollisionDetection = true;
            //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;

          
            //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(layRoads);          
            map.Layers.Add(layLabel);        


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

            map.ZoomToExtents();

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

            return map;
        }
示例#34
0
        public void GetExtents_ValidDatasource()
        {
            Map map = new Map(new System.Drawing.Size(400, 200));

            SharpMap.Layers.VectorLayer vLayer = new SharpMap.Layers.VectorLayer("Geom layer", CreateTestFeatureProvider());
            map.Layers.Add(vLayer);
            IEnvelope box = map.GetExtents();

            Assert.AreEqual(GeometryFactory.CreateEnvelope(0, 50, 0, 346.3493254), box);
        }
示例#35
0
        public void TestMap()
        {
            var m = new Map(new Size(1024, 786)) {BackColor = Color.FloralWhite};
            const string samplePath = @"D:\GIS\FileGDB\samples\data\Topo.gdb";

            var p = new FileGdbProvider(samplePath);

            foreach (var fc in p.GetFeatureClasses("\\USA"))
            {
                if (fc.StartsWith("\\USA\\T"))
                    continue;

                Console.WriteLine(fc);
                var pUse = new FileGdbProvider(samplePath) { Table = fc };
                var vl = new VectorLayer("Layer:" + fc, pUse)
                             {
                                 SmoothingMode = SmoothingMode.HighQuality,
                                 Style = {Fill = RandomBrush(), Line = RandomPen()}
                             };
                m.Layers.Add(vl);

                var fds = new FeatureDataSet();
                vl.ExecuteIntersectionQuery(vl.Envelope, fds);
                fds.Tables[0].TableName = fc;
                var res = fds.Tables[0].Rows[0].ItemArray;
                foreach (DataColumn col in fds.Tables[0].Columns)
                    Console.Write(string.Format("{0} [{1}], ", col.ColumnName, col.DataType));
                Console.WriteLine();

                foreach (var item in res)
                    Console.Write(string.Format(CultureInfo.InvariantCulture, "{0}, ", item));
                Console.WriteLine();

                Console.WriteLine(pUse.GetGeometryByID(1));

                var r = pUse.GetFeature(1);
                foreach (var item in r.ItemArray)
                    Console.Write(string.Format(CultureInfo.InvariantCulture, "{0}, ", item));

                Console.WriteLine();
                Console.WriteLine();
            }
            Console.WriteLine();

            p.Dispose();

            m.ZoomToExtents();
            var b = m.GetMap();
            b.Save("fgdb-usa-states.bmp");

            //var fds = new FeatureDataSet();
            //lc.ExecuteIntersectionQuery(m.GetExtents().GetCentroid(), fds);
            //fds.Tables[0].TableName = lc.LayerName;
            //fds.Tables[0].WriteXml(Console.Out);
        }
示例#36
0
 public MeasureTool(MapControl mapControl)
     : base(mapControl)
 {
     pointGometries = new Collection<IGeometry>();
     pointLayer = new VectorLayer();
     pointLayer.Name = "measure";
     pointLayer.DataSource = new DataTableFeatureProvider(pointGometries);
     pointLayer.Style.Symbol = TrackerSymbolHelper.GenerateSimple(Pens.DarkMagenta, Brushes.Indigo, 6, 6);
     pointLayer.Enabled = false;
     pointLayer.ShowInLegend = false;
 }
示例#37
0
        public VectorLayer getPolygonPoints(PointF points, VectorLayer veclayer)
        {
            //VectorLayer veclayer = (VectorLayer)m_viewBox.Map.GetLayerByName("province");
            SharpMap.Layers.VectorLayer laySelected = new SharpMap.Layers.VectorLayer("Selection"); ;
            CustomTheme myTheme = new CustomTheme(FeatureColoured);
            ShapeFile vecshp = (ShapeFile)veclayer.DataSource;
            ShapeFile shp = vecshp;

            if (!shp.IsOpen)
                shp.Open();

            FeatureDataSet featDataSet = new FeatureDataSet();
            FeatureDataTable featDataTable = null;
            //将point的大地坐标转为经纬度
            Projection pj = new Projection();
            points = pj.GetLatLonFromXY(points,cfg.pjPara);

            //   获取feature数量
            uint featCount = (uint)shp.GetFeatureCount();
            for (uint index = 0; index < featCount; index++)
            {
                FeatureDataRow r = shp.GetFeature(index);
                GeoAPI.Geometries.Coordinate[] geomes = r.Geometry.Coordinates;
                double[] geomsX = new double[geomes.Length];
                double[] geomsY = new double[geomes.Length];
                for (int j = 0; j < geomes.Length; j++)
                {
                    geomsX[j] = geomes[j].X;
                    geomsY[j] = geomes[j].Y;
                }

                if ((points.X < geomsX.Min()) || (points.X > geomsX.Max()) || (points.Y < geomsY.Min()) || (points.Y > geomsY.Max()))
                {
                    continue;
                }

                PointF p1 = new PointF();
                p1.X = points.X;
                p1.Y = points.Y;
                if (InPolygon(geomes, p1))
                {
                    //首先把geomes传出去,供其他使用
                    ContourGeomes = geomes;
                    //如果在某区域内,选中某个区域,放入新图层
                    laySelected.DataSource = new SharpMap.Data.Providers.GeometryProvider(shp.GetFeature(index));
                    polygon = ((NetTopologySuite.Geometries.Polygon)r.Geometry);
                    laySelected.Style.Fill = new System.Drawing.SolidBrush(Color.HotPink);
                    laySelected.CoordinateTransformation = veclayer.CoordinateTransformation;
                }

            }
            return laySelected;
        }
示例#38
0
        public MeasureTool()
        {
            geometries = new List<IGeometry>();
            pointGeometries = geometries.OfType<GeoPoint>();

            pointLayer = new VectorLayer();
            pointLayer.Name = "measure";
            pointLayer.DataSource = new DataTableFeatureProvider(geometries);
            pointLayer.Style.Symbol = TrackerSymbolHelper.GenerateSimple(Pens.DarkMagenta, Brushes.Indigo, 6, 6);
            pointLayer.Visible = false;
            pointLayer.ShowInLegend = false;
        }
示例#39
0
 public void EnablingChildLayerBubblesOnePropertyChangedEvent()
 {
     //this is needed to let the mapcontrol refresh see issue 2749
     int callCount = 0;
     var layerGroup = new GroupLayer();
     var childLayer = new VectorLayer();
     layerGroup.Layers.Add(childLayer);
     ((INotifyPropertyChanged)layerGroup).PropertyChanged += (sender, args) => callCount++;
     childLayer.Visible = false;
     
     Assert.AreEqual(1,callCount);
 }
示例#40
0
        private void LoadWorkspace(WorkspaceModel workspace)
        {
            mapBoxMainWindow.Map.Center   = new GeoAPI.Geometries.Coordinate(workspace.CenterX, workspace.CenterY);
            mapBoxMainWindow.Map.MapScale = workspace.Scale;

            mapBoxMainWindow.Map.Layers.Clear();

            foreach (var item in workspace.Layers)
            {
                SharpMap.Layers.VectorLayer lay1 = new SharpMap.Layers.VectorLayer(item.DbLayerModel.TableName);
                switch (item.DbLayerModel.Connection.DatabaseType)
                {
                case Models.DbType.None:
                    break;

                case Models.DbType.PostgreSQL:
                    lay1.DataSource = new SharpMap.Data.Providers.PostGIS("Server = " + item.DbLayerModel.Connection.HostOrIp + "; Port = " + item.DbLayerModel.Connection.Port + "; Database = " + item.DbLayerModel.Connection.Database + "; User Id = " + item.DbLayerModel.Connection.Username + "; Password = "******"", item.DbLayerModel.TableName, item.DbLayerModel.UniqColumnName);
                    break;

                case Models.DbType.Oracle:
                    lay1.DataSource = new SharpMap.Data.Providers.Oracle("User Id=" + item.DbLayerModel.Connection.Username + ";Password="******";Data Source=" + item.DbLayerModel.Connection.HostOrIp + "", item.DbLayerModel.TableName, item.DbLayerModel.UniqColumnName);
                    break;
                }

                Brush brushColor = new SolidBrush(item.OutlineColor);
                lay1.Style.Outline.Brush = brushColor;
                lay1.Style.Outline.Width = item.PenWidth;

                Brush brushColor2 = new SolidBrush(item.FillColor);
                lay1.Style.Fill          = brushColor2;
                lay1.Style.EnableOutline = true;

                lay1.MinVisible = item.MinVisible;
                lay1.MaxVisible = item.MaxVisible;
                lay1.Enabled    = item.DbLayerModel.IsOpen;

                mapBoxMainWindow.Map.Layers.Add(lay1);
                //mapBox1.Map.ZoomToExtents();
                mapBoxMainWindow.Refresh();

                var addItem = new DbTableModelItem()
                {
                    Connection     = item.DbLayerModel.Connection,
                    IsOpen         = item.DbLayerModel.IsOpen,
                    TableName      = item.DbLayerModel.TableName,
                    UniqColumnName = item.DbLayerModel.UniqColumnName
                };

                this.OpenedTables.Add(addItem);

                LoadLayerList();
            }
        }
        private void AddSineCurveLayers(Map map, LabelLayerMode mode,
                                        LabelStyle.HorizontalAlignmentEnum hzAlign,
                                        LabelStyle.VerticalAlignmentEnum vtAlign)
        {
            string text;

            switch (mode)
            {
            case LabelLayerMode.SineCurveExtended:
                text =
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam";    //", quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
                break;

            default:
                text = "Lorem ipsum olor sit amet, consectetur adipisici elit";
                break;
            }

            var fdt = new SharpMap.Data.FeatureDataTable();

            fdt.BeginInit();
            fdt.Columns.Add(new System.Data.DataColumn("ID", typeof(int)));
            fdt.Columns.Add(new System.Data.DataColumn("LABEL", typeof(string)));
            fdt.PrimaryKey = new[] { fdt.Columns[0] };
            fdt.EndInit();
            fdt.BeginLoadData();
            var fdr = (SharpMap.Data.FeatureDataRow)fdt.LoadDataRow(new object[] { 1, text }, true);

            fdr.Geometry = CreateSineLine(new GeoAPI.Geometries.Coordinate(10, 10));
            fdt.EndLoadData();

            var vLyr = new SharpMap.Layers.VectorLayer("Geometry", new GeometryFeatureProvider(fdt));

            vLyr.Style.Line    = new System.Drawing.Pen(System.Drawing.Color.Black, 4);
            vLyr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            vLyr.SRID          = map.SRID;
            map.Layers.Add(vLyr);

            var lLyr = new SharpMap.Layers.LabelLayer("Label")
            {
                DataSource = vLyr.DataSource, LabelColumn = "LABEL"
            };

            lLyr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            lLyr.Style.ForeColor   = System.Drawing.Color.Cyan;
            lLyr.Style.BackColor   = new SolidBrush(Color.FromArgb(128, Color.LightSlateGray));
            //lLyr.Style.Halo = new Pen(Color.Yellow, 4);
            lLyr.Style.IgnoreLength        = mode == LabelLayerMode.SineCurveExtended;
            lLyr.Style.HorizontalAlignment = hzAlign;
            lLyr.Style.VerticalAlignment   = vtAlign;
            //ll.Style.IsTextOnPath = textOnPath;
            map.Layers.Add(lLyr);
        }
示例#42
0
        private static VectorLayer CrearCapaSelPlanta(VectorLayer capaBase, List <Geometry> lp)
        {
            VectorLayer capaSelPlanta = new SharpMap.Layers.VectorLayer(NOMCAPA_CONSULTA);

            SharpMap.Data.Providers.GeometryProvider provGeo = new SharpMap.Data.Providers.GeometryProvider(lp);
            provGeo.SRID             = capaBase.SRID;
            capaSelPlanta.DataSource = provGeo;
            SimbLaySelPlanta s = new SimbLaySelPlanta();

            capaSelPlanta.Enabled = s.visible;
            capaSelPlanta.Style   = ObtenerEstilo(TipoPaleta.predeterminada, s);
            AsignarEntradaLeyendaConsulta(NOMCAPA_CONSULTA, capaSelPlanta, s.titulo);
            return(capaSelPlanta);
        }
示例#43
0
        private static VectorLayer CrearCapaSelEst(VectorLayer capaBase, Estancia est)
        {
            //Layer de la estancia seleccionada en el arbol de estancias
            VectorLayer capaSelEst = new SharpMap.Layers.VectorLayer(est.Codigo);

            SharpMap.Data.Providers.GeometryProvider provGeo = new SharpMap.Data.Providers.GeometryProvider(est.Geometria);
            provGeo.SRID          = capaBase.SRID;
            capaSelEst.DataSource = provGeo;
            SimbLaySelEst s = new SimbLaySelEst();

            capaSelEst.Enabled = s.visible;
            capaSelEst.Style   = ObtenerEstilo(TipoPaleta.predeterminada, s);
            AsignarEntradaLeyendaSeleccion(capaSelEst.LayerName, capaSelEst, s.titulo);
            return(capaSelEst);
        }
示例#44
0
    public static SharpMap.Map InitializeWmsMap(System.Drawing.Size size)
    {
        HttpContext.Current.Trace.Write("Initializing Wms map...");

        //Initialize a new map of size 'imagesize'
        SharpMap.Map             map    = new SharpMap.Map(size);
        SharpMap.Layers.WmsLayer layWms = GetWmsLayer();
        //Set up the countries layer
        SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries");
        //Set the datasource to a shapefile in the App_data folder
        layCountries.DataSource = new SharpMap.Data.Providers.ShapeFile(HttpContext.Current.Server.MapPath(@"~\App_data\countries.shp"), true);
        //Set fill-style to green
        layCountries.Style.Fill = new SolidBrush(Color.Green);
        //Set the polygons to have a black outline
        layCountries.Style.Outline       = System.Drawing.Pens.Yellow;
        layCountries.Style.EnableOutline = true;
        layCountries.SRID = 4326;

        //Set up a country label layer
        SharpMap.Layers.LabelLayer layLabel = new SharpMap.Layers.LabelLayer("Country labels");
        layLabel.DataSource                = layCountries.DataSource;
        layLabel.Enabled                   = true;
        layLabel.LabelColumn               = "Name";
        layLabel.Style                     = new SharpMap.Styles.LabelStyle();
        layLabel.Style.ForeColor           = Color.White;
        layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 8);
        layLabel.Style.BackColor           = new System.Drawing.SolidBrush(Color.FromArgb(128, 255, 0, 0));
        layLabel.MaxVisible                = 90;
        layLabel.MinVisible                = 30;
        layLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
        layLabel.SRID = 4326;

        //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(layWms);
        map.Layers.Add(layCountries);
        map.Layers.Add(layLabel);

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

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

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
示例#45
0
 private static VectorLayer CrearCapaCentroidesEdificio(IUnidadGeoEstadistica uge)
 {
     if (uge is PlantaEdificio)
     {
         PlantaEdificio pe = (PlantaEdificio)uge;
         VectorLayer    capaCentroidesEdificio            = new SharpMap.Layers.VectorLayer(NOMCAPA_CENTROIDES);
         SharpMap.Data.Providers.PostGIS proveedorPostgis = new SharpMap.Data.Providers.PostGIS(SIGUANETDesktop.DB.DBUtils.GetPGSQLCnString(), "quest_estancias_label", "codigo");
         proveedorPostgis.DefinitionQuery  = string.Format("codigo like '{0}%'", pe.Codigo);
         capaCentroidesEdificio.DataSource = proveedorPostgis;
         return(capaCentroidesEdificio);
     }
     else
     {
         return(null);
     }
 }
示例#46
0
        private void AddShapeLayer(string name, string shapefilePath)
        {
            var shapeLayer = new SharpMap.Layers.VectorLayer("outline",
                                                             new SharpMap.Data.Providers.ShapeFile(shapefilePath))
            {
                Style =
                {
                    Fill          = System.Drawing.Brushes.Transparent,
                    Outline       = System.Drawing.Pens.Black,
                    EnableOutline = true,
                    Enabled       = true
                }
            };

            this.Layers.Add(shapeLayer);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="gMapControl"></param>
        public SharpMapMarker(GMap.NET.WindowsForms.GMapControl gMapControl)
            : base(GMap.NET.PointLatLng.Zero)
        {
            m_gMapControl = gMapControl;

            myMap = new SharpMap.Map(new System.Drawing.Size(m_gMapControl.Width, m_gMapControl.Height));

            m_shapeLayer = new SharpMap.Layers.VectorLayer("SharpMap layer" + Guid.NewGuid());
            //m_shapeLayer.Style.Outline = new System.Drawing.Pen(System.Drawing.Color.Green, 1f);
            m_shapeLayer.Style.EnableOutline = false;
            m_shapeLayer.Style.Line          = new System.Drawing.Pen(System.Drawing.Color.Blue, 1f);

            //myMap.Center = new SharpMap.Geometries.Point(121.54399, 29.868336);

            DisableRegionCheck = true;
            IsHitTestVisible   = false;
        }
示例#48
0
        private void btnMapData_Click_1(object sender, EventArgs e)
        {
            int dataSource = this.cmbStates.SelectedIndex;

            mapBox1.ShowProgressUpdate = true;

            switch (dataSource)
            {
            case 0:
                btnMapData.BackColor = Color.Green;
                SharpMap.Layers.VectorLayer vdat1 = new SharpMap.Layers.VectorLayer("StatesData1");

                vdat1.DataSource = new SharpMap.Data.Providers.ShapeFile(GetFullPathForShapeFile("50states.shp"), true);

                mapBox1.Map.Layers.Add(vdat1);

                mapBox1.Refresh();

                btnMapData.BackColor = Color.Red;


                break;

            case 1:

                btnMapData.BackColor = Color.Red;


                SharpMap.Layers.VectorLayer vdat2 = new SharpMap.Layers.VectorLayer("StatesData2");
                vdat2.DataSource = new SharpMap.Data.Providers.ShapeFile(GetFullPathForShapeFile("Query_Output.shp"), true);

                mapBox1.Map.Layers.Add(vdat2);

                mapBox1.Refresh();

                break;

            default:
                btnMapData.BackColor = Color.Yellow;
                //  SharpMap.Layers.VectorLayer vdat2 = new SharpMap.Layers.VectorLayer("StatesData2");
                // vdat2.DataSource = new SharpMap.Data.Providers.
                break;
            }//end case
        }
示例#49
0
        public void OpenTable(DbTableModelItem item)
        {
            if (!IsLayerOpen(item.TableName))
            {
                SharpMap.Layers.VectorLayer lay1 = new SharpMap.Layers.VectorLayer(item.TableName);
                switch (item.Connection.DatabaseType)
                {
                case Models.DbType.None:
                    break;

                case Models.DbType.PostgreSQL:
                    lay1.DataSource = new SharpMap.Data.Providers.PostGIS("Server = " + item.Connection.HostOrIp + "; Port = " + item.Connection.Port + "; Database = " + item.Connection.Database + "; User Id = " + item.Connection.Username + "; Password = "******"", item.TableName, item.UniqColumnName);
                    break;

                case Models.DbType.Oracle:
                    lay1.DataSource = new SharpMap.Data.Providers.Oracle("User Id=" + item.Connection.Username + ";Password="******";Data Source=" + item.Connection.HostOrIp + "", item.TableName, item.UniqColumnName);
                    break;
                }

                Random rnd        = new Random();
                int    R          = rnd.Next(0, 255);
                int    G          = rnd.Next(0, 255);
                int    B          = rnd.Next(0, 255);
                Color  col        = Color.FromArgb(R, G, B);
                Brush  brushColor = new SolidBrush(col);
                lay1.Style.Outline.Brush = brushColor;
                Color col2        = Color.FromArgb(255 - R, 255 - G, 255 - B);
                Brush brushColor2 = new SolidBrush(col2);
                lay1.Style.Fill          = brushColor2;
                lay1.Style.EnableOutline = true;

                lay1.LayerRendered += Lay1_LayerRendered;

                mapBoxMainWindow.Map.Layers.Add(lay1);
                //mapBox1.Map.ZoomToExtents();
                mapBoxMainWindow.Refresh();

                item.IsOpen = true;

                this.OpenedTables.Add(item);

                LoadLayerList();
            }
        }
示例#50
0
 private static VectorLayer CrearCapaEdificioMuro(IUnidadGeoEstadistica uge)
 {
     if (uge is PlantaEdificio)
     {
         PlantaEdificio pe = (PlantaEdificio)uge;
         VectorLayer    capaEdificioMuro = new SharpMap.Layers.VectorLayer(pe.Codigo + "000");
         SharpMap.Data.Providers.PostGIS proveedorPostgis = new SharpMap.Data.Providers.PostGIS(SIGUANETDesktop.DB.DBUtils.GetPGSQLCnString(), "sig" + pe.Planta.ToString().ToLower(), "gid");
         proveedorPostgis.DefinitionQuery = string.Format("codigo = '{0}000'", pe.Codigo);
         capaEdificioMuro.DataSource      = proveedorPostgis;
         SimbLayEdificioMuro s = new SimbLayEdificioMuro();
         capaEdificioMuro.Enabled = s.visible;
         capaEdificioMuro.Style   = ObtenerEstilo(TipoPaleta.predeterminada, s);
         NuevaEntradaLeyendaBD(capaEdificioMuro.LayerName, capaEdificioMuro, s.titulo);
         return(capaEdificioMuro);
     }
     else
     {
         return(null);
     }
 }
示例#51
0
        //void mapBox1_MouseClick(object sender, MouseEventArgs e)
        //{
        //    if (mouseState == "query")
        //    {
        //        GeoAPI.Geometries.Coordinate coord = this.mapBox1.Map.ImageToWorld(new PointF(e.X, e.Y));
        //        FeatureDataSet ds;
        //        ds = QueryMapByClick(coord);
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            string s = "";
        //            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
        //            {
        //                s = s + dr[i].ToString() + ",";
        //            }
        //            MessageBox.Show(s);
        //            //Console.WriteLine(s);
        //        }
        //    }

        //}

        private FeatureDataSet QueryMapByClick(GeoAPI.Geometries.Coordinate coord)
        {
            FeatureDataSet ds = new FeatureDataSet();

            SharpMap.Layers.VectorLayer vlayer = this.mapBox1.Map.Layers[0] as VectorLayer;
            if (!vlayer.DataSource.IsOpen)
            {
                vlayer.DataSource.Open();
            }

            GeoAPI.Geometries.Envelope env = new GeoAPI.Geometries.Envelope();
            env.Init(coord.X - 0.01, coord.X + 0.01, coord.Y - 0.01, coord.Y + 0.01);

            vlayer.DataSource.ExecuteIntersectionQuery(env, ds);
            if (ds.Tables.Count > 0)
            {
                ShowSelectLayer(ds.Tables[0]);
            }
            return(ds);
        }
示例#52
0
        private void InitializeMapAndEnableControls()
        {
            btnMapData.Enabled = true;
            cmbStates.Enabled  = true;


            SharpMap.Layers.VectorLayer vlay = new SharpMap.Layers.VectorLayer("State_Name");
            vlay.DataSource = new SharpMap.Data.Providers.ShapeFile(GetFullPathForShapeFile("states.shp"), true);

            SharpMap.Layers.VectorLayer vdatlay = new SharpMap.Layers.VectorLayer("dat1");

            //String datFile = "C:\\test\\st99_d00a.dat";
            //String datFile = @"C:\Users\Steven\Downloads\Shape_Files\test\st99_d00a.dat";

            mapBox1.Map.Layers.Add(vlay);
            //mapBox1.ForeColor = Color.SeaGreen;
            mapBox1.Map.BackColor = Color.Wheat;

            mapBox1.Map.ZoomToExtents();
            mapBox1.Refresh();
        }
示例#53
0
        public void AddDbLayer(DbTableModel table)
        {
            if (!IsLayerOpen(table.TableName))
            {
                string idColumn = "MI_PRINX";
                SharpMap.Layers.VectorLayer lay1 = new SharpMap.Layers.VectorLayer(table.TableName);
                switch (table.Db.DbType)
                {
                case DbModelType.None:
                    break;

                case DbModelType.Postgresql:
                    lay1.DataSource = new SharpMap.Data.Providers.PostGIS(Program.mainForm.ConnectionStringPostgis, table.TableName, idColumn);
                    break;

                case DbModelType.Oracle:
                    lay1.DataSource = new SharpMap.Data.Providers.Oracle(Program.mainForm.ConnectionStringOracle, table.TableName, idColumn);
                    break;
                }

                Random rnd        = new Random();
                int    R          = rnd.Next(0, 255);
                int    G          = rnd.Next(0, 255);
                int    B          = rnd.Next(0, 255);
                Color  col        = Color.FromArgb(R, G, B);
                Brush  brushColor = new SolidBrush(col);
                lay1.Style.Outline.Brush = brushColor;
                Color col2        = Color.FromArgb(255 - R, 255 - G, 255 - B);
                Brush brushColor2 = new SolidBrush(col2);
                lay1.Style.Fill          = brushColor2;
                lay1.Style.EnableOutline = true;
                mapBox1.Map.Layers.Add(lay1);
                //mapBox1.Map.ZoomToExtents();
                mapBox1.Refresh();

                table.IsOpen = true;

                LoadLayerList();
            }
        }
示例#54
0
        private void button1_Click(object sender, EventArgs e)
        {
            var theShortestPath = TheRoutingEngine.PerformShortestPathAnalysis(false);

            if (theShortestPath == null)
            {
                label4.Text = "No Path Found.";
                System.Diagnostics.Debug.WriteLine("Either a problem occured or there was no connecting path.");
            }
            else
            {
                // THIS NEXT BIT ONLY DISPLAYS THE PATH ON THE MAP, AND SOME PATH LENGTH INFORMATION
                RemoveShortestPathLineFromMapIfPresent();
                SharpMap.Layers.VectorLayer GraphicsLayer = GetGraphicsLayer(theShortestPath);
                mapBox1.Map.Layers.Add(GraphicsLayer);
                mapBox1.Refresh();
                mapBox1.Update();
                label4.Text = "Shortest Path Length: " + Math.Round(theShortestPath.Length, 2);
            }

            // END OF MAP DISPLAY BIT
        }
示例#55
0
文件: Theming.cs 项目: cugkgq/Project
        public void TestSymbolSelectionTheming()
        {
            //Create a map
            SharpMap.Map map = new SharpMap.Map(new System.Drawing.Size(720, 360));

            //Create some random sample data
            SharpMap.Data.FeatureDataTable fdt =
                cd.CreatePointFeatureDataTableFromArrays(cd.GetRandomOrdinates(80, -180, 180),
                                                         cd.GetRandomOrdinates(80, -90, 90), null);

            //Add rotation column and fill with random rotation values
            fdt.Columns.Add("Symbol", typeof(System.Byte[]));
            foreach (SharpMap.Data.FeatureDataRow row in fdt.Rows)
            {
                row["Symbol"] = RandomSymbol((int)System.Math.Floor(cd.RandomNumberGenerator.NextDouble() * 360d));
            }


            //Create layer and datasource
            SharpMap.Layers.VectorLayer vl = new SharpMap.Layers.VectorLayer("Points", new SharpMap.Data.Providers.FeatureProvider(fdt));

            //Create default style
            SharpMap.Styles.VectorStyle defaultStyle = new SharpMap.Styles.VectorStyle();
            defaultStyle.Symbol      = new System.Drawing.Bitmap(@"..\..\..\DemoWinForm\Resources\flag.png");
            defaultStyle.SymbolScale = 0.5f;

            //Create theming class and apply to layer
            SymbolFromFeatureDataRowTheming srt = new SymbolFromFeatureDataRowTheming("Symbol", defaultStyle);

            vl.Theme = new SharpMap.Rendering.Thematics.CustomTheme(srt.GetRotatedSymol);

            map.Layers.Add(vl);
            map.ZoomToExtents();
            System.Drawing.Image mapImage = map.GetMap();
            mapImage.Save("SymbolFromFDR.bmp");
        }
示例#56
0
    public static SharpMap.Map InitializeMapOgr(System.Drawing.Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

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

        //Set up the countries layer
        SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries");
        //Set the datasource to a shapefile in the App_data folder
        try
        {
            layCountries.DataSource = new SharpMap.Data.Providers.Ogr(HttpContext.Current.Server.MapPath(@"~\App_data\MapInfo\countriesMapInfo.tab"));
        }
        catch (Exception 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';.");
            }
        }

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

        //Set up a river layer
        SharpMap.Layers.VectorLayer layRivers = new SharpMap.Layers.VectorLayer("Rivers");
        //Set the datasource to a shapefile in the App_data folder
        layRivers.DataSource = new SharpMap.Data.Providers.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
        SharpMap.Layers.VectorLayer layCities = new SharpMap.Layers.VectorLayer("Cities");
        //Set the datasource to a shapefile in the App_data folder
        layCities.DataSource = new SharpMap.Data.Providers.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
        SharpMap.Layers.LabelLayer layLabel = new SharpMap.Layers.LabelLayer("Country labels");
        layLabel.DataSource                = layCountries.DataSource;
        layLabel.Enabled                   = true;
        layLabel.LabelColumn               = "Name";
        layLabel.Style                     = new SharpMap.Styles.LabelStyle();
        layLabel.Style.ForeColor           = Color.White;
        layLabel.Style.Font                = new Font(FontFamily.GenericSerif, 12);
        layLabel.Style.BackColor           = new System.Drawing.SolidBrush(Color.FromArgb(128, 255, 0, 0));
        layLabel.MaxVisible                = 90;
        layLabel.MinVisible                = 30;
        layLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
        layLabel.SRID = 4326;
        layLabel.MultipartGeometryBehaviour = SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest;

        //Set up a city label layer
        SharpMap.Layers.LabelLayer layCityLabel = new SharpMap.Layers.LabelLayer("City labels");
        layCityLabel.DataSource                = layCities.DataSource;
        layCityLabel.Enabled                   = true;
        layCityLabel.LabelColumn               = "Name";
        layCityLabel.Style                     = new SharpMap.Styles.LabelStyle();
        layCityLabel.Style.ForeColor           = Color.Black;
        layCityLabel.Style.Font                = new Font(FontFamily.GenericSerif, 11);
        layCityLabel.MaxVisible                = layLabel.MinVisible;
        layCityLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Left;
        layCityLabel.Style.VerticalAlignment   = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Bottom;
        layCityLabel.Style.Offset              = new PointF(3, 3);
        layCityLabel.Style.Halo                = new Pen(Color.Yellow, 2);
        layCityLabel.TextRenderingHint         = System.Drawing.Text.TextRenderingHint.AntiAlias;
        layCityLabel.SmoothingMode             = SmoothingMode.AntiAlias;
        layCityLabel.SRID        = 4326;
        layCityLabel.LabelFilter = SharpMap.Rendering.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 SharpMap.Geometries.Point(0, 0);

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }
示例#57
0
        private void readFromCSVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();

            file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            file.Filter           = "Csv File |*.csv";
            file.Multiselect      = false;

            if (file.ShowDialog() == DialogResult.OK)
            {
                string FileName = file.SafeFileName.Replace(".csv", "");
                string FilePath = file.FileName;

                string encoding  = "UTF-8";
                string seperator = "##";
                int    index     = 0;

                using (StreamReader reader = new StreamReader(FilePath, Encoding.GetEncoding(encoding)))
                {
                    DataTable dt = new DataTable();

                    var dtFeature = new SharpMap.Data.FeatureDataTable();

                    WKTReader wktreader = new WKTReader();

                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        var data = line.Split(new string[] { seperator }, StringSplitOptions.None);

                        if (index == 0)
                        {
                            for (int i = 0; i < data.Length; i++)
                            {
                                dtFeature.Columns.Add(data[i], typeof(string));
                                dt.Columns.Add(data[i], typeof(string));
                            }
                        }
                        else
                        {
                            DataRow dr = dt.NewRow();
                            SharpMap.Data.FeatureDataRow drFeature = dtFeature.NewRow();

                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                dr[i] = data[i];

                                if (dt.Columns[i].Caption == "geom_wkt")
                                {
                                    drFeature[i] = data[i];
                                    if (!string.IsNullOrEmpty(data[i]))
                                    {
                                        IGeometry geom = wktreader.Read(data[i]);

                                        drFeature.Geometry = geom;
                                    }
                                }
                                else
                                {
                                    drFeature[i] = data[i];
                                }
                            }
                            dt.Rows.Add(dr);
                            dtFeature.Rows.Add(drFeature);
                        }

                        index++;
                    }

                    //Collection<IGeometry> geometry = new Collection<IGeometry>();
                    //VectorLayer layer = new VectorLayer(FileName);

                    //for (int i = 0; i < dt.Rows.Count; i++)
                    //{
                    //    if (!string.IsNullOrEmpty(dt.Rows[i]["geom_wkt"].ToString()))
                    //    {
                    //        IGeometry geom = wktreader.Read(dt.Rows[i]["geom_wkt"].ToString());

                    //        geometry.Add(geom);
                    //    }
                    //}

                    var gfp = new GeometryFeatureProvider(dtFeature);

                    var layer = new SharpMap.Layers.VectorLayer(FileName, gfp);
                    layer.DataSource.SRID = 3857;

                    mapBox1.Map.Layers.Add(layer);

                    listBoxLayerList.Items.Add(FileName);

                    var labelLayer = new LabelLayer(FileName + "-Label");
                    labelLayer.DataSource  = gfp;
                    labelLayer.LabelColumn = "kapi_kodu";

                    //mapBox1.Map.Layers.Add(labelLayer);

                    //var provider = new GeometryProvider(geometry);
                    //layer.DataSource = provider;
                    //layer.DataSource.SRID = 3857;

                    //mapBox1.Map.Layers.Add(layer);

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

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

            map.Layers.Add(tileLayer);

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

            using (var cn = new System.Data.OleDb.OleDbConnection(xlsPath))
            {
                cn.Open();
                using (var da = new System.Data.OleDb.OleDbDataAdapter(new System.Data.OleDb.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
            var ctf      = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();
            var cf       = new ProjNet.CoordinateSystems.CoordinateSystemFactory();
            var 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\"]]");
            var epsg3785 = 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\",\"3785\"]]");
            var ct       = ctf.CreateFromCoordinateSystems(epsg4326, epsg3785);
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value)
                {
                    continue;
                }
                double[] coords = new double[] { 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 epsg3785 = new DotSpatial.Projections.ProjectionInfo();
            epsg3785.ReadEsriString("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\",\"3785\"]]");
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value)
                {
                    continue;
                }
                double[] coords = new double[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"]) };
                DotSpatial.Projections.Reproject.ReprojectPoints(coords, null, epsg4326, epsg3785, 0, 1);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }
#endif
            //Add Rotation Column
            ds.Tables[0].Columns.Add("Rotation", typeof(float));
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                row["Rotation"] = -angle;
            }

            //Set up provider
            var xlsProvider = new SharpMap.Data.Providers.DataTablePoint(ds.Tables[0], "OID", "X", "Y");
            var xlsLayer    = new SharpMap.Layers.VectorLayer("XLS", xlsProvider);
            xlsLayer.Style.Symbol = SharpMap.Styles.VectorStyle.DefaultSymbol;

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

            map.ZoomToBox(tileLayer.Envelope);

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

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

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

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

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

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

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

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

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

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

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

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

            map.ZoomToExtents(); // = 360;

            Matrix mat = new Matrix();

            mat.RotateAt(angle, map.WorldToImage(map.Center));
            map.MapTransform = mat;
            //map.Center = new SharpMap.Geometries.Point(0, 0);

            return(map);
        }
示例#60
0
    public static Map InitializeMapPostGis(Size size)
    {
        HttpContext.Current.Trace.Write("Initializing map...");

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

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

        //Set up the countries layer
        SharpMap.Layers.VectorLayer layCountries = new SharpMap.Layers.VectorLayer("Countries");
        //Set the datasource to a new MsSqlSpatialProvider
        layCountries.DataSource = new SharpMap.Data.Providers.PostGIS(connectionString, "countries", "wkb_geometry", "ogc_fid");

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

        //Set up a river layer
        SharpMap.Layers.VectorLayer layRivers = new SharpMap.Layers.VectorLayer("Rivers");
        //Set the datasource to a new MsSqlSpatialProvider
        layRivers.DataSource = new SharpMap.Data.Providers.PostGIS(connectionString, "rivers", "wkb_geometry", "ogc_fid");
        //Define a blue 1px wide pen
        layRivers.Style.Line = new Pen(Color.Blue, 1);

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

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

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


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


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

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

        HttpContext.Current.Trace.Write("Map initialized");
        return(map);
    }