public void TestCaseSensitiveKeyColumn() { var path = Path.GetTempFileName(); try { var sqlite = new System.Data.SQLite.SQLiteConnection("Data Source=" + path); sqlite.Open(); var cmd = sqlite.CreateCommand(); cmd.CommandText = "create table test(col_ID integer primary key, name text, shape blob)"; cmd.ExecuteNonQuery(); cmd.Dispose(); sqlite.Close(); sqlite.Dispose(); using (var sq = new ManagedSpatiaLite("Data Source=" + path, "test", "shape", "COL_ID")) { var ext = new Envelope(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(0, ds.Tables[0].Count); } } catch (Exception ex) { Assert.Fail("Got exception, should not happen"); } finally { File.Delete(path); } }
public static SharpMap.Data.FeatureDataRow FindGeoNearPoint( GeoAPI.Geometries.IPoint point, SharpMap.Layers.VectorLayer layer, double amountGrow) { var box = new GeoAPI.Geometries.Envelope(point.Coordinate); box.ExpandBy(amountGrow); var fds = new SharpMap.Data.FeatureDataSet(); layer.DataSource.ExecuteIntersectionQuery(box, fds); SharpMap.Data.FeatureDataRow result = null; var minDistance = double.MaxValue; foreach (SharpMap.Data.FeatureDataTable fdt in fds.Tables) { foreach (SharpMap.Data.FeatureDataRow fdr in fdt.Rows) { if (fdr.Geometry != null) { var distance = point.Distance(fdr.Geometry); if (distance < minDistance) { result = fdr; minDistance = distance; } } } } return(result); }
public void TestExecuteIntersectionQueryRegion53WithTowns() { using (var sq = CreateProvider("regions")) { var g = sq.GetGeometryByID(53); var env = g.EnvelopeInternal; using (var sqPoints = CreateProvider("towns")) { var featureCount = sqPoints.GetFeatureCount(); sqPoints.UseSpatiaLiteIndex = true; var fds = new SharpMap.Data.FeatureDataSet(); NUnit.Framework.Assert.DoesNotThrow(() => sqPoints.ExecuteIntersectionQuery(env, fds)); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); var table1 = fds.Tables[0]; NUnit.Framework.Assert.AreEqual("towns", table1.TableName); NUnit.Framework.Assert.IsTrue(table1.Rows.Count > 0); NUnit.Framework.Assert.IsTrue(featureCount > table1.Rows.Count); fds = new SharpMap.Data.FeatureDataSet(); NUnit.Framework.Assert.DoesNotThrow(() => sqPoints.ExecuteIntersectionQuery(g, fds)); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); var table2 = fds.Tables[0]; NUnit.Framework.Assert.AreEqual("towns", table2.TableName); NUnit.Framework.Assert.IsTrue(table2.Rows.Count > 0); NUnit.Framework.Assert.IsTrue(featureCount > table2.Rows.Count); NUnit.Framework.Assert.IsTrue(table1.Rows.Count > table2.Rows.Count); } } }
/// <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(IEnvelope bbox, SharpMap.Data.FeatureDataSet ds) { List <IGeometry> features = new List <IGeometry>(); using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(_ConnectionString)) { string strBbox = "box2d('BOX3D(" + bbox.MinX.ToString(SharpMap.Map.numberFormat_EnUS) + " " + bbox.MinY.ToString(SharpMap.Map.numberFormat_EnUS) + "," + bbox.MaxX.ToString(SharpMap.Map.numberFormat_EnUS) + " " + bbox.MaxY.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); } } } }
public void TestExecuteIntersectionQueryRegion53WithTowns() { using (var sq = CreateProvider("regions")) { var g = sq.GetGeometryByID(53); var env = g.EnvelopeInternal; using (var sqPoints = CreateProvider("towns")) { var featureCount = sqPoints.GetFeatureCount(); sqPoints.UseSpatiaLiteIndex = true; var fds = new SharpMap.Data.FeatureDataSet(); NUnit.Framework.Assert.DoesNotThrow(() => sqPoints.ExecuteIntersectionQuery(env, fds)); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); var table1 = fds.Tables[0]; NUnit.Framework.Assert.AreEqual("towns", table1.TableName); NUnit.Framework.Assert.IsTrue(table1.Rows.Count > 0); NUnit.Framework.Assert.IsTrue(featureCount > table1.Rows.Count); fds = new SharpMap.Data.FeatureDataSet(); NUnit.Framework.Assert.DoesNotThrow(() => sqPoints.ExecuteIntersectionQuery(g, fds)); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); var table2 = fds.Tables[0]; NUnit.Framework.Assert.AreEqual("towns", table2.TableName); NUnit.Framework.Assert.IsTrue(table2.Rows.Count > 0); NUnit.Framework.Assert.IsTrue(featureCount > table2.Rows.Count); NUnit.Framework.Assert.IsTrue(table1.Rows.Count > table2.Rows.Count); } } }
public static SharpMap.Map InitializeMap(float angle) { var dataSource = new SharpMap.Data.Providers.ShapeFile( string.Format("{0}/roads.shp", ShapefileSample.PathOsm), true); var fds = new SharpMap.Data.FeatureDataSet(); dataSource.Open(); dataSource.ExecuteIntersectionQuery(dataSource.GetExtents(), fds); dataSource.Close(); var gfp = new SharpMap.Data.Providers.GeometryFeatureProvider(fds.Tables[0]); var vl = new SharpMap.Layers.VectorLayer("roads", gfp) { CoordinateTransformation = LayerTools.Dhdn2ToWgs84 }; var ll = new SharpMap.Layers.LabelLayer("labels") { DataSource = gfp, CoordinateTransformation = LayerTools.Dhdn2ToWgs84, LabelColumn = "name", MultipartGeometryBehaviour = SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest, }; ll.Style.Halo = new System.Drawing.Pen(System.Drawing.Color.Red); //ll.Style.IgnoreLength = true; var map = new SharpMap.Map(); map.Layers.Add(vl); map.Layers.Add(ll); map.Layers.Add(vl); map.ZoomToExtents(); return map; }
public static SharpMap.Data.FeatureDataRow FindGeoNearPoint( GeoAPI.Geometries.IPoint point, SharpMap.Layers.VectorLayer layer, double amountGrow) { var box = new GeoAPI.Geometries.Envelope(point.Coordinate); box.ExpandBy(amountGrow); var fds = new SharpMap.Data.FeatureDataSet(); layer.DataSource.ExecuteIntersectionQuery(box, fds); SharpMap.Data.FeatureDataRow result = null; var minDistance = double.MaxValue; foreach (SharpMap.Data.FeatureDataTable fdt in fds.Tables) { foreach (SharpMap.Data.FeatureDataRow fdr in fdt.Rows) { if (fdr.Geometry != null) { var distance = point.Distance(fdr.Geometry); if (distance < minDistance) { result = fdr; minDistance = distance; } } } } return result; }
public void TestExecuteIntersectionQuery() { NUnit.Framework.Assert.IsTrue(System.IO.File.Exists(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp")), "Specified shapefile is not present!"); var shp = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), false, false); shp.Open(); var fds = new SharpMap.Data.FeatureDataSet(); var bbox = shp.GetExtents(); //narrow it down bbox.ExpandBy(-0.425*bbox.Width, -0.425*bbox.Height); //Just to avoid that initial query does not impose performance penalty shp.DoTrueIntersectionQuery = false; shp.ExecuteIntersectionQuery(bbox, fds); fds.Tables.RemoveAt(0); //Perform query once more var sw = new System.Diagnostics.Stopwatch(); sw.Start(); shp.ExecuteIntersectionQuery(bbox, fds); sw.Stop(); System.Console.WriteLine("Queried using just envelopes:\n" + fds.Tables[0].Rows.Count + " in " + sw.ElapsedMilliseconds + "ms."); fds.Tables.RemoveAt(0); shp.DoTrueIntersectionQuery = true; sw.Reset(); sw.Start(); shp.ExecuteIntersectionQuery(bbox, fds); sw.Stop(); System.Console.WriteLine("Queried using prepared geometries:\n" + fds.Tables[0].Rows.Count + " in " + sw.ElapsedMilliseconds + "ms."); }
public void TestCaseSensitiveKeyColumn() { var path = Path.GetTempFileName(); try { var sqlite = new System.Data.SQLite.SQLiteConnection("Data Source=" + path); sqlite.Open(); var cmd = sqlite.CreateCommand(); cmd.CommandText = "create table test(col_ID integer primary key, name text, shape blob)"; cmd.ExecuteNonQuery(); cmd.Dispose(); sqlite.Close(); sqlite.Dispose(); using (var sq = new ManagedSpatiaLite("Data Source=" + path, "test", "shape", "COL_ID")) { var ext = new Envelope(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(0, ds.Tables[0].Count); } } catch (Exception ex) { Assert.Fail("Got exception, should not happen"); } finally { File.Delete(path); } }
public static void ReprojectFeatureDataSet(SharpMap.Data.FeatureDataSet fds, GeoAPI.CoordinateSystems.ICoordinateSystem target) { for (var i = 0; i < fds.Tables.Count; i++) { var fdt = fds.Tables[i]; ReprojectFeatureDataTable(fdt, target); } }
/// <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); } } } }
public void TestExecuteIntersectionQuery() { using (var sq = GetTestProvider()) { var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(), ds); Assert.AreEqual(100, ds.Tables[0].Rows.Count); } }
public void TestExecuteIntersectionQuery() { SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(), ds); Assert.AreEqual(100, ds.Tables[0].Rows.Count); }
public void TestSetUp() { using (var sf = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("roads_ugl.shp"))) { sf.Open(); var fds = new SharpMap.Data.FeatureDataSet(); sf.ExecuteIntersectionQuery(sf.GetExtents(), fds); _provider = new SharpMap.Data.Providers.GeometryFeatureProvider(fds.Tables[0]); } }
public void TestReadPoints() { using (var sq = CreateProvider("towns")) { var ext = sq.GetExtents(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(8101, ds.Tables[0].Count); } }
public void TestSetUp() { using (var sf = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("roads_ugl.shp"))) { sf.Open(); var fds = new SharpMap.Data.FeatureDataSet(); sf.ExecuteIntersectionQuery(sf.GetExtents(), fds); _provider = new SharpMap.Data.Providers.GeometryFeatureProvider(fds.Tables[0]); } }
public void TestReadPoints() { using (var sq = CreateProvider("towns")) { var ext = sq.GetExtents(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(8101, ds.Tables[0].Count); } }
public void TestReadPolys() { using (var sq = new SharpMap.Data.Providers.ManagedSpatiaLite(GetTestDBPath(), "regions", "Geometry", "ROWID")) { var ext = sq.GetExtents(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(109, ds.Tables[0].Count); } }
public void TestReadPolys() { using (var sq = new SharpMap.Data.Providers.ManagedSpatiaLite(GetTestDBPath(), "regions", "Geometry", "ROWID")) { var ext = sq.GetExtents(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(109, ds.Tables[0].Count); } }
/// <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(IEnvelope bbox, SharpMap.Data.FeatureDataSet ds) { List <IGeometry> features = new List <IGeometry>(); 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); } } } }
public void TestExecuteIntersectionQuery(SqlServerProviderMode providerMode, SharpMap.Data.Providers.SqlServerSpatialObjectType spatialType, bool validateGeometries) { SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(providerMode, spatialType); sq.ValidateGeometries = validateGeometries; SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(spatialType), ds); NUnit.Framework.Assert.AreEqual(sq.ValidateGeometries ? _numValidatedGeoms : _numValidGeoms, ds.Tables[0].Rows.Count); }
public void DoTest() { SharpMap.Data.Providers.ShapeFile sf = new SharpMap.Data.Providers.ShapeFile("cities.shp"); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); sf.ExecuteIntersectionQuery(sf.GetExtents(), fds); SharpMap.Data.Providers.FeatureProvider gfp = new SharpMap.Data.Providers.FeatureProvider(fds.Tables[0]); System.Data.DataTable dt = new System.Data.DataTable("external"); dt.Columns.Add("city", typeof(string)); dt.Columns.Add("males", typeof(int)); dt.Columns.Add("females", typeof(int)); }
private void _cmBoxLayer_SelectedIndexChanged(object sender, EventArgs e) { SharpMap.Layers.VectorLayer layer = _map.GetLayerByName(this._cmBoxLayer.SelectedItem.ToString()) as SharpMap.Layers.VectorLayer; if (layer != null) { SharpMap.Data.FeatureDataSet set = new SharpMap.Data.FeatureDataSet(); layer.ExecuteIntersectionQuery(layer.DataSource.GetExtents(), set); foreach (DataColumn kol in set.Tables[0].Columns) { this._cmBoxAttribute.Items.Add(kol.ColumnName); } } }
/// <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); } } } }
/// <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); } } } }
public void TestExecuteIntersectionQueryExceedGeogMaxExtents(SqlServerProviderMode providerMode, SharpMap.Data.Providers.SqlServerSpatialObjectType spatialType, double x1, double x2, double y1, double y2) { // occurs when user zooms out beyond map extents. For Geog, when latitude approaches 90 N or S can result in // error 24206: "The specified input cannot be accepted because it contains an edge with antipodal points." // Longitudes exceeding -179.99999999 or 180.0 are "wrapped" resulting in unexpected polygon (also contributes to err 24206) SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(providerMode, spatialType); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(new GeoAPI.Geometries.Envelope(x1, x2, y1, y2), ds); NUnit.Framework.Assert.AreEqual(sq.ValidateGeometries ? _numValidatedGeoms : _numValidGeoms, ds.Tables[0].Rows.Count); }
// NPGSQL EXCEPTION - BAD GEOMETRY FORMATING IN THE RESULTING QUERY && TABLE NAMES MUST BE ALTERED NOT TO CONTAIN "" private void GetGeometryIntersections(IGeometry geometry) { SharpMap.Data.Providers.PostGIS postGisProv = new SharpMap.Data.Providers.PostGIS(Constants.connStr, _activeLayer, Constants.geomName, Constants.idName); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); postGisProv.Open(); postGisProv.ExecuteIntersectionQuery(geometry, fds); postGisProv.Close(); //System.Windows.Forms.MessageBox.Show(fds.Tables[0].Rows.Count.ToString()); _view.DataGridView = fds.Tables[0]; }
public void TestExecuteIntersectionQueryAllHints() { SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(); sq.NoLockHint = true; sq.ForceSeekHint = true; sq.ForceIndex = "IX_roads_ugl_GEOM"; SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(), ds); Assert.AreEqual(100, ds.Tables[0].Rows.Count); }
public void Test09ExecuteIntersectionQuery() { using (var provider = GetProvider()) { var ext = provider.GetExtents(); ext.ExpandBy(-0.25 * ext.Width, -0.25 * ext.Height); var fds = new SharpMap.Data.FeatureDataSet(); NUnit.Framework.Assert.DoesNotThrow(() => provider.ExecuteIntersectionQuery(ext, fds)); NUnit.Framework.Assert.Greater(fds.Tables.Count, 0); NUnit.Framework.Assert.Greater(fds.Tables[0].Count, 0); NUnit.Framework.Assert.Less(fds.Tables[0].Count, provider.GetFeatureCount()); } }
public void TestReadLines() { using (var sq = CreateProvider("highways")) { var ext = sq.GetExtents(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(775, ds.Tables[0].Count); var env = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(sq.SRID).ToGeometry(ext); var dsEnv = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(env, dsEnv); NUnit.Framework.Assert.AreEqual(775, dsEnv.Tables[0].Count); } }
public void TestExecuteIntersectionQueryAllHints(SqlServerProviderMode providerMode, SharpMap.Data.Providers.SqlServerSpatialObjectType spatialType, bool validateGeometries) { SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(providerMode, spatialType); sq.NoLockHint = true; sq.ForceSeekHint = true; sq.ForceIndex = spatialType == SharpMap.Data.Providers.SqlServerSpatialObjectType.Geometry ? GeometrySpatialIndex : GeographySpatialIndex;; sq.ValidateGeometries = validateGeometries; SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(spatialType), ds); // Note: ValidateGeometries ignored when using ForceSeek or ForceIndex NUnit.Framework.Assert.AreEqual(_numValidGeoms, ds.Tables[0].Rows.Count); }
public void TestReadLines() { using (var sq = CreateProvider("highways")) { var ext = sq.GetExtents(); var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(ext, ds); NUnit.Framework.Assert.AreEqual(775, ds.Tables[0].Count); var env = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(sq.SRID).ToGeometry(ext); var dsEnv = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(env, dsEnv); NUnit.Framework.Assert.AreEqual(775, dsEnv.Tables[0].Count); } }
public void TestDiscussionNtsAndBaffeledOleDb() { var reader = new NetTopologySuite.IO.WKTReader(); var poly = reader.Read( @"POLYGON ((428999.76819468878 360451.93329044303, 428998.25517286535 360420.80827007542, 429023.1119599645 360406.75878171506, 429004.52340613387 360451.71714446822, 429004.52340613387 360451.71714446822, 428999.76819468878 360451.93329044303))"); var table = WriteCsv(); var p = new SharpMap.Data.Providers.OleDbPoint( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + System.IO.Path.GetTempPath() + "\";" + "Extended Properties=\"text;HDR=Yes;FMT=Delimited\"", table, "ID", "X", "Y"); var extents = p.GetExtents(); NUnit.Framework.Assert.AreEqual(4, p.GetFeatureCount()); p.DefinitionQuery = "Name='One'"; NUnit.Framework.Assert.AreEqual(1, p.GetFeatureCount()); var fdr = p.GetFeatureByOid(1); NUnit.Framework.Assert.AreEqual(1, (int)fdr.Attributes[0]); p.DefinitionQuery = string.Empty; var fds = new SharpMap.Data.FeatureDataSet(); p.ExecuteIntersectionQuery(extents, fds); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); NUnit.Framework.Assert.AreEqual(4, fds.Tables[0].Rows.Count); fds.Tables.Remove(fds.Tables[0]); p.ExecuteIntersectionQuery(poly, fds); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); NUnit.Framework.Assert.AreEqual(3, fds.Tables[0].Rows.Count); var inside = new System.Collections.Generic.List <bool>(new[] { false, true, true, true }); NUnit.Framework.Assert.AreEqual(System.Linq.Enumerable.Count(inside, b => b), fds.Tables[0].Rows.Count); var ext = p.GetExtents(); var oids = p.GetOidsInView(ext); NUnit.Framework.Assert.AreEqual(4, System.Linq.Enumerable.Count(oids)); System.IO.File.Delete(System.IO.Path.Combine(System.IO.Path.GetTempPath(), table)); }
private void DoExecuteIntersectionQuery(int obj) { var ext = _provider.GetExtents(); var minX = _rnd.Next((int)ext.MinX, (int)ext.MaxX); var maxX = _rnd.Next((int)minX, (int)ext.MaxX); var minY = _rnd.Next((int)ext.MinY, (int)ext.MaxY); var maxY = _rnd.Next((int)minY, (int)ext.MaxY); var box = new GeoAPI.Geometries.Envelope(minX, maxX, minY, maxY); Console.WriteLine(@"{0:000}/{2:00}: Executing intersection query agains {1}", obj, box, Thread.CurrentThread.ManagedThreadId); var fds = new SharpMap.Data.FeatureDataSet(); _provider.ExecuteIntersectionQuery(box, fds); var table = fds.Tables[0]; var count = table != null ? table.Rows.Count : 0; Console.WriteLine(@"{0:000}/{3:00}: Executed intersection query agains {1} returned {2} features", obj, box, count, Thread.CurrentThread.ManagedThreadId); }
// Actual drawing is done here. This needs a lot of work. // To Do: // Pen and Brush width should not be fixed. // Some way to rendor the symbol graphics // Assigning the outline colors instead of using black //static public VectorLayer Render(ColorName cName, ref VectorLayer vectorLayer, Ogr layerProvider, OSGeo.OGR.Feature feature, OSGeo.OGR.FieldDefn field, string WKTGeometry) //static public VectorLayer Render(S57.S57Layer layerCollection) static public VectorLayer Render(string layerName, SharpMap.Data.FeatureDataSet fds) { Map map = new Map(); VectorLayer vectorLayer = new VectorLayer(layerName); /* if (layerProvider.OgrGeometryTypeString.IndexOf("Polygon") > 0) * { * vectorLayer.Style.Fill = new SolidBrush(colorMaptoRGBI(cName)); * vectorLayer.Style.Outline = new Pen(colorMaptoRGBI(ColorName.CHBLK), 3.0f); * vectorLayer.Style.EnableOutline = true; * } * else * { * vectorLayer.Style.Line = new Pen(colorMaptoRGBI(ColorName.CHBLK), 3.0f); * } */ return(vectorLayer); }
private void DoExecuteIntersectionQuery(int obj) { var ext = _provider.GetExtents(); var minX = _rnd.Next((int)ext.MinX, (int)ext.MaxX); var maxX = _rnd.Next((int)minX, (int)ext.MaxX); var minY = _rnd.Next((int)ext.MinY, (int)ext.MaxY); var maxY = _rnd.Next((int)minY, (int)ext.MaxY); var box = new GeoAPI.Geometries.Envelope(minX, maxX, minY, maxY); Console.WriteLine(@"{0:000}/{2:00}: Executing intersection query agains {1}", obj, box, Thread.CurrentThread.ManagedThreadId); var fds = new SharpMap.Data.FeatureDataSet(); _provider.ExecuteIntersectionQuery(box, fds); var table = fds.Tables[0]; var count = table != null ? table.Rows.Count : 0; Console.WriteLine(@"{0:000}/{3:00}: Executed intersection query agains {1} returned {2} features", obj, box, count, Thread.CurrentThread.ManagedThreadId); }
public void TestDiscussionNtsAndBaffeledOleDb() { var reader = new NetTopologySuite.IO.WKTReader(); var poly = reader.Read( @"POLYGON ((428999.76819468878 360451.93329044303, 428998.25517286535 360420.80827007542, 429023.1119599645 360406.75878171506, 429004.52340613387 360451.71714446822, 429004.52340613387 360451.71714446822, 428999.76819468878 360451.93329044303))"); var table = WriteCsv(); var p = new SharpMap.Data.Providers.OleDbPoint( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + System.IO.Path.GetTempPath() + "\";" + "Extended Properties=\"text;HDR=Yes;FMT=Delimited\"", table, "ID", "X", "Y"); var extents = p.GetExtents(); NUnit.Framework.Assert.AreEqual(4, p.GetFeatureCount()); p.DefinitionQuery = "Name='One'"; NUnit.Framework.Assert.AreEqual(1, p.GetFeatureCount()); var fdr = p.GetFeature(1); NUnit.Framework.Assert.AreEqual(1, (int)fdr[0]); p.DefinitionQuery = string.Empty; var fds = new SharpMap.Data.FeatureDataSet(); p.ExecuteIntersectionQuery(extents, fds); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); NUnit.Framework.Assert.AreEqual(4, fds.Tables[0].Rows.Count); fds.Tables.Clear(); p.ExecuteIntersectionQuery(poly, fds); NUnit.Framework.Assert.AreEqual(1, fds.Tables.Count); NUnit.Framework.Assert.AreEqual(3, fds.Tables[0].Rows.Count); var inside = new System.Collections.Generic.List<bool>(new[] { false, true, true, true }); NUnit.Framework.Assert.AreEqual(System.Linq.Enumerable.Count(inside, (b) => b == true), fds.Tables[0].Rows.Count); var ext = p.GetExtents(); var oids = p.GetObjectIDsInView(ext); NUnit.Framework.Assert.AreEqual(4, oids.Count); System.IO.File.Delete(System.IO.Path.Combine(System.IO.Path.GetTempPath(), table)); }
public void TestExecuteIntersectionQueryWithFilterDelegate() { NUnit.Framework.Assert.IsTrue(System.IO.File.Exists(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp")), "Specified shapefile is not present!"); var shp = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), false, false); shp.Open(); var fds = new SharpMap.Data.FeatureDataSet(); var bbox = shp.GetExtents(); //narrow it down bbox.ExpandBy(-0.425 * bbox.Width, -0.425 * bbox.Height); //Just to avoid that initial query does not impose performance penalty shp.DoTrueIntersectionQuery = false; shp.FilterDelegate = JustTracks; shp.ExecuteIntersectionQuery(bbox, fds); fds.Tables.RemoveAt(0); //Perform query once more var sw = new System.Diagnostics.Stopwatch(); sw.Start(); shp.ExecuteIntersectionQuery(bbox, fds); sw.Stop(); System.Console.WriteLine("Queried using just envelopes:\n" + fds.Tables[0].Rows.Count + " in " + sw.ElapsedMilliseconds + "ms."); fds.Tables.RemoveAt(0); shp.DoTrueIntersectionQuery = true; sw.Reset(); sw.Start(); shp.ExecuteIntersectionQuery(bbox, fds); sw.Stop(); System.Console.WriteLine("Queried using prepared geometries:\n" + fds.Tables[0].Rows.Count + " in " + sw.ElapsedMilliseconds + "ms."); }
/// <summary> /// Returns all objects whose boundingbox intersects bbox. /// </summary> /// <remarks> /// <para> /// Please note that this method doesn't guarantee that the geometries returned actually intersect 'bbox', but only /// that their boundingbox intersects 'bbox'. /// </para> /// </remarks> /// <param name="bbox"></param> /// <param name="ds"></param> /// <returns></returns> public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds) { //Use the spatial index to get a list of features whose boundingbox intersects bbox List <uint> objectlist = GetObjectIDsInView(bbox); SharpMap.Data.FeatureDataTable dt = dbaseFile.NewTable; for (int i = 0; i < objectlist.Count; i++) { SharpMap.Data.FeatureDataRow fdr = dbaseFile.GetFeature(objectlist[i], dt); fdr.Geometry = ReadGeometry(objectlist[i]); if (fdr.Geometry != null) { if (fdr.Geometry.GetBoundingBox().Intersects(bbox)) { if (FilterDelegate == null || FilterDelegate(fdr)) { dt.AddRow(fdr); } } } } ds.Tables.Add(dt); }
public void DoTest() { SharpMap.Data.Providers.ShapeFile sf = new SharpMap.Data.Providers.ShapeFile("cities.shp"); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); sf.ExecuteIntersectionQuery(sf.GetExtents(), fds); SharpMap.Data.Providers.FeatureProvider gfp = new SharpMap.Data.Providers.FeatureProvider(fds.Tables[0]); System.Data.DataTable dt = new System.Data.DataTable("external"); dt.Columns.Add("city", typeof (string)); dt.Columns.Add("males", typeof (int)); dt.Columns.Add("females", typeof (int)); }
private void SHP2KML(string shpFile, string kmlFile) { SharpMap.Data.Providers.ShapeFile shp = new SharpMap.Data.Providers.ShapeFile(shpFile); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); shp.Open(); shp.ExecuteIntersectionQuery(shp.GetExtents(), fds); System.Data.DataTable dt = fds.Tables[0]; KMLib.KMLRoot kml = new KMLib.KMLRoot(); for (int i = 0; i < dt.Rows.Count; i++ ) { SharpMap.Data.FeatureDataRow row = dt.Rows[i] as SharpMap.Data.FeatureDataRow; StringBuilder description = new StringBuilder(); for (int j = 0; j < dt.Columns.Count; j++) { description.Append("<p><b>" + capitalize(dt.Columns[j].ToString()) + "</b>: " + row[j] + "</p>\n"); } if (row.Geometry is SharpMap.Geometries.Point) { var pointGeom = row.Geometry as SharpMap.Geometries.Point; var placemark = new KMLib.Feature.Placemark(); placemark.Point = new KMLib.Geometry.KmlPoint((float) pointGeom.X, (float) pointGeom.Y); placemark.description = description.ToString(); kml.Document.Add(placemark); } else if (row.Geometry is SharpMap.Geometries.Polygon) { var polygonGeom = row.Geometry as SharpMap.Geometries.Polygon; var placemark = new KMLib.Feature.Placemark(); var polygon = new KMLib.Polygon(); var boundary = new KMLib.BoundaryIs(); foreach (SharpMap.Geometries.Point vertex in polygonGeom.ExteriorRing.Vertices) { boundary.LinearRing.Coordinates.Add(new Core.Geometry.Point3D(vertex.X, vertex.Y)); } boundary.LinearRing.CloseRing(); boundary.LinearRing.Extrude = true; polygon.OuterBoundaryIs = boundary; var interiorRing = new KMLib.BoundaryIs(); for (int j = 0; j < polygonGeom.NumInteriorRing; j++) { foreach (SharpMap.Geometries.Point point in polygonGeom.InteriorRing(j).Vertices) { interiorRing.LinearRing.Coordinates.Add(new Core.Geometry.Point3D(point.X, point.Y)); } interiorRing.LinearRing.CloseRing(); } polygon.InnerBoundaryIs = interiorRing; placemark.Polygon = polygon; kml.Document.Add(placemark); } } kml.Save(kmlFile); shp.Close(); btnConvert.Content = "Done Converting"; }
void Form1_OnDataUpdated() { if (RealtimeInfo.InvokeRequired) { SharpMap.Data.Providers.MemoryDataProviderBase.DataUpdated d = new SharpMap.Data.Providers.MemoryDataProviderBase.DataUpdated(Form1_OnDataUpdated); this.Invoke(d, null); return; } else { System.Collections.Generic.Dictionary<string, SharpMap.Data.Providers.IProvider> providers = IntelliTrack.Service.Common.Singleton<IntelliTrack.Client.Application.Imaging.ComplexMap>.Instance.GetRealTimeLayerProviders(); ; foreach (System.Collections.Generic.KeyValuePair<string, SharpMap.Data.Providers.IProvider> pair in providers) { SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); pair.Value.ExecuteIntersectionQuery(pair.Value.GetExtents(), fds); fds.Tables[0].TableName = pair.Key; RealtimeInfo.SetData(fds.Tables[0]); } //IntelliTrack.Service.Common.Singleton<IntelliTrack.Client.Application.Imaging.ComplexMap>.Instance.UDPDataArrived } }
public SharpMap.Data.FeatureDataSet SelectElements(SharpMap.Geometries.BoundingBox bbox, string layername) { if (!_MapLoaded) return null; SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); SharpMap.Layers.VectorLayer l = (SharpMap.Layers.VectorLayer)Layers_[layername]; l.DataSource.Open(); if (layername == "Frentes") { (l.DataSource as SharpMap.Data.Providers.MemoryDataProvider<IntelliTrack.Data.FrenteDataPoint>).ExecuteIntersectionQuery2(bbox.GetCentroid(), fds); } else { l.DataSource.ExecuteIntersectionQuery(bbox, fds); } l.DataSource.Close(); return fds; }
internal string GetFunctionValue(SharpMap.Geometries.Point p0) { // Aca esta funcion ejecuta el stored procedure para obtener mas // informacion del elemento sobre el que esta parado. // Dadas las coordenadas, se obtienen los elementos. SharpMap.Data.Providers.MemoryDataProvider<IntelliTrack.Data.TransporteDataPoint> dsource = null; if (Layers_.ContainsKey("Transporte Caña")) { dsource = (Layers_["Transporte Caña"] as SharpMap.Layers.VectorLayer).DataSource as SharpMap.Data.Providers.MemoryDataProvider<IntelliTrack.Data.TransporteDataPoint>; } else if (Layers_.ContainsKey("Cañeros")) { dsource = (Layers_["Cañeros"] as SharpMap.Layers.VectorLayer).DataSource as SharpMap.Data.Providers.MemoryDataProvider<IntelliTrack.Data.TransporteDataPoint>; } SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); if (dsource != null) dsource.ExecuteIntersectionQuery2(p0, fds); if (fds.Tables.Count > 0) { if (fds.Tables[0].Count > 0) { return this.GetFunctionValue(fds.Tables[0].Rows[0]["Transponder"].ToString()); } } return ""; }
public void TestExecuteIntersectionQuery() { foreach (var sq in GetTestProvider()) { var ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(), ds); Assert.AreEqual(100d, ds.Tables[0].Rows.Count, 2); } }
private void LlenarLista(SharpMap.Data.Providers.IProvider iProvider, System.Collections.Generic.Dictionary<string, bool> Lista) { SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); iProvider.ExecuteIntersectionQuery(iProvider.GetExtents(), fds); foreach (System.Data.DataRow row in (fds.Tables[0] as System.Data.DataTable).Rows) { Lista[row["Transponder"].ToString()] = true; } }
private void MapImage_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (_Map != null) { if (MouseUp != null) MouseUp(this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)), e); if (e.Button == MouseButtons.Left) { if (this.ActiveTool == Tools.ZoomOut) { double scale = 0.5; if (!mousedragging) { _Map.Center = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MapCenterChanged != null) MapCenterChanged(_Map.Center); } else { if (e.Y - mousedrag.Y < 0) //Zoom out scale = (float)Math.Pow(1 / (float)(mousedrag.Y - e.Y), 0.5); else //Zoom in scale = 1 + (e.Y - mousedrag.Y) * 0.1; } _Map.Zoom *= 1 / scale; if (MapZoomChanged != null) MapZoomChanged(_Map.Zoom); Refresh(); } else if (this.ActiveTool == Tools.ZoomIn) { double scale = 2; if (!mousedragging) { _Map.Center = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MapCenterChanged != null) MapCenterChanged(_Map.Center); } else { if (e.Y - mousedrag.Y < 0) //Zoom out scale = (float)Math.Pow(1 / (float)(mousedrag.Y - e.Y), 0.5); else //Zoom in scale = 1 + (e.Y - mousedrag.Y) * 0.1; } _Map.Zoom *= 1 / scale; if (MapZoomChanged != null) MapZoomChanged(_Map.Zoom); Refresh(); } else if (this.ActiveTool == Tools.Pan) { if (mousedragging) { System.Drawing.Point pnt = new System.Drawing.Point(this.Width / 2 + (mousedrag.X - e.Location.X), this.Height / 2 + (mousedrag.Y - e.Location.Y)); _Map.Center = this._Map.ImageToWorld(pnt); if (MapCenterChanged != null) MapCenterChanged(_Map.Center); } else { _Map.Center = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MapCenterChanged != null) MapCenterChanged(_Map.Center); } Refresh(); } else if (this.ActiveTool == Tools.Query) { if (_Map.Layers.Count > _queryLayerIndex && _queryLayerIndex > -1) { if (_Map.Layers[_queryLayerIndex].GetType() == typeof(SharpMap.Layers.VectorLayer)) { SharpMap.Layers.VectorLayer layer = _Map.Layers[_queryLayerIndex] as SharpMap.Layers.VectorLayer; IEnvelope bbox = GeometryFactory.CreatePoint(this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y))).EnvelopeInternal; bbox.ExpandBy(_Map.PixelSize * 5); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); layer.DataSource.Open(); layer.DataSource.ExecuteIntersectionQuery(bbox, ds); layer.DataSource.Close(); if (ds.Tables.Count > 0) if (MapQueried != null) MapQueried(ds.Tables[0]); else if (MapQueried != null) MapQueried(new SharpMap.Data.FeatureDataTable()); } } else MessageBox.Show("No active layer to query"); } } if (mousedragImg != null) { mousedragImg.Dispose(); mousedragImg = null; } mousedragging = false; } }
/// <summary> /// Gets FeatureInfo as text/plain /// </summary> /// <param name="strBBOX">string representation of a boundingbox</param> /// <returns>Plain text string with featureinfo results</returns> public static string CreateFeatureInfoPlain(SharpMap.Map map, string[] requestedLayers, Single x, Single y, int featureCount, string cqlFilter) { string vstr = "GetFeatureInfo results: \n"; foreach (string requestLayer in requestedLayers) { bool found = false; foreach (ILayer mapLayer in map.Layers) { if (String.Equals(mapLayer.LayerName, requestLayer, StringComparison.InvariantCultureIgnoreCase)) { found = true; if (!(mapLayer is ICanQueryLayer)) continue; ICanQueryLayer queryLayer = mapLayer as ICanQueryLayer; if (queryLayer.IsQueryEnabled) { Single queryBoxMinX = x - (_pixelSensitivity); Single queryBoxMinY = y - (_pixelSensitivity); Single queryBoxMaxX = x + (_pixelSensitivity); Single queryBoxMaxY = y + (_pixelSensitivity); SharpMap.Geometries.Point minXY = map.ImageToWorld(new System.Drawing.PointF(queryBoxMinX, queryBoxMinY)); SharpMap.Geometries.Point maxXY = map.ImageToWorld(new System.Drawing.PointF(queryBoxMaxX, queryBoxMaxY)); BoundingBox queryBox = new BoundingBox(minXY, maxXY); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); queryLayer.ExecuteIntersectionQuery(queryBox, fds); if (_intersectDelegate != null) { fds.Tables[0] = _intersectDelegate(fds.Tables[0], queryBox); } if (fds.Tables.Count == 0) { vstr = vstr + "\nSearch returned no results on layer: " + requestLayer; } else { if (fds.Tables[0].Rows.Count == 0) { vstr = vstr + "\nSearch returned no results on layer: " + requestLayer + " "; } else { //filter the rows with the CQLFilter if one is provided if (cqlFilter != null) { for (int i = fds.Tables[0].Rows.Count - 1; i >= 0; i--) { if (!CQLFilter((SharpMap.Data.FeatureDataRow)fds.Tables[0].Rows[i], cqlFilter)) { fds.Tables[0].Rows.RemoveAt(i); } } } //if featurecount < fds...count, select smallest bbox, because most likely to be clicked vstr = vstr + "\n Layer: '" + requestLayer + "'\n Featureinfo:\n"; int[] keys = new int[fds.Tables[0].Rows.Count]; double[] area = new double[fds.Tables[0].Rows.Count]; for (int l = 0; l < fds.Tables[0].Rows.Count; l++) { SharpMap.Data.FeatureDataRow fdr = fds.Tables[0].Rows[l] as SharpMap.Data.FeatureDataRow; area[l] = fdr.Geometry.GetBoundingBox().GetArea(); keys[l] = l; } Array.Sort(area, keys); if (fds.Tables[0].Rows.Count < featureCount) { featureCount = fds.Tables[0].Rows.Count; } for (int k = 0; k < featureCount; k++) { for (int j = 0; j < fds.Tables[0].Rows[keys[k]].ItemArray.Length; j++) { vstr = vstr + " '" + fds.Tables[0].Rows[keys[k]].ItemArray[j].ToString() + "'"; } if ((k + 1) < featureCount) vstr = vstr + ",\n"; } } } } } } if (found == false) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + requestLayer + "'"); } } return vstr; }
public void TestExecuteIntersectionQueryAllHints() { SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(); sq.NoLockHint = true; sq.ForceSeekHint = true; sq.ForceIndex = "IX_roads_ugl_GEOM"; SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(), ds); Assert.AreEqual(100, ds.Tables[0].Rows.Count); }
/// <summary> /// Gets the features in view. /// </summary> /// <param name="bbox">The bbox.</param> /// <param name="ds">The ds.</param> public void GetFeaturesInView(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds) { ExecuteIntersectionQuery(bbox, ds); }
private void mapImage_MapQueriedDataSet(SharpMap.Data.FeatureDataSet data) { dataGridView1.DataSource = data as System.Data.DataSet; }
/// <summary> /// Gets FeatureInfo as GeoJSON /// </summary> /// <param name="strBBOX">string representation of a boundingbox</param> /// <returns>GeoJSON string with featureinfo results</returns> public static string CreateFeatureInfoGeoJSON(SharpMap.Map map, string[] requestedLayers, Single x, Single y, int featureCount, string cqlFilter) { List<SharpMap.Converters.GeoJSON.GeoJSON> items = new List<SharpMap.Converters.GeoJSON.GeoJSON>(); foreach (string requestLayer in requestedLayers) { bool found = false; foreach (ILayer mapLayer in map.Layers) { if (String.Equals(mapLayer.LayerName, requestLayer, StringComparison.InvariantCultureIgnoreCase)) { found = true; if (!(mapLayer is ICanQueryLayer)) continue; ICanQueryLayer queryLayer = mapLayer as ICanQueryLayer; if (queryLayer.IsQueryEnabled) { Single queryBoxMinX = x - (_pixelSensitivity); Single queryBoxMinY = y - (_pixelSensitivity); Single queryBoxMaxX = x + (_pixelSensitivity); Single queryBoxMaxY = y + (_pixelSensitivity); SharpMap.Geometries.Point minXY = map.ImageToWorld(new System.Drawing.PointF(queryBoxMinX, queryBoxMinY)); SharpMap.Geometries.Point maxXY = map.ImageToWorld(new System.Drawing.PointF(queryBoxMaxX, queryBoxMaxY)); BoundingBox queryBox = new BoundingBox(minXY, maxXY); SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); queryLayer.ExecuteIntersectionQuery(queryBox, fds); // if (_intersectDelegate != null) { fds.Tables[0] = _intersectDelegate(fds.Tables[0], queryBox); } //filter the rows with the CQLFilter if one is provided if (cqlFilter != null) { for (int i = fds.Tables[0].Rows.Count-1; i >=0 ; i--) { if (!CQLFilter((SharpMap.Data.FeatureDataRow)fds.Tables[0].Rows[i], cqlFilter)) { fds.Tables[0].Rows.RemoveAt(i); } } } IEnumerable<SharpMap.Converters.GeoJSON.GeoJSON> data = SharpMap.Converters.GeoJSON.GeoJSONHelper.GetData(fds); #if DotSpatialProjections throw new NotImplementedException(); #else // Reproject geometries if needed IMathTransform transform = null; if (queryLayer is VectorLayer) { ICoordinateTransformation transformation = (queryLayer as VectorLayer).CoordinateTransformation; transform = transformation == null ? null : transformation.MathTransform; } if (transform != null) { data = data.Select(d => { Geometry converted = GeometryTransform.TransformGeometry(d.Geometry, transform); d.SetGeometry(converted); return d; }); } #endif items.AddRange(data); } } } if (found == false) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, "Unknown layer '" + requestLayer + "'"); } } StringWriter writer = new StringWriter(); SharpMap.Converters.GeoJSON.GeoJSONWriter.Write(items, writer); return writer.ToString(); }
private void Form1_Shown(object sender, EventArgs e) { SplashScreen.SplashScreen.SetStatus("Abriendo ventana de informacion de capas de tiempo real"); RealtimeInfo = new ElementInformation(this); RealtimeInfo.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockBottom;//.Document;// WeifenLuo.WinFormsUI.Docking.DockState.Float; RealtimeInfo.Text = "EVENTOS"; RealtimeInfo.Name = "Eventos"; RealtimeInfo.TabText = "Eventos"; RealtimeInfo.Text = "Eventos"; RealtimeInfo.CloseButtonVisible = false; RealtimeInfo.CloseButton = false; /* if (this.dockPanel.DocumentStyle == WeifenLuo.WinFormsUI.Docking.DocumentStyle.SystemMdi) { RealtimeInfo.MdiParent = this; RealtimeInfo.Show(); } else { RealtimeInfo.Show(dockPanel); } nCount++;*/ SplashScreen.SplashScreen.SetStatus("Abriendo Mapa"); frmMap = new MapForm(this); frmMap.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; frmMap.Text = "Mapa"; nCount++; /*reportForm = new ReportForm(this); reportForm.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; reportForm.Text = "Reporte"; nCount++;*/ SplashScreen.SplashScreen.SetStatus("Generando eventos..."); //System.Windows.Forms.Application.DoEvents(); eventosFrm = new Eventos(this); eventosFrm.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockBottom; eventosFrm.CloseButtonVisible = false; eventosFrm.CloseButton = false; eventosFrm.Text = "Eventos"; SplashScreen.SplashScreen.SetStatus("Abriendo vista general"); //System.Windows.Forms.Application.DoEvents(); Overviewmap = new OverviewMap(this); Overviewmap.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Float; Overviewmap.Text = "MAPA"; SplashScreen.SplashScreen.SetStatus("Abriendo ventana de selección"); //System.Windows.Forms.Application.DoEvents(); elementInfo = new ElementInformation(this); elementInfo.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockBottom; elementInfo.Text = "INFORMACION"; elementInfo.CloseButtonVisible = false; elementInfo.CloseButton = false; //System.Windows.Forms.Application.DoEvents(); SplashScreen.SplashScreen.CloseForm(); string configFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory), "dock.xml"); if (!System.IO.File.Exists(configFile)) { if (this.dockPanel.DocumentStyle == WeifenLuo.WinFormsUI.Docking.DocumentStyle.SystemMdi) { frmMap.MdiParent = this; frmMap.Show(); /*reportForm.MdiParent = this; reportForm.Show();*/ } else { frmMap.Show(dockPanel); //reportForm.Show(dockPanel); } eventosFrm.Show(dockPanel); Overviewmap.Show(dockPanel/*dockPanel.DockWindows[WeifenLuo.WinFormsUI.Docking.DockState.DockBottom]*/); elementInfo.Show(dockPanel); RealtimeInfo.Show(dockPanel); } else { dockPanel.LoadFromXml(configFile, m_deserializeDockContent); } System.Collections.Generic.Dictionary<string, SharpMap.Data.Providers.IProvider> providers = IntelliTrack.Service.Common.Singleton<IntelliTrack.Client.Application.Imaging.ComplexMap>.Instance.GetRealTimeLayerProviders(); foreach (System.Collections.Generic.KeyValuePair<string, SharpMap.Data.Providers.IProvider> pair in providers) { SharpMap.Data.FeatureDataSet fds = new SharpMap.Data.FeatureDataSet(); pair.Value.ExecuteIntersectionQuery(pair.Value.GetExtents(), fds); fds.Tables[0].TableName = pair.Key; RealtimeInfo.SetData(fds.Tables[0]); ((SharpMap.Data.Providers.MemoryDataProviderBase)pair.Value).OnDataUpdated += new SharpMap.Data.Providers.MemoryDataProviderBase.DataUpdated(Form1_OnDataUpdated); } IntelliTrack.Service.Common.Singleton<IntelliTrack.Client.Application.Imaging.ComplexMap>.Instance.StartTimer(); // reportForm = new ReportForm(this, new IntelliTrack.Client.Application.Reportes.Reporte1()); // reportForm.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; // reportForm.Text = "Reporte"; nCount++; // reportForm.Show(dockPanel); reporteRegadores = new ReportForm(this, new IntelliTrack.Client.Application.Reportes.Regadores()); reporteRegadores.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; reporteRegadores.Text = "Reporte de Regadores"; nCount++; reporteRegadores.Show(dockPanel); rawDataForm = new frmRawData(this); rawDataForm.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Document; rawDataForm.Text = "Información obtenida"; nCount++; rawDataForm.Show(dockPanel); frmMap.Activate(); //Aca voy a activar o desactivar los items del menu, en funcion de la seguridad elementInfo.Hide(); QuitarControlesAForms(); }
/// <summary> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(System.Drawing.Graphics g, Map map) { if (this.Style.Enabled && this.Style.MaxVisible >= map.Zoom && this.Style.MinVisible < map.Zoom) { if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); g.TextRenderingHint = this.TextRenderingHint; g.SmoothingMode = this.SmoothingMode; SharpMap.Geometries.BoundingBox envelope = map.Envelope; //View to render if (this.CoordinateTransformation != null) envelope = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformBox(envelope, this.CoordinateTransformation.MathTransform.Inverse()); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); this.DataSource.Open(); this.DataSource.ExecuteIntersectionQuery(envelope, ds); this.DataSource.Close(); if (ds.Tables.Count == 0) { base.Render(g,map); return; } SharpMap.Data.FeatureDataTable features = (SharpMap.Data.FeatureDataTable)ds.Tables[0]; //Initialize label collection List<Rendering.Label> labels = new List<SharpMap.Rendering.Label>(); //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection //Render labels for (int i = 0; i < features.Count; i++) { SharpMap.Data.FeatureDataRow feature = features[i]; if (this.CoordinateTransformation != null) features[i].Geometry = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(features[i].Geometry, this.CoordinateTransformation.MathTransform); SharpMap.Styles.LabelStyle style = null; if (this.Theme != null) //If thematics is enabled, lets override the style style = this.Theme.GetStyle(feature) as SharpMap.Styles.LabelStyle; else style = this.Style; float rotation = 0; if (this.RotationColumn != null && this.RotationColumn != "") float.TryParse(feature[this.RotationColumn].ToString(), System.Globalization.NumberStyles.Any,SharpMap.Map.numberFormat_EnUS, out rotation); string text; if (_getLabelMethod != null) text = _getLabelMethod(feature); else text = feature[this.LabelColumn].ToString(); if (text != null && text != String.Empty) { if (feature.Geometry is SharpMap.Geometries.GeometryCollection) { if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All) { foreach (SharpMap.Geometries.Geometry geom in (feature.Geometry as Geometries.GeometryCollection)) { SharpMap.Rendering.Label lbl = CreateLabel(geom, text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter) { SharpMap.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First) { if ((feature.Geometry as Geometries.GeometryCollection).Collection.Count > 0) { SharpMap.Rendering.Label lbl = CreateLabel((feature.Geometry as Geometries.GeometryCollection).Collection[0], text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest) { Geometries.GeometryCollection coll = (feature.Geometry as Geometries.GeometryCollection); if (coll.NumGeometries > 0) { double largestVal = 0; int idxOfLargest = 0; for (int j = 0; j < coll.NumGeometries; j++) { SharpMap.Geometries.Geometry geom = coll.Geometry(j); if (geom is Geometries.LineString && ((Geometries.LineString)geom).Length > largestVal) { largestVal = ((Geometries.LineString)geom).Length; idxOfLargest = j; } if (geom is Geometries.MultiLineString && ((Geometries.MultiLineString)geom).Length > largestVal) { largestVal = ((Geometries.LineString)geom).Length; idxOfLargest = j; } if (geom is Geometries.Polygon && ((Geometries.Polygon)geom).Area > largestVal) { largestVal = ((Geometries.Polygon)geom).Area; idxOfLargest = j; } if (geom is Geometries.MultiPolygon && ((Geometries.MultiPolygon)geom).Area > largestVal) { largestVal = ((Geometries.MultiPolygon)geom).Area; idxOfLargest = j; } } SharpMap.Rendering.Label lbl = CreateLabel(coll.Geometry(idxOfLargest), text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } } else { SharpMap.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } } if (labels.Count > 0) //We have labels to render... { if (this.Style.CollisionDetection && this._LabelFilter!=null) this._LabelFilter(labels); for (int i = 0; i < labels.Count;i++ ) SharpMap.Rendering.VectorRenderer.DrawLabel(g, labels[i].LabelPoint, labels[i].Style.Offset, labels[i].Style.Font, labels[i].Style.ForeColor, labels[i].Style.BackColor, Style.Halo, labels[i].Rotation, labels[i].Text, map); } labels = null; } base.Render(g, map); }
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(); } }
public void TestExecuteIntersectionQuery() { SharpMap.Data.Providers.SqlServer2008 sq = GetTestProvider(); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); sq.ExecuteIntersectionQuery(GetTestEnvelope(), ds); Assert.AreEqual(100, ds.Tables[0].Rows.Count); }
/// <summary> /// Renders the layer to a graphics object /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(System.Drawing.Graphics g, Map map) { if (map.Center == null) throw (new ApplicationException("Cannot render map. View center not specified")); g.SmoothingMode = this.SmoothingMode; SharpMap.Geometries.BoundingBox envelope = map.Envelope; //View to render if (this.CoordinateTransformation != null) envelope = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformBox(envelope, this.CoordinateTransformation.MathTransform.Inverse()); //List<SharpMap.Geometries.Geometry> features = this.DataSource.GetGeometriesInView(map.Envelope); if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); //If thematics is enabled, we use a slighty different rendering approach if (this.Theme != null) { SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); this.DataSource.Open(); this.DataSource.ExecuteIntersectionQuery(envelope, ds); this.DataSource.Close(); SharpMap.Data.FeatureDataTable features = (SharpMap.Data.FeatureDataTable)ds.Tables[0]; if (this.CoordinateTransformation != null) for (int i = 0; i < features.Count; i++) features[i].Geometry = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(features[i].Geometry, this.CoordinateTransformation.MathTransform); //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (Style.EnableOutline) { //foreach (SharpMap.Geometries.Geometry feature in features) for (int i = 0; i < features.Count; i++) { SharpMap.Data.FeatureDataRow feature = features[i]; //Draw background of all line-outlines first if (feature.Geometry is SharpMap.Geometries.LineString) { SharpMap.Styles.VectorStyle outlinestyle1 = this.Theme.GetStyle(feature) as SharpMap.Styles.VectorStyle; if (outlinestyle1.Enabled && outlinestyle1.EnableOutline) SharpMap.Rendering.VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlinestyle1.Outline, map); } else if (feature.Geometry is SharpMap.Geometries.MultiLineString) { SharpMap.Styles.VectorStyle outlinestyle2 = this.Theme.GetStyle(feature) as SharpMap.Styles.VectorStyle; if (outlinestyle2.Enabled && outlinestyle2.EnableOutline) SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlinestyle2.Outline, map); } } } for (int i = 0; i < features.Count; i++) { SharpMap.Data.FeatureDataRow feature = features[i]; SharpMap.Styles.VectorStyle style = this.Theme.GetStyle(feature) as SharpMap.Styles.VectorStyle; RenderGeometry(g, map, feature.Geometry, style); } } else { this.DataSource.Open(); List<SharpMap.Geometries.Geometry> geoms = this.DataSource.GetGeometriesInView(envelope); this.DataSource.Close(); if (this.CoordinateTransformation != null) for (int i = 0; i < geoms.Count; i++) geoms[i] = SharpMap.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(geoms[i], this.CoordinateTransformation.MathTransform); //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (this.Style.EnableOutline) { foreach (SharpMap.Geometries.Geometry geom in geoms) { if (geom != null) { //Draw background of all line-outlines first switch (geom.GetType().FullName) { case "SharpMap.Geometries.LineString": SharpMap.Rendering.VectorRenderer.DrawLineString(g, geom as LineString, this.Style.Outline, map); break; case "SharpMap.Geometries.MultiLineString": SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, geom as MultiLineString, this.Style.Outline, map); break; default: break; } } } } for (int i = 0; i < geoms.Count; i++) { if (geoms[i] != null) RenderGeometry(g, map, geoms[i], this.Style); } } base.Render(g, map); }
static AppEngine() { _featureData = new SharpMap.Data.FeatureDataSet(); }
public SharpMap.Data.FeatureDataRow FindGeoNearPoint(SharpMap.Geometries.Point pos, double amountGrow, ref double DistanceToSelected) { SharpMap.Geometries.BoundingBox bbox = pos.GetBoundingBox().Grow(amountGrow); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); DataSource.ExecuteIntersectionQuery(bbox, ds); System.Data.DataTable tbl = ds.Tables[0] as SharpMap.Data.FeatureDataTable; GisSharpBlog.NetTopologySuite.IO.WKTReader reader = new GisSharpBlog.NetTopologySuite.IO.WKTReader(); GeoAPI.Geometries.IGeometry point = reader.Read(pos.ToString()); if (tbl.Rows.Count == 0) return null; double distance = point.Distance(reader.Read((tbl.Rows[0] as SharpMap.Data.FeatureDataRow).Geometry.ToString())); SharpMap.Data.FeatureDataRow selectedFeature = tbl.Rows[0] as SharpMap.Data.FeatureDataRow; if (tbl.Rows.Count > 1) for (int i = 1; i < tbl.Rows.Count; i++) { GeoAPI.Geometries.IGeometry line = reader.Read((tbl.Rows[i] as SharpMap.Data.FeatureDataRow).Geometry.ToString()); if (point.Distance(line) < distance) { distance = point.Distance(line); selectedFeature = tbl.Rows[i] as SharpMap.Data.FeatureDataRow; } } DistanceToSelected = distance; return selectedFeature; }
public static SharpMap.Map InitializeMap(float angle) { var dataSource = new SharpMap.Data.Providers.ShapeFile( string.Format("{0}/roads.shp", ShapefileSample.PathOsm), true); var fds = new SharpMap.Data.FeatureDataSet(); dataSource.Open(); dataSource.ExecuteIntersectionQuery(dataSource.GetExtents(), fds); dataSource.Close(); var gfp = new SharpMap.Data.Providers.GeometryFeatureProvider(fds.Tables[0]); var vl = new SharpMap.Layers.VectorLayer("roads", gfp) { CoordinateTransformation = LayerTools.Dhdn2ToWgs84 }; var ll = new SharpMap.Layers.LabelLayer("labels") { DataSource = gfp, CoordinateTransformation = LayerTools.Dhdn2ToWgs84, LabelColumn = "name", MultipartGeometryBehaviour = SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest, }; ll.Style.Halo = new System.Drawing.Pen(System.Drawing.Color.Red); //ll.Style.IgnoreLength = true; var map = new SharpMap.Map(); map.Layers.Add(vl); map.Layers.Add(ll); map.Layers.Add(vl); map.ZoomToExtents(); return map; }