Пример #1
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public Collection <uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
        {
            Collection <uint> objectlist = new Collection <uint>();

            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                string strSQL = "SELECT * FROM ST.FilterQuery('" + this.Table + "', '" + this.GeometryColumn + "', " + this.BuildEnvelope(bbox) + ")";

                if (!String.IsNullOrEmpty(_definitionQuery))
                {
                    strSQL += " WHERE " + this.DefinitionQuery;
                }

                using (SqlCommand command = new SqlCommand(strSQL, conn))
                {
                    conn.Open();
                    using (SqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            if (dr[0] != DBNull.Value)
                            {
                                uint ID = (uint)(int)dr[0];
                                objectlist.Add(ID);
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(objectlist);
        }
Пример #2
0
        /// <summary>
        /// Returns the data associated with all the geometries that are intersected by 'geom'.
        /// Please note that the ShapeFile provider currently doesn't fully support geometryintersection
        /// and thus only BoundingBox/BoundingBox querying are performed. The results are NOT
        /// guaranteed to lie withing 'geom'.
        /// </summary>
        /// <param name="geom"></param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds)
        {
            SharpMap.Data.FeatureDataTable  dt   = (SharpMap.Data.FeatureDataTable)dbaseFile.NewTable;
            SharpMap.Geometries.BoundingBox bbox = geom.GetBoundingBox();
            //Get candidates by intersecting the spatial index tree
            List <uint> objectlist = tree.Search(bbox);

            if (objectlist.Count == 0)
            {
                return;
            }

            for (int j = 0; j < objectlist.Count; j++)
            {
                for (uint i = (uint)dt.Rows.Count - 1; i >= 0; i--)
                {
                    FeatureDataRow fdr = GetFeature(objectlist[j], dt);
                    if (fdr.Geometry != null)
                    {
                        if (fdr.Geometry.GetBoundingBox().Intersects(bbox))
                        {
                            //replace above line with this:  if(fdr.Geometry.Intersects(bbox))  when relation model is complete
                            if (FilterDelegate == null || FilterDelegate(fdr))
                            {
                                dt.AddRow(fdr);
                            }
                        }
                    }
                }
            }
            ds.Tables.Add(dt);
        }
Пример #3
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public List <uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
        {
            List <uint> objectlist = new List <uint>();

            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
            {
                string strSQL = "Select " + this.ObjectIdColumn + " FROM " + this.Table + " WHERE ";
                if (_defintionQuery != null && _defintionQuery != "")
                {
                    strSQL += _defintionQuery + " AND ";
                }
                //Limit to the points within the boundingbox
                strSQL += this.XColumn + " BETWEEN " + bbox.Left.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + bbox.Right.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + this.YColumn +
                          " BETWEEN " + bbox.Bottom.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + bbox.Top.ToString(SharpMap.Map.numberFormat_EnUS);

                using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
                {
                    conn.Open();
                    using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            if (dr[0] != DBNull.Value)
                            {
                                objectlist.Add((uint)(int)dr[0]);
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(objectlist);
        }
Пример #4
0
        void m_Map_MapNewTileAvaliable(TileLayer sender, SharpMap.Geometries.BoundingBox box, Bitmap bm, int sourceWidth, int sourceHeight, ImageAttributes imageAttributes)
        {
            lock (m_ImageStatic)
            {
                try
                {
                    PointF min = m_Map.WorldToImage(new Geometries.Point(box.Min.X, box.Min.Y));
                    PointF max = m_Map.WorldToImage(new Geometries.Point(box.Max.X, box.Max.Y));

                    min = new PointF((float)Math.Round(min.X), (float)Math.Round(min.Y));
                    max = new PointF((float)Math.Round(max.X), (float)Math.Round(max.Y));

                    if (this.IsDisposed == false)
                    {
                        Graphics g = Graphics.FromImage(this.m_ImageStatic);

                        g.DrawImage(bm,
                                    new Rectangle((int)min.X, (int)max.Y, (int)(max.X - min.X), (int)(min.Y - max.Y)),
                                    0, 0,
                                    sourceWidth, sourceHeight,
                                    GraphicsUnit.Pixel,
                                    imageAttributes);

                        g.Dispose();
                        UpdateImage(false);
                    }
                }
                catch (Exception ex)
                {
                    //this can be a GDI+ Hell Exception...
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Boundingbox of dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public SharpMap.Geometries.BoundingBox GetExtents()
        {
            SharpMap.Geometries.BoundingBox box = null;
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
            {
                string strSQL = "Select Min(" + this.XColumn + ") as MinX, Min(" + this.YColumn + ") As MinY, " +
                                "Max(" + this.XColumn + ") As MaxX, Max(" + this.YColumn + ") As MaxY FROM " + this.Table;
                if (_defintionQuery != null && _defintionQuery != "")                 //If a definition query has been specified, add this as a filter on the query
                {
                    strSQL += " WHERE " + _defintionQuery;
                }

                using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
                {
                    conn.Open();
                    using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
                    {
                        if (dr.Read())
                        {
                            //If the read row is OK, create a point geometry from the XColumn and YColumn and return it
                            if (dr[0] != DBNull.Value && dr[1] != DBNull.Value && dr[2] != DBNull.Value && dr[3] != DBNull.Value)
                            {
                                box = new SharpMap.Geometries.BoundingBox((double)dr[0], (double)dr[1], (double)dr[2], (double)dr[3]);
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(box);
        }
 private string GetFileName(SharpMap.Geometries.BoundingBox boundingBox)
 {
     return(String.Format("{0}/{1}_{2}_{3}_{4}.{5}", directory,
                          boundingBox.Left.ToString("r", cultureInfo), boundingBox.Top.ToString("r", cultureInfo),
                          boundingBox.Right.ToString("r", cultureInfo), boundingBox.Bottom.ToString("r", cultureInfo),
                          "png"));
 }
Пример #7
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public List <uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
        {
            List <uint> objectlist = new List <uint>();

            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                string strSQL = "SELECT " + this.ObjectIdColumn + " ";
                strSQL += "FROM " + this.Table + " WHERE ";

                strSQL += GetBoxClause(bbox);

                if (_defintionQuery != null && _defintionQuery != "")
                {
                    strSQL += " AND " + this.DefinitionQuery + " AND ";
                }

                using (SqlCommand command = new SqlCommand(strSQL, conn))
                {
                    conn.Open();
                    using (SqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            if (dr[0] != DBNull.Value)
                            {
                                uint ID = (uint)(int)dr[0];
                                objectlist.Add(ID);
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(objectlist);
        }
Пример #8
0
        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();
        }
Пример #9
0
 /// <summary>
 /// Boundingbox of dataset
 /// </summary>
 /// <returns>boundingbox</returns>
 public SharpMap.Geometries.BoundingBox GetExtents()
 {
     using (SqlConnection conn = new SqlConnection(_ConnectionString))
     {
         string strSQL = "SELECT g." + this.GeometryColumn + ".STEnvelope().STAsText() FROM " + this.Table + " g ";
         if (!String.IsNullOrEmpty(_defintionQuery))
         {
             strSQL += " WHERE " + this.DefinitionQuery;
         }
         using (SqlCommand command = new SqlCommand(strSQL, conn))
         {
             conn.Open();
             //SharpMap.Geometries.Geometry geom = null;
             SharpMap.Geometries.BoundingBox bx = null;
             SqlDataReader dr = command.ExecuteReader();
             while (dr.Read())
             {
                 string wkt = dr.GetString(0); //[this.GeometryColumn];
                 SharpMap.Geometries.Geometry    g  = SharpMap.Converters.WellKnownText.GeometryFromWKT.Parse(wkt);
                 SharpMap.Geometries.BoundingBox bb = g.GetBoundingBox();
                 if (bx == null)
                 {
                     bx = bb;
                 }
                 else
                 {
                     bx = bx.Join(bb);
                 }
             }
             dr.Close();
             conn.Close();
             return(bx);
         }
     }
 }
Пример #10
0
        /// <summary>
        /// Searches the tree and looks for intersections with the boundingbox 'bbox'
        /// </summary>
        /// <param name="box">Boundingbox to intersect with</param>
        public Collection <uint> Search(SharpMap.Geometries.BoundingBox box)
        {
            Collection <uint> objectlist = new Collection <uint>();

            IntersectTreeRecursive(box, this, ref objectlist);
            return(objectlist);
        }
Пример #11
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
        {
            List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>();

            using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(_ConnectionString))
            {
                string strBbox = "box2d('BOX3D(" +
                                 bbox.Min.X.ToString(SharpMap.Map.numberFormat_EnUS) + " " +
                                 bbox.Min.Y.ToString(SharpMap.Map.numberFormat_EnUS) + "," +
                                 bbox.Max.X.ToString(SharpMap.Map.numberFormat_EnUS) + " " +
                                 bbox.Max.Y.ToString(SharpMap.Map.numberFormat_EnUS) + ")'::box3d)";
                if (this.SRID > 0)
                {
                    strBbox = "setSRID(" + strBbox + "," + this.SRID.ToString(Map.numberFormat_EnUS) + ")";
                }

                string strSQL = "SELECT *, AsBinary(" + this.GeometryColumn + ") AS sharpmap_tempgeometry ";
                strSQL += "FROM " + this.Table + " WHERE ";

                if (!String.IsNullOrEmpty(_defintionQuery))
                {
                    strSQL += this.DefinitionQuery + " AND ";
                }

                strSQL += this.GeometryColumn + " && " + strBbox;

                using (Npgsql.NpgsqlDataAdapter adapter = new Npgsql.NpgsqlDataAdapter(strSQL, conn))
                {
                    conn.Open();
                    System.Data.DataSet ds2 = new System.Data.DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
                        {
                            SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                            foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }
                            fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Reads and parses the header of the .shx index file
        /// </summary>
        private void ParseHeader()
        {
            fsShapeIndex = new FileStream(_Filename.Remove(_Filename.Length - 4, 4) + ".shx", FileMode.Open, FileAccess.Read);
            brShapeIndex = new BinaryReader(fsShapeIndex, System.Text.Encoding.Unicode);

            brShapeIndex.BaseStream.Seek(0, 0);
            //Check file header
            if (brShapeIndex.ReadInt32() != 170328064)             //File Code is actually 9994, but in Little Endian Byte Order this is '170328064'
            {
                throw (new ApplicationException("Invalid Shapefile Index (.shx)"));
            }

            brShapeIndex.BaseStream.Seek(24, 0);                         //seek to File Length
            int IndexFileSize = SwapByteOrder(brShapeIndex.ReadInt32()); //Read filelength as big-endian. The length is based on 16bit words

            _FeatureCount = (2 * IndexFileSize - 100) / 8;               //Calculate FeatureCount. Each feature takes up 8 bytes. The header is 100 bytes

            brShapeIndex.BaseStream.Seek(32, 0);                         //seek to ShapeType
            _ShapeType = (ShapeType)brShapeIndex.ReadInt32();

            //Read the spatial bounding box of the contents
            brShapeIndex.BaseStream.Seek(36, 0);             //seek to box
            _Envelope = new SharpMap.Geometries.BoundingBox(brShapeIndex.ReadDouble(), brShapeIndex.ReadDouble(), brShapeIndex.ReadDouble(), brShapeIndex.ReadDouble());

            brShapeIndex.Close();
            fsShapeIndex.Close();
        }
Пример #13
0
        /// <summary>
        /// Creates a node and either splits the objects recursively into sub-nodes, or stores them at the node depending on the heuristics.
        /// Tree is built top->down
        /// </summary>
        /// <param name="objList">Geometries to index</param>
        /// <param name="depth">Current depth of tree</param>
        /// <param name="heurdata">Heuristics data</param>
        public QuadTree(List <BoxObjects> objList, uint depth, Heuristic heurdata)
        {
            _Depth = depth;

            _box = objList[0].box;
            for (int i = 0; i < objList.Count; i++)
            {
                _box = _box.Join(objList[i].box);
            }

            // test our build heuristic - if passes, make children
            if (depth < heurdata.maxdepth && objList.Count > heurdata.mintricnt &&
                (objList.Count > heurdata.tartricnt || ErrorMetric(_box) > heurdata.minerror))
            {
                List <BoxObjects>[] objBuckets = new List <BoxObjects> [2];              // buckets of geometries
                objBuckets[0] = new List <BoxObjects>();
                objBuckets[1] = new List <BoxObjects>();

                uint   longaxis = _box.LongestAxis; // longest axis
                double geoavg   = 0;                // geometric average - midpoint of ALL the objects

                // go through all bbox and calculate the average of the midpoints
                double frac = 1.0f / objList.Count;
                for (int i = 0; i < objList.Count; i++)
                {
                    geoavg += objList[i].box.GetCentroid()[longaxis] * frac;
                }

                // bucket bbox based on their midpoint's side of the geo average in the longest axis
                for (int i = 0; i < objList.Count; i++)
                {
                    objBuckets[geoavg > objList[i].box.GetCentroid()[longaxis] ? 1 : 0].Add(objList[i]);
                }

                //If objects couldn't be splitted, just store them at the leaf
                //TODO: Try splitting on another axis
                if (objBuckets[0].Count == 0 || objBuckets[1].Count == 0)
                {
                    _child0 = null;
                    _child1 = null;
                    // copy object list
                    _objList = objList;
                }
                else
                {
                    // create new children using the buckets
                    _child0 = new QuadTree(objBuckets[0], depth + 1, heurdata);
                    _child1 = new QuadTree(objBuckets[1], depth + 1, heurdata);
                }
            }
            else
            {
                // otherwise the build heuristic failed, this is
                // set the first child to null (identifies a leaf)
                _child0 = null;
                _child1 = null;
                // copy object list
                _objList = objList;
            }
        }
Пример #14
0
        /// <summary>
        /// Returns the data associated with all the geometries that are intersected by 'geom'
        /// </summary>
        /// <param name="bbox">Geometry to intersect with</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, FeatureDataSet ds)
        {
            FeatureDataTable myDt = new FeatureDataTable();

            _OgrLayer.SetSpatialFilterRect(bbox.Left, bbox.Bottom, bbox.Right, bbox.Top);

            //reads the column definition of the layer/feature
            this.ReadColumnDefinition(myDt, _OgrLayer);

            OGR.Feature _OgrFeature;
            _OgrLayer.ResetReading();
            while ((_OgrFeature = _OgrLayer.GetNextFeature()) != null)
            {
                FeatureDataRow _dr = myDt.NewRow();
                for (int iField = 0; iField < _OgrFeature.GetFieldCount(); iField++)
                {
                    if (myDt.Columns[iField].DataType == System.Type.GetType("System.String"))
                    {
                        _dr[iField] = _OgrFeature.GetFieldAsString(iField);
                    }
                    else if (myDt.Columns[iField].GetType() == System.Type.GetType("System.Int32"))
                    {
                        _dr[iField] = _OgrFeature.GetFieldAsInteger(iField);
                    }
                    else if (myDt.Columns[iField].GetType() == System.Type.GetType("System.Double"))
                    {
                        _dr[iField] = _OgrFeature.GetFieldAsDouble(iField);
                    }
                }

                _dr.Geometry = this.ParseOgrGeometry(_OgrFeature.GetGeometryRef());
                myDt.AddRow(_dr);
            }
            ds.Tables.Add(myDt);
        }
Пример #15
0
        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                using (IGeometry fgeom = _geomFactory.CreateGeometry(txtGeometry.Text))
                {
                    byte[] wkb = null;
                    if (!FdoGeometryUtil.Is2D(fgeom))
                    {
                        using (IGeometry ffgeom = FdoGeometryUtil.Flatten(fgeom, _geomFactory))
                        {
                            wkb = _geomFactory.GetWkb(ffgeom);
                        }
                    }
                    else
                    {
                        wkb = _geomFactory.GetWkb(fgeom);
                    }

                    SharpMap.Geometries.Geometry sgeom = SharpMap.Geometries.Geometry.GeomFromWKB(wkb);
                    _layer.DataSource = new SharpMap.Data.Providers.GeometryProvider(sgeom);
                    SharpMap.Geometries.BoundingBox bbox = _mapCtl.Map.GetExtents();
                    bbox = bbox.Grow(2.0, 2.0);
                    _mapCtl.Map.ZoomToBox(bbox);
                    _mapCtl.Refresh();
                    btnOK.Enabled = true;
                }
            }
            catch (Exception)
            {
                MessageService.ShowError("The specified text does not constitute a valid geometry");
                btnOK.Enabled = false;
            }
        }
Пример #16
0
        /// <summary>
        /// Returns geometries within the specified bounding box
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public List <SharpMap.Geometries.Geometry> GetGeometriesInView(SharpMap.Geometries.BoundingBox bbox)
        {
            List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>();

            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
            {
                string strSQL = "Select " + this.XColumn + ", " + this.YColumn + " FROM " + this.Table + " WHERE ";
                if (_defintionQuery != null && _defintionQuery != "")
                {
                    strSQL += _defintionQuery + " AND ";
                }
                //Limit to the points within the boundingbox
                strSQL += this.XColumn + " BETWEEN " + bbox.Left.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + bbox.Right.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " +
                          this.YColumn + " BETWEEN " + bbox.Bottom.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + bbox.Top.ToString(SharpMap.Map.numberFormat_EnUS);

                using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
                {
                    conn.Open();
                    using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            if (dr[0] != DBNull.Value && dr[1] != DBNull.Value)
                            {
                                features.Add(new SharpMap.Geometries.Point((double)dr[0], (double)dr[1]));
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(features);
        }
Пример #17
0
 public void GetExtents_ValidDatasource()
 {
     SharpMap.Map map = new SharpMap.Map(new System.Drawing.Size(400, 200));
     SharpMap.Layers.VectorLayer vLayer = new SharpMap.Layers.VectorLayer("Geom layer", CreateDatasource());
     map.Layers.Add(vLayer);
     SharpMap.Geometries.BoundingBox box = map.GetExtents();
     Assert.AreEqual(new SharpMap.Geometries.BoundingBox(0, 0, 50, 346.3493254), box);
 }
Пример #18
0
 /// <summary>
 /// Zooms the map to fit a bounding box
 /// </summary>
 /// <remarks>
 /// NOTE: If the aspect ratio of the box and the aspect ratio of the mapsize
 /// isn't the same, the resulting map-envelope will be adjusted so that it contains
 /// the bounding box, thus making the resulting envelope larger!
 /// </remarks>
 /// <param name="bbox"></param>
 public void ZoomToBox(SharpMap.Geometries.BoundingBox bbox)
 {
     this._Zoom = bbox.Width;             //Set the private center value so we only fire one MapOnViewChange event
     if (this.Envelope.Height < bbox.Height)
     {
         this._Zoom *= bbox.Height / this.Envelope.Height;
     }
     this.Center = bbox.GetCentroid();
 }
Пример #19
0
 /// <summary>
 /// Returns geometry Object IDs whose bounding box intersects 'bbox'
 /// </summary>
 /// <param name="bbox"></param>
 /// <returns></returns>
 public List <uint> GetObjectIDsInView(SharpMap.Geometries.BoundingBox bbox)
 {
     if (!this.IsOpen)
     {
         throw (new ApplicationException("An attempt was made to read from a closed datasource"));
     }
     //Use the spatial index to get a list of features whose boundingbox intersects bbox
     return(tree.Search(bbox));
 }
Пример #20
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
        {
            List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>();

            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                string strSQL = "SELECT " + this.FeatureColumns + ", ST.AsBinary(" + this.BuildGeometryExpression() + ") AS sharpmap_tempgeometry ";
                strSQL += "FROM ST.FilterQuery" + this.BuildSpatialQuerySuffix() + "(" + this.BuildEnvelope(bbox) + ")";

                if (!String.IsNullOrEmpty(this.DefinitionQuery))
                {
                    strSQL += " WHERE " + this.DefinitionQuery;
                }

                if (!String.IsNullOrEmpty(this.OrderQuery))
                {
                    strSQL += " ORDER BY " + this.OrderQuery;
                }

                using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn))
                {
                    conn.Open();
                    System.Data.DataSet ds2 = new System.Data.DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (col.ColumnName != this.GeometryColumn && !col.ColumnName.StartsWith(this.GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry")
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
                        {
                            SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                            foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (col.ColumnName != this.GeometryColumn && !col.ColumnName.StartsWith(this.GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry")
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }
                            if (dr["sharpmap_tempgeometry"] != DBNull.Value)
                            {
                                fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                            }
                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #21
0
 private string BuildEnvelope(SharpMap.Geometries.BoundingBox bbox)
 {
     return(string.Format(SharpMap.Map.numberFormat_EnUS,
                          "ST.MakeEnvelope({0},{1},{2},{3},{4})",
                          bbox.Min.X,
                          bbox.Min.Y,
                          bbox.Max.X,
                          bbox.Max.Y,
                          this.SRID));
 }
Пример #22
0
        public override FeatureList process(FeatureList input, FilterEnv env)
        {
            FeatureList output = new FeatureList();

            //Boolean encontrado = false;
            SharpMap.Geometries.BoundingBox boundingBox = new SharpMap.Geometries.BoundingBox(longitudeMin, latitudeMin, longitudeMax, latitudeMax);

            foreach (Feature feature in input)
            {
                //if type of features is Point
                if (feature.row.Geometry is SharpMap.Geometries.Point)
                {
                    SharpMap.Geometries.Point p = (SharpMap.Geometries.Point)feature.row.Geometry;
                    if (boundingBox.Contains(p.GetBoundingBox()))
                    {
                        output.Add(feature);
                    }
                }
                //if type of features is Polygon
                else if (feature.row.Geometry is SharpMap.Geometries.Polygon)
                {
                    SharpMap.Geometries.Polygon polygon = (SharpMap.Geometries.Polygon)feature.row.Geometry;
                    if (boundingBox.Contains(polygon.GetBoundingBox()))
                    {
                        output.Add(feature);
                    }
                }
                //if type of features is MultiPolygon
                else if (feature.row.Geometry is SharpMap.Geometries.MultiPolygon)
                {
                    SharpMap.Geometries.MultiPolygon mp = (SharpMap.Geometries.MultiPolygon)feature.row.Geometry;
                    SharpMap.Geometries.BoundingBox  bb = mp.GetBoundingBox();
                    if (boundingBox.Contains(bb))
                    {
                        output.Add(feature);
                    }
                }
            }

            if (successor != null)
            {
                if (successor is FeatureFilter)
                {
                    FeatureFilter filter = (FeatureFilter)successor;
                    FeatureList   l      = filter.process(output, env);
                }
                else if (successor is FragmentFilter)
                {
                    FragmentFilter filter = (FragmentFilter)successor;
                    FragmentList   l      = filter.process(output, env);
                }
            }

            return(output);
        }
Пример #23
0
        private static XmlElement GenerateBoundingBoxElement(SharpMap.Geometries.BoundingBox bbox, int SRID, XmlDocument doc)
        {
            XmlElement xmlBbox = doc.CreateElement("BoundingBox", wmsNamespaceURI);

            xmlBbox.Attributes.Append(CreateAttribute("minx", bbox.Left.ToString(SharpMap.Map.numberFormat_EnUS), doc));
            xmlBbox.Attributes.Append(CreateAttribute("miny", bbox.Bottom.ToString(SharpMap.Map.numberFormat_EnUS), doc));
            xmlBbox.Attributes.Append(CreateAttribute("maxx", bbox.Right.ToString(SharpMap.Map.numberFormat_EnUS), doc));
            xmlBbox.Attributes.Append(CreateAttribute("maxy", bbox.Top.ToString(SharpMap.Map.numberFormat_EnUS), doc));
            xmlBbox.Attributes.Append(CreateAttribute("CRS", "EPSG:" + SRID.ToString(), doc));
            return(xmlBbox);
        }
Пример #24
0
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox box, SharpMap.Data.FeatureDataSet ds)
        {
            Rectangle r = new Rectangle((float)box.Left, (float)box.Bottom, (float)box.Right, (float)box.Top, (float)0.0, (float)0.0);

            FdoFeature[] matches = _data.Intersects(r);

            FeatureDataTable table = new FeatureDataTable();

            foreach (DataColumn col in _data.Columns)
            {
                table.Columns.Add(col.ColumnName, col.DataType, col.Expression);
            }

            //Filter the initial result set by inverting the operands. This weeds out non-matches on point intersection tests.
            IEnvelope   env  = Converter.EnvelopeFromBoundingBox(box);
            FdoGeometry poly = new FdoGeometry(Converter.CreatePolygonFromEnvelope(env));

            foreach (FdoFeature feat in matches)
            {
                FdoGeometry geom = feat.DesignatedGeometry;
                if (geom != null)
                {
                    if (geom.Contains(env) || geom.Intersects(poly))
                    {
                        FeatureDataRow row = table.NewRow();
                        bool           add = true;
                        foreach (DataColumn col in _data.Columns)
                        {
                            if (col.ColumnName == _data.GeometryColumn)
                            {
                                try
                                {
                                    row.Geometry = Converter.FromFdoGeometry(geom, _geomFactory);
                                }
                                catch //Can't help you if you fail conversion.
                                {
                                    add = false;
                                }
                            }
                            else
                            {
                                row[col.ColumnName] = feat[col.ColumnName];
                            }
                        }
                        if (add)
                        {
                            table.AddRow(row);
                        }
                    }
                }
            }
            ds.Tables.Add(table);
        }
Пример #25
0
        /// <summary>
        /// Converts the <see cref="SharpMap.Geometries.BoundingBox"/> instance <paramref name="boundingBox"/>
        /// into a correspondant <see cref="SharpMap.Geometries.Polygon"/>.
        /// </summary>
        /// <param name="boundingBox"></param>
        /// <returns></returns>
        public static SharpMap.Geometries.Geometry ToSharpMapGeometry(SharpMap.Geometries.BoundingBox boundingBox)
        {
            Collection <SharpMap.Geometries.Point> vertices = new Collection <SharpMap.Geometries.Point>();

            vertices.Add(new SharpMap.Geometries.Point(boundingBox.Min.X, boundingBox.Min.Y));
            vertices.Add(new SharpMap.Geometries.Point(boundingBox.Max.X, boundingBox.Min.Y));
            vertices.Add(new SharpMap.Geometries.Point(boundingBox.Max.X, boundingBox.Max.Y));
            vertices.Add(new SharpMap.Geometries.Point(boundingBox.Min.X, boundingBox.Max.Y));
            vertices.Add(new SharpMap.Geometries.Point(boundingBox.Min.X, boundingBox.Min.Y));
            SharpMap.Geometries.LinearRing exterior = new SharpMap.Geometries.LinearRing(vertices);
            return(new SharpMap.Geometries.Polygon(exterior));
        }
Пример #26
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
        {
            List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>();

            using (OracleConnection conn = new OracleConnection(_ConnectionString))
            {
                //Get bounding box string
                string strBbox = GetBoxFilterStr(bbox);

                string strSQL = "SELECT g.*, g." + this.GeometryColumn + ".Get_WKB() AS sharpmap_tempgeometry ";
                strSQL += "FROM " + this.Table + " g WHERE ";

                if (!String.IsNullOrEmpty(_defintionQuery))
                {
                    strSQL += this.DefinitionQuery + " AND ";
                }

                strSQL += strBbox;

                using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn))
                {
                    conn.Open();
                    System.Data.DataSet ds2 = new System.Data.DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
                        {
                            SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                            foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }
                            fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
        {
            List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>();

            using (SqlConnection conn = new SqlConnection(_ConnectionString))
            {
                string strSQL = "SELECT *, " + this.GeometryColumn + " AS sharpmap_tempgeometry ";
                strSQL += "FROM " + this.Table + " WHERE ";
                strSQL += GetBoxClause(bbox);

                if (_defintionQuery != null && _defintionQuery != "")
                {
                    strSQL += " AND " + this.DefinitionQuery;
                }

                using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn))
                {
                    conn.Open();
                    System.Data.DataSet ds2 = new System.Data.DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_"))
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
                        {
                            SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                            foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_"))
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }
                            if (dr["sharpmap_tempgeometry"] != DBNull.Value)
                            {
                                fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                            }
                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #28
0
 private void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             Close();
             _Envelope = null;
             tree      = null;
         }
         disposed = true;
     }
 }
Пример #29
0
        private void FormDemoDrawGeometries_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);



            SharpMap.Layers.VectorLayer vl = new VectorLayer("My Geometries");
            geoProvider   = new SharpMap.Data.Providers.GeometryProvider(new List <SharpMap.Geometries.Geometry>());
            vl.DataSource = geoProvider;
            this.mapBox1.Map.Layers.Add(vl);

            /*
             * SharpMap.Geometries.BoundingBox geom =
             *     ProjNet.CoordinateSystems.Transformations.GeometryTransform.TransformBox(
             *         new SharpMap.Geometries.BoundingBox(-9.205626, 38.690993, -9.123736, 38.740837),
             *         LayerTools.Wgs84toGoogleMercator.MathTransform);
             */

#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

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

            this.mapBox1.GeometryDefined += new SharpMap.Forms.MapBox.GeometryDefinedHandler(mapBox1_GeometryDefined);

            this.mapBox1.ActiveToolChanged += new SharpMap.Forms.MapBox.ActiveToolChangedHandler(mapBox1_ActiveToolChanged);

            this.mapBox1.MouseMove += new SharpMap.Forms.MapBox.MouseEventHandler(mapBox1_MouseMove);
        }
Пример #30
0
        /// <summary>
        /// Returns all features with the view box
        /// </summary>
        /// <param name="bbox">view box</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds)
        {
            using (PgConnection conn = new PgConnection(_ConnectionString))
            {
                string strBbox = GetBoundingBoxSql(bbox, this.SRID);

                string strSQL = String.Format("SELECT *, AsBinary({0}) AS sharpmap_tempgeometry FROM {1} WHERE ",
                                              this.GeometryColumn,
                                              this.Table);

                if (!String.IsNullOrEmpty(_defintionQuery))
                {
                    strSQL += this.DefinitionQuery + " AND ";
                }

                strSQL += this.GeometryColumn + " && " + strBbox;

                using (PgDataAdapter adapter = new PgDataAdapter(strSQL, conn))
                {
                    conn.Open();
                    System.Data.DataSet ds2 = new System.Data.DataSet();
                    adapter.Fill(ds2);
                    conn.Close();
                    if (ds2.Tables.Count > 0)
                    {
                        FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]);
                        foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                        {
                            if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
                            {
                                fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression);
                            }
                        }
                        foreach (System.Data.DataRow dr in ds2.Tables[0].Rows)
                        {
                            SharpMap.Data.FeatureDataRow fdr = fdt.NewRow();
                            foreach (System.Data.DataColumn col in ds2.Tables[0].Columns)
                            {
                                if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry")
                                {
                                    fdr[col.ColumnName] = dr[col];
                                }
                            }
                            fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]);
                            fdt.AddRow(fdr);
                        }
                        ds.Tables.Add(fdt);
                    }
                }
            }
        }
Пример #31
0
        /// <summary>
        /// initialize a Gdal based raster layer
        /// </summary>
        /// <param name="strLayerName">Name of layer</param>
        /// <param name="imageFilename">location of image</param>
        public GdalRasterLayer(string strLayerName, string imageFilename)
        {
            this.LayerName = strLayerName;
            this.Filename = imageFilename;
            disposed = false;

            GDAL.gdal.AllRegister();
            try
            {
				_GdalDataset = GDAL.gdal.Open(_Filename, GDAL.gdalconst.GA_ReadOnly);
				imagesize = new Size(_GdalDataset.RasterXSize, _GdalDataset.RasterYSize);
                
				_Envelope = this.GetExtent();
            }
            catch (Exception ex) { 
                _GdalDataset = null;
                throw new Exception("Couldn't load dataset. " + ex.Message + ex.InnerException);
            }
 
        }
Пример #32
0
		/// <summary>
		/// Boundingbox of dataset
		/// </summary>
		/// <returns>boundingbox</returns>
		public SharpMap.Geometries.BoundingBox GetExtents()
		{
			SharpMap.Geometries.BoundingBox box = null;
			using (SqlConnection conn = new SqlConnection(_ConnectionString))
			{
				string strSQL = "SELECT Min(Envelope_MinX) AS MinX, Min(Envelope_MinY) AS MinY, Max(Envelope_MaxX) AS MaxX, Max(Envelope_MaxY) AS MaxY FROM " + this.Table;
				if (!String.IsNullOrEmpty(_defintionQuery))
					strSQL += " WHERE " + this.DefinitionQuery;
				using (SqlCommand command = new SqlCommand(strSQL, conn))
				{
					conn.Open();
					using (SqlDataReader dr = command.ExecuteReader())
						if (dr.Read())
						{
							box = new SharpMap.Geometries.BoundingBox((float)dr[0], (float)dr[1], (float)dr[2], (float)dr[3]);
						}
					conn.Close();
				}
				return box;
			}
		}
Пример #33
0
        /// <summary>
        /// Boundingbox of dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public SharpMap.Geometries.BoundingBox GetExtents()
        {
            SharpMap.Geometries.BoundingBox box = null;
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
            {
                string strSQL = "Select Min(" + this.XColumn + ") as MinX, Min(" + this.YColumn + ") As MinY, " +
                                       "Max(" + this.XColumn + ") As MaxX, Max(" + this.YColumn + ") As MaxY FROM " + this.Table;
                if (_defintionQuery != null && _defintionQuery != "") //If a definition query has been specified, add this as a filter on the query
                    strSQL += " WHERE " + _defintionQuery;

                using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
                {
                    conn.Open();
                    using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
                    {
                        if(dr.Read())
                        {
                            //If the read row is OK, create a point geometry from the XColumn and YColumn and return it
                            if (dr[0] != DBNull.Value && dr[1] != DBNull.Value && dr[2] != DBNull.Value && dr[3] != DBNull.Value)
                                box = new SharpMap.Geometries.BoundingBox((double)dr[0], (double)dr[1], (double)dr[2], (double)dr[3]);
                        }
                    }
                    conn.Close();
                }
            }
            return box;
        }
Пример #34
0
        public SharpMap.Geometries.BoundingBox GetExtents()
        {
            //TODO: Update GetExtents
            SharpMap.Geometries.BoundingBox box = null;
            using (SQLiteConnection conn = new SQLiteConnection(_ConnectionString))
            {

                //string strSQL = "SELECT Min(minx) AS MinX, Min(miny) AS MinY, Max(maxx) AS MaxX, Max(maxy) AS MaxY FROM " + this.Table;
                string strSQL = string.Format("SELECT max(MbrMaxY({0})) as maxy, max(MbrMaxX({0})) as maxx, min(MbrMinY({0})) as miny, min(MbrMinX({0})) as minx from {1};", _GeometryColumn, _Table);
                if (!String.IsNullOrEmpty(_defintionQuery))
                    strSQL += " WHERE " + this.DefinitionQuery;
                using (SQLiteCommand command = new SQLiteCommand(strSQL, conn))
                {
                    conn.Open();
                    Object retVal = new SQLiteCommand("SELECT load_extension('libspatialite-2.dll');", conn).ExecuteScalar();
                    using (SQLiteDataReader dr = command.ExecuteReader())
                        if (dr.Read())
                        {
                            box = new SharpMap.Geometries.BoundingBox((double)dr["minx"], (double)dr["miny"], (double)dr["maxx"], (double)dr["maxy"]);
                        }
                    conn.Close();
                }
                return box;
            }
        }
Пример #35
0
 private void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             Close();
             _Envelope = null;
             tree = null;
         }
         disposed = true;
     }
 }
Пример #36
0
 public void Pan(SharpMap.Geometries.Point p0, SharpMap.Geometries.Point p1)
 {
   _BaseMap.Center += (p0 - p1);
   _RealTimeMap.Center = _BaseMap.Center;
   _MapArea = _BaseMap.Envelope;
   BaseMapRedrawn = false;
   OverviewMapRedrawn = false;
   RealTimeMapRedrawn = false;
   RefreshViews();
 }
Пример #37
0
        private static Map InitializeMapOsm(float angle)
        {
            //Transparent style
            VectorStyle transparentStyle = new VectorStyle();
            transparentStyle.Fill = Brushes.Transparent;
            transparentStyle.EnableOutline = true; //otherwise all the fancy theming stuff won't work!
            transparentStyle.Line.Brush = Brushes.Transparent;
            transparentStyle.Outline.Brush = Brushes.Transparent;
            transparentStyle.Symbol = null;

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

            //Initialize a new map
            Map map = new Map();
            map.BackColor = Color.Cornsilk;

            //Set up the countries layer
            VectorLayer layNatural = new VectorLayer("Natural");
            //Set the datasource to a shapefile in the App_data folder
            layNatural.DataSource = new ShapeFile(string.Format("{0}/natural.shp", PathOsm), true);
            //Set default style to draw nothing
            layNatural.Style = transparentStyle;
            //Set theme
            ThemeViaDelegate theme = new ThemeViaDelegate(layNatural.Style, "type");
            theme.GetStyleFunction = delegate(FeatureDataRow row)
                                         {
                                             string caseVal = (String) row["type"];
                                             caseVal = caseVal.ToLowerInvariant();
                                             VectorStyle returnStyle = new VectorStyle();
                                             
                                             switch (caseVal)
                                             {
                                                 case "forest":
                                                     returnStyle.Fill = Brushes.ForestGreen;
                                                     returnStyle.EnableOutline = true;
                                                     returnStyle.Outline.Brush = Brushes.DarkGreen;
                                                     break;
                                                 case "water":
                                                     returnStyle.Fill = Brushes.Aqua;
                                                     returnStyle.EnableOutline = true;
                                                     returnStyle.Outline.Brush = Brushes.DarkBlue;
                                                     break;
                                                 case "riverbank":
                                                     returnStyle.Fill = Brushes.Peru;
                                                     returnStyle.EnableOutline = true;
                                                     returnStyle.Outline.Brush = Brushes.OrangeRed;
                                                     break;
                                                 case "park":
                                                     returnStyle.Fill = Brushes.PaleGreen;
                                                     returnStyle.EnableOutline = true;
                                                     returnStyle.Outline.Brush = Brushes.DarkGreen;
                                                     break;
                                                 default:
                                                     returnStyle = null;
                                                     break;
                                             }
                                             return returnStyle;
                                         };
            layNatural.Theme = theme;
            layNatural.SRID = 31466;

            VectorLayer layRoads = new VectorLayer("Roads");
            layRoads.DataSource = new ShapeFile(string.Format("{0}/roads.shp", PathOsm));
            layRoads.DataSource.Open();
            _roadsExtents = layRoads.DataSource.GetExtents();
            //layRoads.DataSource.Close();
            layRoads.Style = transparentStyle;
            ThemeViaDelegate themeRoads = new ThemeViaDelegate(transparentStyle, "type");
            themeRoads.GetStyleFunction = delegate(FeatureDataRow row)
                                              {
                                                  VectorStyle returnStyle = new VectorStyle();

                                                  switch ((String)row["type"])
                                                  {
                                                      case "rail":
                                                          returnStyle.Fill = Brushes.White;
                                                          returnStyle.Line.DashPattern = new float[] { 4f, 4f };//;System.Drawing.Drawing2D.DashStyle.Dash;
                                                          returnStyle.Line.Width = 4;
                                                          returnStyle.EnableOutline = true;
                                                          returnStyle.Outline.Brush = Brushes.Black;
                                                          returnStyle.Outline.Width = 6;
                                                          break;
                                                      case "canal":
                                                          returnStyle.Fill = Brushes.Aqua;
                                                          returnStyle.Outline.Brush = Brushes.DarkBlue;
                                                          returnStyle.Outline.Width = 5;
                                                          break;
                                                      case "cycleway":
                                                      case "footway":
                                                      case "pedestrian":
                                                          returnStyle.Line.Brush = Brushes.DarkGray;
                                                          returnStyle.Line.DashStyle =
                                                              DashStyle.Dot;
                                                          returnStyle.Line.Width = 1;
                                                          returnStyle.MaxVisible = _roadsExtents.Width * 0.05d;
                                                          break;
                                                      case "living_street":
                                                      case "residential":
                                                          returnStyle.Line.Brush = Brushes.LightGoldenrodYellow;
                                                          returnStyle.Line.Width = 2;
                                                          returnStyle.EnableOutline = true;
                                                          returnStyle.Outline.Brush = Brushes.DarkGray;
                                                          returnStyle.Outline.Width = 4;
                                                          returnStyle.MaxVisible = _roadsExtents.Width * 0.15d;
                                                          break;
                                                      case "primary":
                                                          returnStyle.Line.Brush = Brushes.LightGoldenrodYellow;
                                                          returnStyle.Line.Width = 7;
                                                          returnStyle.EnableOutline = true;
                                                          returnStyle.Outline.Brush = Brushes.Black;
                                                          returnStyle.Outline.Width = 11;
                                                          break;
                                                      case "secondary":
                                                          returnStyle.Line.Brush = Brushes.LightGoldenrodYellow;
                                                          returnStyle.Line.Width = 6;
                                                          returnStyle.EnableOutline = true;
                                                          returnStyle.Outline.Brush = Brushes.Black;
                                                          returnStyle.MaxVisible = _roadsExtents.Width * 0.3d;
                                                          returnStyle.Outline.Width = 10;
                                                          break;
                                                      case "tertiary":
                                                          returnStyle.Line.Brush = Brushes.LightGoldenrodYellow;
                                                          returnStyle.Line.Width = 5;
                                                          returnStyle.EnableOutline = true;
                                                          returnStyle.Outline.Brush = Brushes.Black;
                                                          returnStyle.MaxVisible = _roadsExtents.Width * 0.6d;
                                                          returnStyle.Outline.Width = 9;
                                                          break;
                                                      case "path":
                                                      case "track":
                                                      case "unclassified":
                                                          returnStyle.Line.Brush = Brushes.DarkGray;
                                                          returnStyle.Line.DashStyle =
                                                              DashStyle.DashDotDot;
                                                          returnStyle.Line.Width = 1;
                                                          returnStyle.MaxVisible = _roadsExtents.Width * 0.025d;
                                                          break;
                                                      default:
                                                          returnStyle = null;
                                                          break;
                                                  }
                                                  return returnStyle;
                                              };
            layRoads.Theme = themeRoads;
            layRoads.SRID = 31466;

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

            VectorLayer layWaterways = new VectorLayer("Waterways");
            layWaterways.Style = transparentStyle;
            layWaterways.DataSource = new ShapeFile(string.Format("{0}/waterways.shp", PathOsm));
            layRoads.Style = transparentStyle;
            ThemeViaDelegate themeWater = new ThemeViaDelegate(transparentStyle, "type");
            themeWater.GetStyleFunction = delegate(FeatureDataRow row)
            {
                VectorStyle returnStyle = new VectorStyle();
                returnStyle.Line.Brush = Brushes.Aqua;
                returnStyle.EnableOutline = true;
                Int32 lineWidth = 1;
                switch ((String)row["type"])
                {
                    case "canal":
                    case "derelict_canal":
                        lineWidth = 2;
                        break;
                    case "drain":
                        returnStyle.EnableOutline = false;
                        break;
                    case "stream":
                        lineWidth = 2;
                        break;
                    default:
                        //returnStyle = null;
                        break;
                }
                returnStyle.Line.Width = lineWidth;
                returnStyle.Outline.Brush = Brushes.DarkBlue;
                returnStyle.Outline.Width = lineWidth + 1;
                return returnStyle;
            };
            layWaterways.Theme = themeWater;
            layWaterways.SRID = 31466;

            VectorLayer layPoints = new VectorLayer("Points");
            layPoints.DataSource = new ShapeFile(string.Format("{0}/points.shp", PathOsm));
            layPoints.Style = transparentStyle2;
            ThemeViaDelegate themePoints = new ThemeViaDelegate(transparentStyle2, "type");
            themePoints.GetStyleFunction = delegate(FeatureDataRow row)
            {
                VectorStyle returnStyle = new VectorStyle();
                switch ((String)row["type"])
                {
                    case "bank":
                        returnStyle.Symbol = new Bitmap("Images/Bank.gif");
                        break;
                    case "hospital":
                        returnStyle.Symbol = new Bitmap("Images/medical-facility.gif");
                        break;
                    case "hotel":
                        returnStyle.Symbol = new Bitmap("Images/hotel.gif");
                        break;
                    case "restaurant":
                    case "fast-food":
                        returnStyle.Symbol = new Bitmap("Images/restaurant.gif");
                        break;
                    case "parking":
                        returnStyle.Symbol = new Bitmap("Images/car.gif");
                        break;
                    default:
                        Bitmap tmp = new Bitmap(1,1);
                        tmp.SetPixel(0,0, Color.Transparent);
                        returnStyle.Symbol = tmp;
                        break;
                }
                return returnStyle;
            };
            layPoints.Theme = themePoints;
            layWaterways.SRID = 31466;

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

            ShapeProvider sp = new ShapeProvider(string.Format("{0}/obepath.shp", PathOsm));
            VectorLayer vl = new VectorLayer("obepath", sp);
            vl.SRID = 31466;
            vl.Style.Symbol = new Bitmap("Images/car.gif");

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

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

            map.Disclaimer = "Geodata from OpenStreetMap (CC-by-SA)\nTransformed to Shapefile by geofabrik.de";
            map.DisclaimerFont = new Font("Arial", 7f, FontStyle.Italic);
            map.DisclaimerLocation = 1;
            transparentStyle2.MaxVisible = map.MaximumZoom*0.3;

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

            return map;
        }
Пример #38
0
    protected void ZoomFactor(double factor)
    {
      _BaseMap.Zoom *= factor;

      _RealTimeMap.ZoomToBox(_BaseMap.Envelope);
      _MapArea = _BaseMap.Envelope;

      BaseMapRedrawn = false;
      OverviewMapRedrawn = false;
      RealTimeMapRedrawn = false;
      RefreshViews();
    }
Пример #39
0
        void HandleMapNewTileAvaliable(TileLayer sender, BoundingBox box, Bitmap bm, int sourceWidth, int sourceHeight, ImageAttributes imageAttributes)
        {
            lock (_imageBackground)
            {
                try
                {
                    PointF min = _map.WorldToImage(new GeoPoint(box.Min.X, box.Min.Y));
                    PointF max = _map.WorldToImage(new GeoPoint(box.Max.X, box.Max.Y));

                    min = new PointF((float)Math.Round(min.X), (float)Math.Round(min.Y));
                    max = new PointF((float)Math.Round(max.X), (float)Math.Round(max.Y));

                    if (IsDisposed == false)
                    {
                        Graphics g = Graphics.FromImage(_imageBackground);

                        g.DrawImage(bm,
                            new Rectangle((int)min.X, (int)max.Y, (int)(max.X - min.X), (int)(min.Y - max.Y)),
                            0, 0,
                            sourceWidth, sourceHeight,
                            GraphicsUnit.Pixel,
                            imageAttributes);

                        g.Dispose();
                        UpdateImage(false);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    //this can be a GDI+ Hell Exception...
                }
            }


        }
Пример #40
0
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (_map != null)
            {
                if (MouseUp != null)
                    MouseUp(_map.ImageToWorld(new Point(e.X, e.Y)), e);

                if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
                {
                    if (_activeTool == Tools.ZoomOut)
                    {
                        double scale = 0.5;
                        if (_dragging)
                        {
                            if (e.Y - _dragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(_dragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - _dragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }

                        _map.Zoom /= scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(_map.Zoom);
                    }
                    else if (_activeTool == Tools.ZoomIn)
                    {
                        double scale = 2;
                        if (_dragging)
                        {
                            if (e.Y - _dragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(_dragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - _dragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }

                        _map.Zoom *= 1 / scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(_map.Zoom);

                    }
                    else if ((_activeTool == Tools.Pan && !(_shiftButtonDragRectangleZoom && (Control.ModifierKeys & Keys.Shift) != Keys.None)) ||
                        (e.Button == System.Windows.Forms.MouseButtons.Left && _dragging && (_activeTool == Tools.DrawLine || _activeTool == Tools.DrawPolygon)))
                    {
                        if (_dragging)
                        {
                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }
                        else
                        {
                            if (_panOnClick)
                            {
                                _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                                if (MapCenterChanged != null)
                                    MapCenterChanged(_map.Center);
                            }
                        }
                    }
                    else if (_activeTool == Tools.Query || _activeTool == Tools.QueryGeometry)
                    {
                        if (_map.Layers.Count > _queryLayerIndex && _queryLayerIndex > -1)
                        {
                            var layer = _map.Layers[_queryLayerIndex] as ICanQueryLayer;
                            if (layer != null)
                            {
                                BoundingBox bounding;
                                bool isPoint = false;
                                if (_dragging)
                                {
                                    GeoPoint lowerLeft;
                                    GeoPoint upperRight;
                                    GetBounds(_map.ImageToWorld(_dragStartPoint), _map.ImageToWorld(_dragEndPoint), out lowerLeft, out upperRight);

                                    bounding = new BoundingBox(lowerLeft, upperRight);
                                }
                                else
                                {
                                    bounding =
                                        _map.ImageToWorld(new Point(e.X, e.Y)).GetBoundingBox().Grow(_map.PixelSize*
                                                                                                     _queryGrowFactor);
                                    isPoint = true;
                                }

                                Data.FeatureDataSet ds = new Data.FeatureDataSet();
                                if (_activeTool == Tools.Query)
                                    layer.ExecuteIntersectionQuery(bounding, ds);
                                else
                                {
                                    Geometry geom;
                                    if (isPoint && QueryGrowFactor == 0)
                                        geom = _map.ImageToWorld(new Point(e.X, e.Y));
                                    else    
                                        geom = bounding.ToGeometry();
                                    layer.ExecuteIntersectionQuery(geom, ds);
                                }

                                if (ds.Tables.Count > 0)
                                    if (MapQueried != null) MapQueried(ds.Tables[0]);
                                    else if (MapQueried != null) MapQueried(new Data.FeatureDataTable());
                            }

                        }
                        else
                            MessageBox.Show("No active layer to query");
                    }
                    else if (_activeTool == Tools.ZoomWindow || (_shiftButtonDragRectangleZoom && (Control.ModifierKeys & Keys.Shift) != Keys.None))
                    {
                        if (_rectangle.Width > 0 && _rectangle.Height > 0)
                        {
                            GeoPoint lowerLeft;
                            GeoPoint upperRight;
                            GetBounds(_map.ImageToWorld(_dragStartPoint), _map.ImageToWorld(_dragEndPoint), out lowerLeft, out upperRight);
                            _dragEndPoint.X = 0;
                            _dragEndPoint.Y = 0;

                            _map.ZoomToBox(new BoundingBox(lowerLeft, upperRight));
                            
                            if (MapZoomChanged != null)
                                MapZoomChanged(_map.Zoom);

                        }
                    }
                    else if (_activeTool == Tools.DrawPoint)
                    {
                        if (GeometryDefined != null)
                        {
                            GeometryDefined(Map.ImageToWorld(new PointF(e.X, e.Y)));
                        }
                    }
                    else if (_activeTool == Tools.DrawPolygon || _activeTool == Tools.DrawLine)
                    {
                        //pointArray = null;
                        if (_pointArray == null)
                        {
                            _pointArray = new SharpMap.Geometries.Point[2];
                            _pointArray[0] = Map.ImageToWorld(e.Location);
                            _pointArray[1] = Map.ImageToWorld(e.Location);
                        }
                        else
                        {
                            SharpMap.Geometries.Point[] temp = new SharpMap.Geometries.Point[_pointArray.GetUpperBound(0) + 2];
                            for (int i = 0; i <= _pointArray.GetUpperBound(0); i++)
                                temp[i] = _pointArray[i];

                            temp[temp.GetUpperBound(0)] = Map.ImageToWorld(e.Location);
                            _pointArray = temp;
                        }
                    }
                }


                if (_dragging)
                {
                    _dragging = false;
                    if (_activeTool == Tools.Query)
                        Invalidate(_rectangle);
                    if (_activeTool == Tools.ZoomWindow || _activeTool == Tools.Query)
                        _rectangle = Rectangle.Empty;

                    Refresh();
                }
                else if (_activeTool == Tools.ZoomIn || _activeTool == Tools.ZoomOut || _activeTool == Tools.Pan)
                {
                    Refresh();
                }
            }
        }
Пример #41
0
        private void GetImagesAsync(BoundingBox extent, int imageGeneration)
        {
            Map safeMap = null;
            lock (maplocker)
            {
                if (isDisposed)
                    return;

                if (imageGeneration < _imageGeneration)
                {
                    /*we're to old*/
                    return;
                }
                safeMap = _map.Clone();
                _imageVariable = GetMap(safeMap, _map.VariableLayers, LayerCollectionType.Variable, extent);
                lock (lockerStaticImages)
                {
                    _imageStatic = GetMap(safeMap, _map.Layers, LayerCollectionType.Static, extent);
                }
                lock (lockerBackgroundImages)
                {
                    _imageBackground = GetMap(safeMap, _map.BackgroundLayer, LayerCollectionType.Background, extent);
                }
            }
        }
Пример #42
0
        public SharpMap.Geometries.BoundingBox GetExtents()
        {
            SharpMap.Geometries.BoundingBox bbox = null;
            if (_data == null || _data.Rows.Count == 0 || string.IsNullOrEmpty(_data.GeometryColumn))
                return new SharpMap.Geometries.BoundingBox(0.0, 0.0, 0.0, 0.0);

            foreach (FdoFeature feat in _data.Rows)
            {
                if (feat[_data.GeometryColumn] != null && feat[_data.GeometryColumn] != DBNull.Value)
                {
                    try
                    {
                        OSGeo.FDO.Geometry.IGeometry geom = (OSGeo.FDO.Geometry.IGeometry)feat[_data.GeometryColumn];
                        if (bbox != null)
                        {
                            if (geom.Envelope.MaxX > bbox.Max.X)
                                bbox.Max.X = geom.Envelope.MaxX;
                            if (geom.Envelope.MaxY > bbox.Max.Y)
                                bbox.Max.Y = geom.Envelope.MaxY;
                            if (geom.Envelope.MinX < bbox.Min.X)
                                bbox.Min.X = geom.Envelope.MinX;
                            if (geom.Envelope.MinY < bbox.Min.Y)
                                bbox.Min.Y = geom.Envelope.MinY;
                        }
                        else
                        {
                            bbox = new SharpMap.Geometries.BoundingBox(geom.Envelope.MinX, geom.Envelope.MinY, geom.Envelope.MaxX, geom.Envelope.MaxY);
                        }
                    }
                    catch { }
                }
            }
            if (bbox != null)
                return bbox;
            else
                return new SharpMap.Geometries.BoundingBox(0.0, 0.0, 0.0, 0.0);
        }
Пример #43
0
        /// <summary>
        /// Boundingbox of dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public SharpMap.Geometries.BoundingBox GetExtents()
        {
            using (PgConnection conn = new PgConnection(_ConnectionString))
            {
                string strSQL = String.Format("SELECT EXTENT({0}) FROM {1}",
                                              this.GeometryColumn,
                                              this.Table);

                if (!String.IsNullOrEmpty(_defintionQuery))
                    strSQL += " WHERE " + this.DefinitionQuery;


                strSQL += ";";

                using (PgCommand command = new PgCommand(strSQL, conn))
                {
                    conn.Open();

                    SharpMap.Geometries.BoundingBox bbox = null;
                    try
                    {
                        PostgreSql.Data.PgTypes.PgBox2D result = (PostgreSql.Data.PgTypes.PgBox2D)command.ExecuteScalar();
                        bbox = new SharpMap.Geometries.BoundingBox(result.LowerLeft.X, result.LowerLeft.Y, result.UpperRight.X, result.UpperRight.Y);
                    }
                    catch (System.Exception ex)
                    {
                        throw new Exception("Box2d couldn't fetched from table. " + ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                    return bbox;
                }
            }
        }
Пример #44
0
		/// <summary>
		/// Boundingbox of the dataset
		/// </summary>
		/// <returns>boundingbox</returns>
		public SharpMap.Geometries.BoundingBox GetExtents()
		{
			if(this._bbox==null)
			{
				OGR.Envelope _OgrEnvelope = new Envelope();
                int i = _OgrLayer.GetExtent(_OgrEnvelope, 1);
			
                this._bbox = new SharpMap.Geometries.BoundingBox(_OgrEnvelope.MinX,
                                                                 _OgrEnvelope.MinY,
                                                                 _OgrEnvelope.MaxX,
                                                                 _OgrEnvelope.MaxY);
            
			}
			
			return _bbox;
		}
Пример #45
0
    public void ZoomToElement(SharpMap.Geometries.Geometry Element)
    {
      if (Element == null)
        return;

      SharpMap.Geometries.Point point = Element.GetBoundingBox().GetCentroid().AsPoint();
      if ((point.X == 0.0) && (point.Y == 0.0))
        return;
      _BaseMap.Center = Element.GetBoundingBox().GetCentroid();
      _RealTimeMap.ZoomToBox(_BaseMap.Envelope);
      _MapArea = _BaseMap.Envelope;
      BaseMapRedrawn = false;
      OverviewMapRedrawn = false;
      RealTimeMapRedrawn = false;
      RefreshViews();
    }
Пример #46
0
        private void GetImagesAsyncEnd(GetImageEndResult res)
        {
            //draw only if generation is larger than the current, else we have aldready drawn something newer
            if (res == null || res.generation < _imageGeneration)
                return;

#if DEBUG
            Debug.WriteLine(string.Format("{2}: {0} - {1}", res.generation, res.bbox, DateTime.Now));
#endif

            if ((_setActiveToolNoneDuringRedraw || ShowProgressUpdate) && InvokeRequired)
            {
                try
                {
                    BeginInvoke(new MethodInvoker(delegate
                    {
                        GetImagesAsyncEnd(res);
                    }));

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {
                try
                {
                    var oldRef = _image;
                    if (Width > 0 && Height > 0)
                    {

                        var bmp = new Bitmap(Width, Height);

                        lock (_map)
                        {
                            using (var g = Graphics.FromImage(bmp))
                            {
                                //Draws the background Image
                                if (_imageBackground != null)
                                {
                                    try
                                    {
                                        g.DrawImageUnscaled(_imageBackground, 0, 0);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.ToString());
                                    }
                                }

                                //Draws the static images
                                if (_imageStatic != null)
                                {
                                    try
                                    {
                                        g.DrawImageUnscaled(_imageStatic, 0, 0);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.ToString());
                                    }

                                }

                                //Draws the variable Images
                                if (_imageVariable != null)
                                {
                                    try
                                    {
                                        g.DrawImageUnscaled(_imageVariable, 0, 0);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.ToString());
                                    }
                                }

                                g.Dispose();
                            }



                            _image = bmp;
                            _imageBoundingBox = res.bbox;
                        }
                    }

                    if (res.Tool.HasValue)
                    {
                        if (_setActiveToolNoneDuringRedraw)
                            ActiveTool = res.Tool.Value;

                        _dragEndPoint = new Point(0, 0);
                        _isRefreshing = false;

                        if (_setActiveToolNoneDuringRedraw)
                            Enabled = true;

                        if (ShowProgressUpdate)
                        {
                            _progressBar.Enabled = false;
                            _progressBar.Visible = false;
                        }
                    }

                    if (oldRef != null)
                        oldRef.Dispose();

                    Invalidate();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

#if DEBUG
                _watch.Stop();
                LastRefreshTime = _watch.Elapsed;
#endif

                try
                {
                    if (MapRefreshed != null)
                    {
                        MapRefreshed(this, null);
                    }
                }
                catch (Exception ee)
                {
                    //Trap errors that occured when calling the eventhandlers
                    Console.WriteLine(ee.ToString());
                }
            }
        }
Пример #47
0
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (_map != null)
            {
                if (MouseUp != null)
                    MouseUp(_map.ImageToWorld(new Point(e.X, e.Y)), e);

                if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
                {
                    if (_activeTool == Tools.ZoomOut)
                    {
                        double scale = 0.5;
                        if (_dragging)
                        {
                            if (e.Y - _dragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(_dragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - _dragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }

                        _map.Zoom /= scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(_map.Zoom);
                    }
                    else if (_activeTool == Tools.ZoomIn)
                    {
                        double scale = 2;
                        if (_dragging)
                        {
                            if (e.Y - _dragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(_dragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - _dragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }

                        _map.Zoom *= 1 / scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(_map.Zoom);

                    }
                    else if (_activeTool == Tools.Pan && !(_shiftButtonDragRectangleZoom && (Control.ModifierKeys & Keys.Shift) != Keys.None))
                    {
                        if (_dragging)
                        {
                            Point point = new Point(ClientSize.Width / 2 + (_dragStartPoint.X - e.Location.X), ClientSize.Height / 2 + (_dragStartPoint.Y - e.Location.Y));
                            _map.Center = _map.ImageToWorld(point);

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }
                        else
                        {
                            _map.Center = _map.ImageToWorld(new Point(e.X, e.Y));

                            if (MapCenterChanged != null)
                                MapCenterChanged(_map.Center);
                        }
                    }
                    else if (_activeTool == Tools.Query)
                    {
                        if (_map.Layers.Count > _queryLayerIndex && _queryLayerIndex > -1)
                        {
                            /*
                            if (m_Map.Layers[m_QueryLayerIndex].GetType() == typeof(Layers.VectorLayer))
                            {
                                
                                Layers.VectorLayer layer = m_Map.Layers[m_QueryLayerIndex] as Layers.VectorLayer;
                                Geometries.BoundingBox bounding;
                                
                                if (m_Dragging)
                                {
                                    GeoPoint lowerLeft;
                                    GeoPoint upperRight;
                                    GetBounds(m_Map.ImageToWorld(m_DragStartPoint), m_Map.ImageToWorld(m_DragEndPoint), out lowerLeft, out upperRight);

                                    bounding = new Geometries.BoundingBox(lowerLeft, upperRight);
                                }
                                else
                                    bounding = m_Map.ImageToWorld(new Point(e.X, e.Y)).GetBoundingBox().Grow(m_Map.PixelSize * 5);
                                
                                Data.FeatureDataSet ds = new Data.FeatureDataSet();
                                layer.DataSource.Open();
                                layer.DataSource.ExecuteIntersectionQuery(bounding, ds);
                                layer.DataSource.Close();

                                if (MapQueried != null)
                                    MapQueried((ds.Tables.Count > 0 ? ds.Tables[0] : new Data.FeatureDataTable()));
                            }
                             */
                            var layer = _map.Layers[_queryLayerIndex] as ICanQueryLayer;
                            if (layer != null)
                            {
                                BoundingBox bounding;

                                if (_dragging)
                                {
                                    GeoPoint lowerLeft;
                                    GeoPoint upperRight;
                                    GetBounds(_map.ImageToWorld(_dragStartPoint), _map.ImageToWorld(_dragEndPoint), out lowerLeft, out upperRight);

                                    bounding = new BoundingBox(lowerLeft, upperRight);
                                }
                                else
                                    bounding = _map.ImageToWorld(new Point(e.X, e.Y)).GetBoundingBox().Grow(_map.PixelSize * 5);

                                Data.FeatureDataSet ds = new Data.FeatureDataSet();
                                layer.ExecuteIntersectionQuery(bounding, ds);
                                if (ds.Tables.Count > 0)
                                    if (MapQueried != null) MapQueried(ds.Tables[0]);
                                    else if (MapQueried != null) MapQueried(new Data.FeatureDataTable());
                            }

                        }
                        else
                            MessageBox.Show("No active layer to query");
                    }
                    else if (_activeTool == Tools.ZoomWindow || (_shiftButtonDragRectangleZoom && (Control.ModifierKeys & Keys.Shift) != Keys.None))
                    {
                        if (_rectangle.Width > 0 && _rectangle.Height > 0)
                        {
                            GeoPoint lowerLeft;
                            GeoPoint upperRight;
                            GetBounds(_map.ImageToWorld(_dragStartPoint), _map.ImageToWorld(_dragEndPoint), out lowerLeft, out upperRight);
                            _dragEndPoint.X = 0;
                            _dragEndPoint.Y = 0;

                            _map.ZoomToBox(new BoundingBox(lowerLeft, upperRight));
                            
                            if (MapZoomChanged != null)
                                MapZoomChanged(_map.Zoom);

                        }
                    }
                    else if (_activeTool == Tools.DrawPoint)
                    {
                        if (GeometryDefined != null)
                        {
                            GeometryDefined(Map.ImageToWorld(new PointF(e.X, e.Y)));
                        }
                    }
                    else if (_activeTool == Tools.DrawPolygon || _activeTool == Tools.DrawLine)
                    {
                        //pointArray = null;
                        if (_pointArray == null)
                        {
                            _pointArray = new Point[2];
                            _pointArray[0] = e.Location;
                            _pointArray[1] = e.Location;
                        }
                        else
                        {
                            Point[] temp = new Point[_pointArray.GetUpperBound(0) + 2];
                            for (int i = 0; i <= _pointArray.GetUpperBound(0); i++)
                                temp[i] = _pointArray[i];

                            temp[temp.GetUpperBound(0)] = e.Location;
                            _pointArray = temp;
                        }
                    }
                }


                if (_dragging)
                {

                    _dragging = false;

                    if (_activeTool == Tools.Query)
                        Invalidate(_rectangle);

                    if (_activeTool == Tools.ZoomWindow || _activeTool == Tools.Query)
                        _rectangle = Rectangle.Empty;

                    Refresh();

                    if (_activeTool != Tools.ZoomOut)
                    {
                        if (_image != null)
                        {
                            _image.Dispose();
                            _image = null;
                        }
                        _image = _dragImage;
                        Invalidate();
                    }


                }
                else if (_activeTool == Tools.ZoomIn || _activeTool == Tools.ZoomOut || _activeTool == Tools.Pan)
                {
                    Refresh();
                }


            }
        }
Пример #48
0
    public void ZoomToElement(string layerName, uint IDElement)
    {
      // private System.Collections.Generic.Dictionary<string, SharpMap.Layers.ILayer> Layers_;
      // private System.Collections.Generic.List<string> RealTimeLayers_;
      SharpMap.Geometries.Geometry geo = (Layers_[layerName] as SharpMap.Layers.VectorLayer).DataSource.GetGeometryByID(IDElement);

      if (geo == null)
        return;

      SharpMap.Geometries.Point pt = geo.GetBoundingBox().GetCentroid().AsPoint();
      if ((pt.X == 0) && (pt.Y == 0))
        return;
      _BaseMap.Center = geo.GetBoundingBox().GetCentroid();
      
      _RealTimeMap.ZoomToBox(_BaseMap.Envelope);
      _MapArea = _BaseMap.Envelope;

      BaseMapRedrawn = false;
      OverviewMapRedrawn = false;
      RealTimeMapRedrawn = false;
      RefreshViews();
    }
Пример #49
0
        public override FeatureList process(FeatureList input, FilterEnv env)
        {
            FeatureList output = new FeatureList();

            //Boolean encontrado = false;
            SharpMap.Geometries.BoundingBox boundingBox = new SharpMap.Geometries.BoundingBox(longitudeMin,latitudeMin,longitudeMax,latitudeMax);

            foreach (Feature feature in input)
            {
                //if type of features is Point
                if (feature.row.Geometry is SharpMap.Geometries.Point)
                {
                    SharpMap.Geometries.Point p = (SharpMap.Geometries.Point)feature.row.Geometry;
                    if (boundingBox.Contains(p.GetBoundingBox()))
                    {
                        output.Add(feature);
                    }
                }
                //if type of features is Polygon
                else if (feature.row.Geometry is SharpMap.Geometries.Polygon)
                {
                    SharpMap.Geometries.Polygon polygon = (SharpMap.Geometries.Polygon)feature.row.Geometry;
                    if (boundingBox.Contains(polygon.GetBoundingBox()))
                    {
                        output.Add(feature);
                    }
                }
                //if type of features is MultiPolygon
                else if (feature.row.Geometry is SharpMap.Geometries.MultiPolygon)
                {
                    SharpMap.Geometries.MultiPolygon mp = (SharpMap.Geometries.MultiPolygon)feature.row.Geometry;
                    SharpMap.Geometries.BoundingBox bb = mp.GetBoundingBox();
                    if (boundingBox.Contains(bb))
                    {
                        output.Add(feature);
                    }
                }

            }

            if (successor != null)
            {
                if (successor is FeatureFilter)
                {
                    FeatureFilter filter = (FeatureFilter)successor;
                    FeatureList l = filter.process(output, env);
                }
                else if (successor is FragmentFilter)
                {
                    FragmentFilter filter = (FragmentFilter)successor;
                    FragmentList l = filter.process(output, env);
                }
            }

            return output;
        }
Пример #50
0
 public void ZoomToBox(SharpMap.Geometries.BoundingBox bbox)
 {
   _BaseMap.ZoomToBox(bbox);
   _RealTimeMap.ZoomToBox(bbox);
   _MapArea = bbox;
   BaseMapRedrawn = false;
   OverviewMapRedrawn = false;
   RealTimeMapRedrawn = false;
   RefreshViews();
 }
Пример #51
0
 private void GetImagesAsync(BoundingBox extent)
 {
     Map safeMap = null;
     lock (_map)
     {
         safeMap = _map.Clone();
         _imageVariable = GetMap(safeMap, _map.VariableLayers, LayerCollectionType.Variable, extent);
         _imageStatic = GetMap(safeMap, _map.Layers, LayerCollectionType.Static, extent);
         _imageBackground = GetMap(safeMap, _map.BackgroundLayer, LayerCollectionType.Background, extent);
     }
 }
Пример #52
0
        /// <summary>
        /// Creates a node and either splits the objects recursively into sub-nodes, or stores them at the node depending on the heuristics.
        /// Tree is built top->down
        /// </summary>
        /// <param name="objList">Geometries to index</param>
        /// <param name="depth">Current depth of tree</param>
        /// <param name="heurdata">Heuristics data</param>
        public QuadTree(List<BoxObjects> objList, uint depth, Heuristic heurdata)
        {
            _Depth = depth;

            _box = objList[0].box;
            for (int i = 0; i < objList.Count;i++ )
                _box = _box.Join(objList[i].box);

            // test our build heuristic - if passes, make children
            if (depth < heurdata.maxdepth && objList.Count > heurdata.mintricnt &&
                (objList.Count > heurdata.tartricnt || ErrorMetric(_box) > heurdata.minerror))
            {
                List<BoxObjects>[] objBuckets = new List<BoxObjects>[2]; // buckets of geometries
                objBuckets[0] = new List<BoxObjects>();
                objBuckets[1] = new List<BoxObjects>();

                uint longaxis = _box.LongestAxis; // longest axis
                double geoavg = 0; // geometric average - midpoint of ALL the objects

                // go through all bbox and calculate the average of the midpoints
                double frac = 1.0f / objList.Count;
                for (int i = 0; i < objList.Count;i++ )
                    geoavg += objList[i].box.GetCentroid()[longaxis] * frac;

                // bucket bbox based on their midpoint's side of the geo average in the longest axis
                for (int i = 0; i < objList.Count;i++ )
                    objBuckets[geoavg > objList[i].box.GetCentroid()[longaxis] ? 1 : 0].Add(objList[i]);

                //If objects couldn't be splitted, just store them at the leaf
                //TODO: Try splitting on another axis
                if (objBuckets[0].Count == 0 || objBuckets[1].Count == 0)
                {
                    _child0 = null;
                    _child1 = null;
                    // copy object list
                    _objList = objList;
                }
                else
                {
                    // create new children using the buckets
                    _child0 = new QuadTree(objBuckets[0], depth + 1, heurdata);
                    _child1 = new QuadTree(objBuckets[1], depth + 1, heurdata);
                }
            }
            else
            {
                // otherwise the build heuristic failed, this is
                // set the first child to null (identifies a leaf)
                _child0 = null;
                _child1 = null;
                // copy object list
                _objList = objList;
            }
        }
Пример #53
0
        /// <summary>
        /// Reads and parses the header of the .shx index file
        /// </summary>
        private void ParseHeader()
        {
            fsShapeIndex = new FileStream(_Filename.Remove(_Filename.Length - 4, 4) + ".shx", FileMode.Open, FileAccess.Read);
            brShapeIndex = new BinaryReader(fsShapeIndex, System.Text.Encoding.Unicode);

            brShapeIndex.BaseStream.Seek(0, 0);
            //Check file header
            if (brShapeIndex.ReadInt32() != 170328064) //File Code is actually 9994, but in Little Endian Byte Order this is '170328064'
                throw (new ApplicationException("Invalid Shapefile Index (.shx)"));

            brShapeIndex.BaseStream.Seek(24, 0); //seek to File Length
            int IndexFileSize = SwapByteOrder(brShapeIndex.ReadInt32()); //Read filelength as big-endian. The length is based on 16bit words
            _FeatureCount = (2 * IndexFileSize - 100) / 8; //Calculate FeatureCount. Each feature takes up 8 bytes. The header is 100 bytes

            brShapeIndex.BaseStream.Seek(32, 0); //seek to ShapeType
            _ShapeType = (ShapeType)brShapeIndex.ReadInt32();

            //Read the spatial bounding box of the contents
            brShapeIndex.BaseStream.Seek(36, 0); //seek to box
            _Envelope = new SharpMap.Geometries.BoundingBox(brShapeIndex.ReadDouble(), brShapeIndex.ReadDouble(), brShapeIndex.ReadDouble(), brShapeIndex.ReadDouble());

            brShapeIndex.Close();
            fsShapeIndex.Close();
        }
Пример #54
0
    private void ProcessCommand()
    {
      switch (_CommandAction)
      {
        case CommandActions.INFORMATION:
          {
            SharpMap.Geometries.Point p0 = Singleton<ComplexMap>.Instance.ImageToWorld(ptOriginal);
            SharpMap.Geometries.Point p1 = Singleton<ComplexMap>.Instance.ImageToWorld(ptLast);
            List<SharpMap.Geometries.BoundingBox> lst = new List<SharpMap.Geometries.BoundingBox>();
            lst.Add(p0.GetBoundingBox());
            lst.Add(p1.GetBoundingBox());
            SharpMap.Geometries.BoundingBox bbox = new SharpMap.Geometries.BoundingBox(lst);

            SharpMap.Data.FeatureDataSet fds = Singleton<ComplexMap>.Instance.SelectElements(bbox, "caminos");
            fds.Tables[0].TableName = "Caminos";
            SharpMap.Data.FeatureDataSet fds2 = Singleton<ComplexMap>.Instance.SelectElements(bbox, "Referencias");
            fds2.Tables[0].TableName = "Referencias";

            ((Form1)_parent).elementInfo.ClearData();
            ((Form1)_parent).elementInfo.SetData(fds.Tables[0]);
            ((Form1)_parent).elementInfo.SetData(fds2.Tables[0]);

          }
          break;
        case CommandActions.PAN:
          {
            SharpMap.Geometries.Point p0 = Singleton<ComplexMap>.Instance.ImageToWorld(ptOriginal);
            SharpMap.Geometries.Point p1 = Singleton<ComplexMap>.Instance.ImageToWorld(ptLast);
            Singleton<ComplexMap>.Instance.Pan(p0, p1);
          }
          break;
        /*case CommandActions.ZOOM_IN:
          {
            SharpMap.Geometries.Point p = Singleton<ComplexMap>.Instance.ImageToWorld(ptLast);
            Singleton<ComplexMap>.Instance.ZoomIn();
          }
          break;*/
        /*case CommandActions.ZOOM_OUT:
          {
            SharpMap.Geometries.Point p = Singleton<ComplexMap>.Instance.ImageToWorld(ptLast);
            Singleton<ComplexMap>.Instance.ZoomOut();
          }
          break;*/
        case CommandActions.ZOOM_WINDOW:
          {
            SharpMap.Geometries.Point p0 = Singleton<ComplexMap>.Instance.ImageToWorld(ptOriginal);
            SharpMap.Geometries.Point p1 = Singleton<ComplexMap>.Instance.ImageToWorld(ptLast);
            List<SharpMap.Geometries.BoundingBox> lst = new List<SharpMap.Geometries.BoundingBox>();
            lst.Add(p0.GetBoundingBox());
            lst.Add(p1.GetBoundingBox());
            SharpMap.Geometries.BoundingBox bbox = new SharpMap.Geometries.BoundingBox(lst);
            Singleton<ComplexMap>.Instance.ZoomToBox(bbox);
          }
          break;
        default:
          break;
      }
      //_CommandAction = CommandActions.NO_ACTION;
    }
Пример #55
0
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (m_Map != null)
            {
                if (MouseUp != null)
                    MouseUp(m_Map.ImageToWorld(new Point(e.X, e.Y)), e);

                if (e.Button == MouseButtons.Left)
                {
                    if (m_ActiveTool == Tools.ZoomOut)
                    {
                        double scale = 0.5;
                        if (m_Dragging)
                        {
                            if (e.Y - m_DragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(m_DragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - m_DragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            m_Map.Center = m_Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y));
                            
                            if (MapCenterChanged != null)
                                MapCenterChanged(m_Map.Center);
                        }

                        m_Map.Zoom /= scale;

                        if (MapZoomChanged != null)
                            MapZoomChanged(m_Map.Zoom);
                    }
                    else if (m_ActiveTool == Tools.ZoomIn)
                    {
                        double scale = 2;
                        if (m_Dragging)
                        {
                            if (e.Y - m_DragStartPoint.Y < 0) //Zoom out
                                scale = (float)Math.Pow(1 / (float)(m_DragStartPoint.Y - e.Y), 0.5);
                            else //Zoom in
                                scale = 1 + (e.Y - m_DragStartPoint.Y) * 0.1;
                        }
                        else
                        {
                            m_Map.Center = m_Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y));
                            
                            if (MapCenterChanged != null)
                                MapCenterChanged(m_Map.Center);
                        }

                        m_Map.Zoom *= 1 / scale;
                        
                        if (MapZoomChanged != null)
                            MapZoomChanged(m_Map.Zoom);
                    }
                    else if (m_ActiveTool == Tools.Pan)
                    {
                        if (m_Dragging)
                        {
                            System.Drawing.Point point = new System.Drawing.Point(ClientSize.Width / 2 + (m_DragStartPoint.X - e.Location.X), ClientSize.Height / 2 + (m_DragStartPoint.Y - e.Location.Y));
                            m_Map.Center = m_Map.ImageToWorld(point);
                            
                            if (MapCenterChanged != null)
                                MapCenterChanged(m_Map.Center);
                        }
                        else
                        {
                            m_Map.Center = m_Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y));
                            
                            if (MapCenterChanged != null)
                                MapCenterChanged(m_Map.Center);
                        }
                    }
                    else if (m_ActiveTool == Tools.Query)
                    {
                        if (m_Map.Layers.Count > m_QueryLayerIndex && m_QueryLayerIndex > -1)
                        {
                            if (m_Map.Layers[m_QueryLayerIndex].GetType() == typeof(SharpMap.Layers.VectorLayer))
                            {
                                
                                SharpMap.Layers.VectorLayer layer = m_Map.Layers[m_QueryLayerIndex] as SharpMap.Layers.VectorLayer;
                                SharpMap.Geometries.BoundingBox bounding;
                                
                                if (m_Dragging)
                                {
                                    SharpMap.Geometries.Point lowerLeft;
                                    SharpMap.Geometries.Point upperRight;
                                    GetBounds(m_Map.ImageToWorld(m_DragStartPoint), m_Map.ImageToWorld(m_DragEndPoint), out lowerLeft, out upperRight);

                                    bounding = new SharpMap.Geometries.BoundingBox(lowerLeft, upperRight);
                                }
                                else
                                    bounding = m_Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)).GetBoundingBox().Grow(m_Map.PixelSize * 5);
                                
                                SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet();
                                layer.DataSource.Open();
                                layer.DataSource.ExecuteIntersectionQuery(bounding, ds);
                                layer.DataSource.Close();

                                if (MapQueried != null)
                                    MapQueried((ds.Tables.Count > 0 ? ds.Tables[0] : new SharpMap.Data.FeatureDataTable()));
                            }
                        }
                        else
                            MessageBox.Show("No active layer to query");
                    }
                    else if (m_ActiveTool == Tools.ZoomWindow)
                    {
                        if (m_Rectangle.Width > 0 && m_Rectangle.Height > 0)
                        {
                            SharpMap.Geometries.Point lowerLeft;
                            SharpMap.Geometries.Point upperRight;
                            GetBounds(m_Map.ImageToWorld(m_DragStartPoint), m_Map.ImageToWorld(m_DragEndPoint), out lowerLeft, out upperRight);

                            m_Map.ZoomToBox(new SharpMap.Geometries.BoundingBox(lowerLeft, upperRight));
                        }
                    }
                }

                if (m_DragImage != null)
                {
                    m_DragImage.Dispose();
                    m_DragImage = null;
                }

                if (m_Dragging)
                {
                    m_Dragging = false;

                    if (m_ActiveTool == Tools.Query)
                        Invalidate(m_Rectangle);

                    if (m_ActiveTool == Tools.ZoomWindow || m_ActiveTool == Tools.Query)
                        m_Rectangle = Rectangle.Empty;

                    Refresh();
                }
                else if (m_ActiveTool == Tools.ZoomIn || m_ActiveTool == Tools.ZoomOut || m_ActiveTool== Tools.Pan)
                    Refresh();
            }
        }
Пример #56
-1
        private Image GetMap(Map map, LayerCollection layers, LayerCollectionType layerCollectionType, BoundingBox extent)
        {

            if ((layers == null || layers.Count == 0 || Width == 0 || Height == 0))
            {
                if (layerCollectionType == LayerCollectionType.Background)
                    return new Bitmap(1, 1);
                return null;
            }

            var retval = new Bitmap(Width, Height);

            using(var g = Graphics.FromImage(retval))
            {
                map.RenderMap(g, layerCollectionType, false);
            }

            if (layerCollectionType == LayerCollectionType.Variable)
                retval.MakeTransparent(_map.BackColor);

            return retval;
        }