/// <summary> /// Returns geometry Object IDs whose bounding box intersects 'bbox' /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection <uint> GetObjectIDsInView(GeoAPI.Geometries.IEnvelope bbox) { Collection <uint> objectlist = new Collection <uint>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT " + this.ObjectIdColumn + " "; strSQL += "FROM " + this.Table + " WHERE "; strSQL += GetBoxClause(bbox); if (!String.IsNullOrEmpty(_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); }
/// <summary> /// Boundingbox of dataset /// </summary> /// <returns>boundingbox</returns> public GeoAPI.Geometries.IEnvelope GetExtents() { GeoAPI.Geometries.IEnvelope 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 (!String.IsNullOrEmpty(_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 = SharpMap.Converters.Geometries.GeometryFactory.CreateEnvelope((double)dr[0], (double)dr[1], (double)dr[2], (double)dr[3]); } } } conn.Close(); } } return(box); }
/// <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(GeoAPI.Geometries.IEnvelope 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.Centre; }
/// <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 IList GetFeatures(GeoAPI.Geometries.IEnvelope bbox) { //List<GeoAPI.Geometries.IGeometry> features = new List<GeoAPI.Geometries.IGeometry>(); 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); } return(fdt); } } } return(null); }
/// <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(GeoAPI.Geometries.IEnvelope 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 (!String.IsNullOrEmpty(_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); } } } }
/// <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 IList GetFeatures(GeoAPI.Geometries.IEnvelope bbox) { //List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>(); using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString)) { string strSQL = "Select * FROM " + this.Table + " WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) //If a definition query has been specified, add this as a filter on the query { strSQL += _defintionQuery + " AND "; } //Limit to the points within the boundingbox strSQL += this.XColumn + " BETWEEN " + bbox.MinX.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + bbox.MaxX.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + this.YColumn + " BETWEEN " + bbox.MaxY.ToString(SharpMap.Map.numberFormat_EnUS) + " AND " + bbox.MinY.ToString(SharpMap.Map.numberFormat_EnUS); using (System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(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) { 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) { fdr[col.ColumnName] = dr[col]; } if (dr[this.XColumn] != DBNull.Value && dr[this.YColumn] != DBNull.Value) { fdr.Geometry = SharpMap.Converters.Geometries.GeometryFactory.CreatePoint((double)dr[this.XColumn], (double)dr[this.YColumn]); } fdt.AddRow(fdr); } return(fdt); } } } return(null); }
/// <summary> /// Boundingbox of dataset /// </summary> /// <returns>boundingbox</returns> public GeoAPI.Geometries.IEnvelope GetExtents() { using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = string.Format("SELECT ST.AsBinary(ST.EnvelopeQueryWhere('{0}', '{1}', '{2}'))", this.Table, this.GeometryColumn, this.DefinitionQuery.Replace("'", "''")); using (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); object result = command.ExecuteScalar(); conn.Close(); if (result == System.DBNull.Value) { return(null); } GeoAPI.Geometries.IEnvelope bbox = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])result).EnvelopeInternal; return(bbox); } } }
/// <summary> /// Gets the extents of the map based on the extents of all the layers in the layers collection /// </summary> /// <returns>Full map extents</returns> public GeoAPI.Geometries.IEnvelope GetExtents() { if (this.Layers == null || this.Layers.Count == 0) { throw (new InvalidOperationException("No layers to zoom to")); } GeoAPI.Geometries.IEnvelope bbox = null; for (int i = 0; i < this.Layers.Count; i++) { if (bbox == null) { bbox = this.Layers[i].Envelope; } else { bbox.ExpandToInclude(this.Layers[i].Envelope); } } return(bbox); }
/// <summary> /// Transforms a <see cref="GisSharpBlog.NetTopologySuite.Geometries.Envelope"/>. /// </summary> /// <param name="box">BoundingBox to transform</param> /// <param name="transform">Math Transform</param> /// <returns>Transformed object</returns> public static GeoAPI.Geometries.IEnvelope TransformBox(GeoAPI.Geometries.IEnvelope box, IMathTransform transform) { if (box == null) { return(null); } double[][] corners = new double[4][]; corners[0] = transform.Transform(ToLightStruct(box.MinX, box.MinY)); //LL corners[1] = transform.Transform(ToLightStruct(box.MaxX, box.MaxY)); //UR corners[2] = transform.Transform(ToLightStruct(box.MinX, box.MaxY)); //UL corners[3] = transform.Transform(ToLightStruct(box.MaxX, box.MinY)); //LR IEnvelope result = GeometryFactory.CreateEnvelope(); foreach (double[] p in corners) { result.ExpandToInclude(p[0], p[1]); } return(result); }
/// <summary> /// Returns geometries within the specified bounding box /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection <GeoAPI.Geometries.IGeometry> GetGeometriesInView(GeoAPI.Geometries.IEnvelope bbox) { Collection <IGeometry> features = new Collection <IGeometry>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT ST.AsBinary(" + this.BuildGeometryExpression() + ") "; 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 (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { if (dr[0] != DBNull.Value) { GeoAPI.Geometries.IGeometry geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]); if (geom != null) { features.Add(geom); } } } } conn.Close(); } } return(features); }
private string BuildEnvelope(GeoAPI.Geometries.IEnvelope bbox) { /* * if (this.TargetSRID > 0 && !string.IsNullOrEmpty(SrsWkt).SrsWkt > 0 && this.SrsWkt != this.TargetSRID) * return string.Format(SharpMap.Map.numberFormat_EnUS, * "ST.Transform(ST.MakeEnvelope({0},{1},{2},{3},{4}),{5})", * bbox.MinX, * bbox.MinY, * bbox.MaxX, * bbox.MaxY, * this.TargetSRID, * this.SrsWkt); * else */ return(string.Format(SharpMap.Map.numberFormat_EnUS, "ST.MakeEnvelope({0},{1},{2},{3},{4})", bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY, this.SrsWkt)); }
/// <summary> /// Returns geometries within the specified bounding box /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection <GeoAPI.Geometries.IGeometry> GetGeometriesInView(GeoAPI.Geometries.IEnvelope bbox) { Collection <GeoAPI.Geometries.IGeometry> features = new Collection <GeoAPI.Geometries.IGeometry>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string BoxIntersect = GetBoxClause(bbox); string strSQL = "SELECT " + this.GeometryColumn + " AS Geom "; strSQL += "FROM " + this.Table + " WHERE "; strSQL += BoxIntersect; if (!String.IsNullOrEmpty(_defintionQuery)) { strSQL += " AND " + this.DefinitionQuery; } using (SqlCommand command = new SqlCommand(strSQL, conn)) { conn.Open(); using (SqlDataReader dr = command.ExecuteReader()) { while (dr.Read()) { if (dr[0] != DBNull.Value) { GeoAPI.Geometries.IGeometry geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[0]); if (geom != null) { features.Add(geom); } } } } conn.Close(); } } return(features); }
/// <summary> /// Returns geometry Object IDs whose bounding box intersects 'bbox' /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection <uint> GetObjectIDsInView(GeoAPI.Geometries.IEnvelope bbox) { Collection <uint> objectlist = new Collection <uint>(); using (SqlConnection conn = new SqlConnection(this.ConnectionString)) { string strSQL = "SELECT * FROM ST.FilterQuery('" + this.Table + "', '" + this.GeometryColumn + "', " + this.BuildEnvelope(bbox) + ")"; if (!String.IsNullOrEmpty(this.DefinitionQuery)) { strSQL += " WHERE " + this.DefinitionQuery; } if (!String.IsNullOrEmpty(this.OrderQuery)) { strSQL += " ORDER BY " + this.OrderQuery; } 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); }
private string BuildEnvelope(GeoAPI.Geometries.IEnvelope bbox) { if (this.TargetSRID > 0 && this.SRID > 0 && this.SRID != this.TargetSRID) { return(string.Format(SharpMap.Map.numberFormat_EnUS, "ST.Transform(ST.MakeEnvelope({0},{1},{2},{3},{4}),{5})", bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY, this.TargetSRID, this.SRID)); } else { return(string.Format(SharpMap.Map.numberFormat_EnUS, "ST.MakeEnvelope({0},{1},{2},{3},{4})", bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY, this.SRID)); } }
public void GetFeaturesInView(GeoAPI.Geometries.IEnvelope bbox, SharpMap.Data.FeatureDataSet ds) { ExecuteIntersectionQuery(bbox, ds); }
/// <summary> /// Creates a new table in a Microsoft SQL Server database and copies rows from an existing datasource. /// </summary> /// <remarks> /// <para>The datatable created will contain six extra columns besides the attribute data: "OID" (Object ID row), /// "WKB_Geometry" (Geometry stored as WKB), and Envelope_MinX, Envelope_MinY, Envelope_MaxX, Envelope_MaxY /// for geometry bounding box.</para> /// <para> /// <example> /// Upload a ShapeFile to a database: /// <code> /// public void CreateDatabase(string shapeFile) /// { /// if (!System.IO.File.Exists(shapeFile)) /// { /// MessageBox.Show("File not found"); /// return; /// } /// ShapeFile shp = new ShapeFile(shapeFile, false); /// //Create tablename from filename /// string tablename = shapeFile.Substring(shapeFile.LastIndexOf('\\') + 1, /// shapeFile.LastIndexOf('.') - shapeFile.LastIndexOf('\\') - 1); /// //Create connectionstring /// string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|GeoDatabase.mdf;Integrated Security=True;User Instance=True"; /// int count = SharpMap.Data.Providers.MsSql.CreateDataTable(shp, tablename, connstr); /// MessageBox.Show("Uploaded " + count.ToString() + " features to datatable '" + tablename + "'"); /// } /// </code> /// </example> /// </para> /// </remarks> /// <param name="datasource">Datasource to upload</param> /// <param name="tablename">Name of table to create (existing table will be overwritten!)</param> /// <param name="connstr">Connection string to database</param> /// <returns>Number or rows inserted, -1 if failed and 0 if table created but no rows inserted.</returns> public static int CreateDataTable(SharpMap.Data.Providers.IFeatureProvider datasource, string tablename, string connstr) { if (datasource is IFileBased) { IFileBased fileBasedDataSource = (IFileBased)datasource; fileBasedDataSource.Open(fileBasedDataSource.Path); } // TODO: this should work as IFeature FeatureDataRow geom = (FeatureDataRow)datasource.GetFeature(0); DataColumnCollection columns = geom.Table.Columns; int counter = -1; using (SqlConnection conn = new SqlConnection(connstr)) { SqlCommand command = new SqlCommand(); command.Connection = conn; conn.Open(); //Try to drop table if it exists try { command.CommandText = "DROP TABLE \"" + tablename + "\";"; command.ExecuteNonQuery(); } catch { } //Create new table for storing the datasource string sql = "CREATE TABLE " + tablename + " (oid INTEGER IDENTITY PRIMARY KEY, WKB_Geometry Image, " + "Envelope_MinX real, Envelope_MinY real, Envelope_MaxX real, Envelope_MaxY real"; foreach (DataColumn col in columns) { if (col.DataType != typeof(String)) { sql += ", " + col.ColumnName + " " + Type2SqlType(col.DataType).ToString(); } else { sql += ", " + col.ColumnName + " VARCHAR(256)"; } } command.CommandText = sql + ");"; command.ExecuteNonQuery(); counter++; ICollection <int> indexes = datasource.GetObjectIDsInView(datasource.GetExtents()); //Select all indexes in shapefile, loop through each feature and insert them one-by-one foreach (int idx in indexes) { //Get feature from shapefile // TODO: this should work as IFeature SharpMap.Data.FeatureDataRow feature = (FeatureDataRow)datasource.GetFeature(idx); if (counter == 0) { //Create insert script string strSQL = " ("; foreach (DataColumn col in feature.Table.Columns) { strSQL += "@" + col.ColumnName + ","; } strSQL += "@WKB_Geometry,@Envelope_MinX,@Envelope_MinY, " + "@Envelope_MaxX,@Envelope_MaxY)"; strSQL = "INSERT INTO " + tablename + strSQL.Replace("@", "") + " VALUES" + strSQL; command.CommandText = strSQL; command.Parameters.Clear(); //Add datacolumn parameters foreach (DataColumn col in feature.Table.Columns) { command.Parameters.Add("@" + col.ColumnName, Type2SqlType(col.DataType)); } //Add geometry parameters command.Parameters.Add("@WKB_Geometry", SqlDbType.VarBinary); command.Parameters.Add("@Envelope_MinX", SqlDbType.Real); command.Parameters.Add("@Envelope_MinY", SqlDbType.Real); command.Parameters.Add("@Envelope_MaxX", SqlDbType.Real); command.Parameters.Add("@Envelope_MaxY", SqlDbType.Real); } //Set values foreach (DataColumn col in feature.Table.Columns) { command.Parameters["@" + col.ColumnName].Value = feature[col]; } if (feature.Geometry != null) { command.Parameters["@WKB_Geometry"].Value = feature.Geometry.AsBinary(); //Add the geometry as Well-Known Binary GeoAPI.Geometries.IEnvelope box = feature.Geometry.EnvelopeInternal; command.Parameters["@Envelope_MinX"].Value = box.MinX; command.Parameters["@Envelope_MinY"].Value = box.MinY; command.Parameters["@Envelope_MaxX"].Value = box.MaxX; command.Parameters["@Envelope_MaxY"].Value = box.MaxY; } else { command.Parameters["@WKB_Geometry"].Value = DBNull.Value; command.Parameters["@Envelope_MinX"].Value = DBNull.Value; command.Parameters["@Envelope_MinY"].Value = DBNull.Value; command.Parameters["@Envelope_MaxX"].Value = DBNull.Value; command.Parameters["@Envelope_MaxY"].Value = DBNull.Value; } //Insert row command.ExecuteNonQuery(); counter++; } //Create indexes command.Parameters.Clear(); command.CommandText = "CREATE INDEX [IDX_Envelope_MinX] ON " + tablename + " (Envelope_MinX)"; command.ExecuteNonQuery(); command.CommandText = "CREATE INDEX [IDX_Envelope_MinY] ON " + tablename + " (Envelope_MinY)"; command.ExecuteNonQuery(); command.CommandText = "CREATE INDEX [IDX_Envelope_MaxX] ON " + tablename + " (Envelope_MaxX)"; command.ExecuteNonQuery(); command.CommandText = "CREATE INDEX [IDX_Envelope_MaxY] ON " + tablename + " (Envelope_MaxY)"; command.ExecuteNonQuery(); conn.Close(); } if (datasource is IFileBased) { ((IFileBased)datasource).Close(); } return(counter); }
private string GetBoxClause(GeoAPI.Geometries.IEnvelope bbox) { return(String.Format(SharpMap.Map.numberFormat_EnUS, "(Envelope_MinX < {0} AND Envelope_MaxX > {1} AND Envelope_MinY < {2} AND Envelope_MaxY > {3})", bbox.MaxX, bbox.MinX, bbox.MaxY, bbox.MinY)); }