public void ShowMapWithPointLayerBasedOnFeatureDataTable() { var table = new FeatureDataTable(); table.Columns.Add("X", typeof(double)); table.Columns.Add("Y", typeof(double)); table.Columns.Add("Category", typeof(string)); DataRow row = table.NewRow(); table.Rows.Add(row); row.ItemArray = new object[] { 100000, 400000, "testCategory" }; row = table.NewRow(); table.Rows.Add(row); row.ItemArray = new object[] { 200000, 400000, "TestCategory" }; var dataTablePoint = new DataTablePoint(table, "Category", "X", "Y"); var vectorLayer = new VectorLayer("test", dataTablePoint); vectorLayer.Theme =ThemeFactory.CreateSingleFeatureTheme(vectorLayer.Style.GeometryType, Color.Blue, 10); var map = new Map { Name = "testmap" }; map.Layers.Add(vectorLayer); map.Center = new Coordinate(150000, 400000); map.Zoom = 200000; //map.ZoomToExtents(); //map.ZoomToBox(map.Envelope); MapTestHelper.Show(map); }
/// <summary> /// little util wich just adds one vector layer to the map and assigns it a random theme. /// </summary> /// <param name="context"></param> /// <param name="m"></param> public static void SetupMap(HttpContext context, Map m) { var l = new VectorLayer( "Countries", new ShapeFile(context.Server.MapPath(ConfigurationManager.AppSettings["shpfilePath"]))); l.Style = RandomStyle.RandomVectorStyleNoSymbols(); l.Theme = new CustomTheme<IVectorStyle>( delegate { return RandomStyle.RandomVectorStyleNoSymbols(); }); m.Layers.Add(l); FeatureDataTable labelData = new FeatureDataTable(); labelData.Columns.Add("Name", typeof (string)); FeatureDataRow r = labelData.NewRow(); r["Name"] = "My Lair"; r.Geometry = new Point(5, 5); labelData.AddRow(r); LabelLayer labelLayer = new LabelLayer("labelLayer") { DataSource = new GeometryFeatureProvider(labelData), Enabled = true, LabelColumn = "Name", Style = new LabelStyle { BackColor = new SolidBrush(Color.Black), ForeColor = Color.White, Halo = new Pen(Color.Yellow, 0.1F), CollisionDetection = false, Font = new Font("Arial", 10, GraphicsUnit.Point) } }; m.Layers.Add(labelLayer); }
public void GetSetAttributesViaIFeature() { var featureTable = new FeatureDataTable(); featureTable.Columns.Add("name", typeof (string)); featureTable.Columns.Add("attribute1", typeof(int)); var feature1 = featureTable.NewRow(); feature1.Geometry = new Point(0, 0); feature1["name"] = "feature1"; feature1["attribute1"] = 1; featureTable.Rows.Add(feature1); // now access it using IFeature iterfaces IFeature f1 = feature1; f1.Attributes.Count .Should().Be.EqualTo(2); f1.Attributes.Keys .Should().Have.SameSequenceAs(new[] {"name", "attribute1"}); f1.Attributes["name"] .Should().Be.EqualTo("feature1"); f1.Attributes["attribute1"] .Should().Be.EqualTo(1); f1.Attributes[0] .Should().Be.EqualTo("feature1"); f1.Attributes[1] .Should().Be.EqualTo(1); }
public void AddedRowChangesRowState() { FeatureDataTable table = new FeatureDataTable(); FeatureDataRow row = table.NewRow(); table.AddRow(row); Assert.AreEqual(DataRowState.Added, row.RowState); }
/// <summary> /// reloads the data /// </summary> public void Reload() { using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString)) { string strSQL = "Select * FROM " + this.Table; 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) { m_fdt = new FeatureDataTable(ds2.Tables[0]); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) m_fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (System.Data.DataRow dr in ds2.Tables[0].Rows) { SharpMap.Data.FeatureDataRow fdr = m_fdt.NewRow(); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) fdr[col.ColumnName] = dr[col]; SharpMap.Geometries.Geometry geom = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr[this.GeometryColumn]); fdr.Geometry = geom; m_fdt.AddRow(fdr); } } } } }
public void AcceptChangesAppearAsUnchanged() { FeatureDataTable table = new FeatureDataTable(); FeatureDataRow row = table.NewRow(); table.AddRow(row); table.AcceptChanges(); Assert.AreEqual(DataRowState.Unchanged, row.RowState); }
public void AddedRowAppearsAsChange() { FeatureDataTable table = new FeatureDataTable(); FeatureDataRow row = table.NewRow(); table.AddRow(row); FeatureDataTable changes = table.GetChanges(); Assert.AreEqual(1, changes.FeatureCount); }
public void AddedRowIncreasesRowCount() { FeatureDataTable table = new FeatureDataTable(); FeatureDataRow row = table.NewRow(); table.AddRow(row); Assert.AreEqual(1, table.Rows.Count); Assert.AreEqual(1, table.FeatureCount); }
public void AcceptChangesReturnsNullChangesTable() { FeatureDataTable table = new FeatureDataTable(); FeatureDataRow row = table.NewRow(); table.AddRow(row); table.AcceptChanges(); FeatureDataTable changes = table.GetChanges(); Assert.IsNull(changes); }
public void NewRowReturnsDetachedFeatureDataRow() { FeatureDataTable table = new FeatureDataTable(); FeatureDataRow row = table.NewRow(); Assert.IsNotNull(row); Assert.AreEqual(0, table.Rows.Count); Assert.AreEqual(DataRowState.Detached, row.RowState); Assert.AreSame(table, row.Table); }
/// <summary> /// Initializes a new instance of the <see cref="GeometryProvider"/> /// </summary> /// <param name="geometries">Set of geometries that this datasource should contain</param> public GeometryFeatureProvider(Collection<Geometry> geometries) { _features = new FeatureDataTable(); foreach (Geometry geom in geometries) { FeatureDataRow fdr = _features.NewRow(); fdr.Geometry = geom; _features.AddRow(fdr); } }
/// <summary> /// Initializes a new instance of the <see cref="GeometryProvider"/> /// </summary> /// <param name="geometries">Set of geometries that this datasource should contain</param> public GeometryFeatureProvider(IEnumerable<IGeometry> geometries) { _features = new FeatureDataTable(); foreach (var geom in geometries) { var fdr = _features.NewRow(); fdr.Geometry = geom; _features.AddRow(fdr); } _features.TableCleared += HandleFeaturesCleared; }
public void KeepColumnNamesInSync() { var table = new FeatureDataTable(); var row = table.NewRow(); table.Rows.Add(row); var accessor = new FeatureDataRowAttributeAccessor(row); // now add column and check if it is available via accessor table.Columns.Add("Name", typeof (string)); accessor.Count .Should().Be.EqualTo(1); }
public VectorLayer CreateGeometryLayer() { FeatureDataTable fdt = new FeatureDataTable(); fdt.Columns.Add(new DataColumn("Name", typeof (String))); FeatureDataRow fdr; fdr = fdt.NewRow(); fdr["Name"] = "Mayence"; fdr.Geometry = (Geometry) new Point(8.1, 50.0); fdt.AddRow(fdr); VectorLayer vLayer = new VectorLayer("GeometryProvider"); vLayer.DataSource = new GeometryFeatureProvider(fdt); vLayer.SRID = 4326; return vLayer; }
/// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="rowId"></param> /// <returns>datarow</returns> public override FeatureDataRow GetFeature(uint rowId) { using (var conn = new OleDbConnection(ConnectionString)) { var strSQL = "SELECT * FROM " + Table + " WHERE " + ObjectIdColumn + "=" + rowId.ToString(Map.NumberFormatEnUs); conn.Open(); using (var adapter = new OleDbDataAdapter(strSQL, conn)) { var ds = new DataSet(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { var fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } if (ds.Tables[0].Rows.Count > 0) { var dr = ds.Tables[0].Rows[0]; var fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) { fdr[col.Ordinal] = dr[col]; } if (dr[XColumn] != DBNull.Value && dr[YColumn] != DBNull.Value) { fdr.Geometry = Factory.CreatePoint(new Coordinate((double)dr[XColumn], (double)dr[YColumn])); } return(fdr); } return(null); } return(null); } } }
/// <summary> /// Creates a new FeatureDataSet for the layer with all features that intersect the supplied query feature geometry /// </summary> /// <param name="queryFeature"></param> /// <param name="fds"></param> public void ExecuteSpatialQuery(SqlGeometry queryFeature, GeospatialServices.Runtime.FeatureDataSet fds) { using (SqlConnection conn = new SqlConnection(ConnectionString)) { string strSQL = String.Format("SELECT * FROM {0} WHERE {1}.STIntersects(Geometry::STGeomFromText('{2}',4326)) = 1", this.Table, this.GeometryColumn, queryFeature.ToString()); using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); System.Data.DataSet ds = new System.Data.DataSet(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != this.GeometryColumn && col.ColumnName != this.GeometryColumn) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { GeospatialServices.Runtime.FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != this.GeometryColumn && col.ColumnName != this.GeometryColumn) { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = (SqlGeometry)dr[this.GeometryColumn]; fdt.AddRow(fdr); } fds.Tables.Add(fdt); } } } }
/// <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); OSGeo.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); } else { _dr[iField] = _OgrFeature.GetFieldAsString(iField); } } _dr.Geometry = this.ParseOgrGeometry(_OgrFeature.GetGeometryRef()); myDt.AddRow(_dr); } ds.Tables.Add(myDt); }
public IFeatureDataRecord GetFeatureByOid(TOid oid) { FeatureQueryExpression exp = new FeatureQueryExpression( new AllAttributesExpression(), null, null, new OidCollectionExpression(new[] { oid }), null); using (IFeatureDataReader reader = ExecuteFeatureQuery(exp)) { FeatureDataTable fdt = new FeatureDataTable <TOid>("features", OidColumn, GeometryFactory); for (int i = 0; i < reader.FieldCount; i++) { string name = reader.GetName(i); if (name != OidColumn) { fdt.Columns.Add(name, reader.GetFieldType(i)); } } foreach (IFeatureDataRecord fdr in reader) { FeatureDataRow row = fdt.NewRow(); for (int i = 0; i < reader.FieldCount; i++) { string name = reader.GetName(i); row[name] = reader[i]; } if ((fdr as SpatialDbFeatureDataReader).HasGeometry) { row.Geometry = reader.Geometry; } fdt.AddRow(row); return(row); } } return(null); }
private void Export(string colName) { ExportDirectory = Path.Combine(Path.GetDirectoryName(Provider.Filename), Path.GetFileNameWithoutExtension(Provider.Filename) + "_Export"); if (!Directory.Exists(ExportDirectory)) { Directory.CreateDirectory(ExportDirectory); } FeatureDataTable fdt = Provider.CreateNewTable(); IFeatureDataReader reader = Provider.GetReader(); while (reader.Read()) { string layerName = GenerateUniqueName(reader[colName].ToString()); using ( ShapeFileProvider export = ShapeFileProvider.Create(ExportDirectory, layerName, Provider.ShapeType, Provider.CreateNewTable(), Provider.GeometryFactory, _geometryServices.CoordinateSystemFactory)) { export.IsSpatiallyIndexed = false; export.Open(); FeatureDataRow <uint> fdr = (FeatureDataRow <uint>)fdt.NewRow(); object[] vals = new object[fdt.Columns.Count]; reader.GetValues(vals); fdr.ItemArray = vals; fdr.Geometry = reader.Geometry; export.Insert(fdr); export.Close(); } } }
public FeatureDataRow GetFeature(uint rowId, FeatureDataTable dt) { Debug.Assert(dt != null); if (DbaseFile != null) { if (_useMemoryCache) { FeatureDataRow dr2; _cacheDataTable.TryGetValue(rowId, out dr2); if (dr2 == null) { dr2 = DbaseFile.GetFeature(rowId, dt); dr2.Geometry = ReadGeometry(rowId); _cacheDataTable.Add(rowId, dr2); } FeatureDataRow drNew = dt.NewRow(); for (int i = 0; i < dr2.Table.Columns.Count; i++) { drNew[i] = dr2[i]; } drNew.Geometry = dr2.Geometry; return(drNew); } FeatureDataRow dr = DbaseFile.GetFeature(rowId, dt); dr.Geometry = ReadGeometry(rowId); if (FilterDelegate == null || FilterDelegate(dr)) { return(dr); } return(null); } throw (new ApplicationException( "An attempt was made to read DBase data from a shapefile without a valid .DBF file")); }
public VectorLayer CreateGeometryLayer() { FeatureDataTable fdt = new FeatureDataTable(); fdt.Columns.Add(new DataColumn("Name", typeof(String))); FeatureDataRow fdr; fdr = fdt.NewRow(); fdr["Name"] = "Mayence"; fdr.Geometry = (Geometry) new Point(8.1, 50.0); fdt.AddRow(fdr); VectorLayer vLayer = new VectorLayer("GeometryProvider"); vLayer.DataSource = new GeometryFeatureProvider(fdt); vLayer.SRID = 4326; return(vLayer); }
private static FeatureDataTable CreateLinealFeatureDataTable(IGeometryFactory geometryFactory) { var fdt = new FeatureDataTable <uint>("OID", geometryFactory); fdt.Columns.AddRange(new[] { new DataColumn("Length", typeof(double)), new DataColumn("Y", typeof(double)), }); for (uint i = 1; i <= 100; i++) { var row = fdt.NewRow(i); var geom = RandomLineal(geometryFactory); row.Geometry = geom; if (geom is ILineString) { row["Length"] = ((ILineString)geom).Length; } else { row["Length"] = ((IMultiLineString)geom).Length; } fdt.Rows.Add(row); } Assert.True(fdt.Rows.Count == 100); return(fdt); }
/// <summary> /// little util wich just adds one vector layer to the map and assigns it a random theme. /// </summary> /// <param name="context"></param> /// <param name="m"></param> public static void SetupMap(HttpContext context, Map m) { var l = new VectorLayer( "Countries", new ShapeFile(context.Server.MapPath(ConfigurationManager.AppSettings["shpfilePath"]))); l.Style = RandomStyle.RandomVectorStyleNoSymbols(); l.Theme = new CustomTheme <IVectorStyle>( delegate { return(RandomStyle.RandomVectorStyleNoSymbols()); }); m.Layers.Add(l); FeatureDataTable labelData = new FeatureDataTable(); labelData.Columns.Add("Name", typeof(string)); FeatureDataRow r = labelData.NewRow(); r["Name"] = "My Lair"; r.Geometry = new Point(5, 5); labelData.AddRow(r); LabelLayer labelLayer = new LabelLayer("labelLayer") { DataSource = new GeometryFeatureProvider(labelData), Enabled = true, LabelColumn = "Name", Style = new LabelStyle { BackColor = new SolidBrush(Color.Black), ForeColor = Color.White, Halo = new Pen(Color.Yellow, 0.1F), CollisionDetection = false, Font = new Font("Arial", 10, GraphicsUnit.Point) } }; m.Layers.Add(labelLayer); }
public void FixtureSetUp() { var fdt = new FeatureDataTable(); fdt.Columns.Add(new DataColumn("ID", typeof (int))); fdt.Columns.Add(new DataColumn("LABEL", typeof (string))); fdt.Columns.Add(new DataColumn("HALIGN", typeof (int))); fdt.Columns.Add(new DataColumn("VALIGN", typeof (int))); var factory = GeoAPI.GeometryServiceProvider.Instance.CreateGeometryFactory(4236); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { var fdr = fdt.NewRow(); fdr[0] = i*3 + j; fdr[1] = string.Format("Point({0}, {1})\nID {2}", i, j, i*3 + j); fdr[2] = j; fdr[3] = i; fdr.Geometry = factory.CreatePoint(new Coordinate(j*100, i*100)); fdt.AddRow(fdr); } } _featureDataTable = 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(BoundingBox bbox, FeatureDataSet ds) { List<Geometry> features = new List<Geometry>(); using (OracleConnection conn = new OracleConnection(_ConnectionString)) { //Get bounding box string string strBbox = GetBoxFilterStr(bbox); string strSQL = "SELECT g.*, g." + GeometryColumn + ".Get_WKB() AS sharpmap_tempgeometry "; strSQL += "FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strBbox; using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn)) { conn.Open(); DataSet ds2 = new DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]); foreach (DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public IList GetFeatures(GeoAPI.Geometries.IGeometry geom) { FeatureDataSet ds = new FeatureDataSet(); List <IGeometry> features = new List <IGeometry>(); using (SqlConnection conn = new SqlConnection(this.ConnectionString)) { string strGeom; if (this.TargetSRID > 0 && this.SRID > 0 && this.SRID != this.TargetSRID) { strGeom = "ST.Transform(ST.GeomFromText('" + geom.AsText() + "'," + this.TargetSRID.ToString() + ")," + this.SRID.ToString() + ")"; } else { strGeom = "ST.GeomFromText('" + geom.AsText() + "', " + this.SRID.ToString() + ")"; } string strSQL = "SELECT " + this.FeatureColumns + ", ST.AsBinary(" + this.BuildGeometryExpression() + ") As sharpmap_tempgeometry "; strSQL += "FROM ST.RelateQuery" + this.BuildSpatialQuerySuffix() + "(" + strGeom + ", 'intersects')"; 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(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.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 ds.Tables[0].Rows) { SharpMap.Data.FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.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); return(fdt); } } } return(null); }
private static FeatureDataTable createFeatureDataTable() { FeatureDataTable<Int64> fdt = new FeatureDataTable<Int64>("TestFeatureDataTable", "OID", _geometryFactory); DataColumn dc = fdt.Columns["OID"]; dc.AutoIncrementSeed = 1001; dc.AutoIncrementStep = 1; dc.AutoIncrement = true; fdt.Columns.Add("LABEL", typeof(String)); FeatureDataRow fdr = null; GeoAPI.IO.WellKnownText.IWktGeometryReader wktReader = fdt.GeometryFactory.WktReader; fdr = fdt.NewRow(); fdr.Geometry = wktReader.Read("POINT (0 0)"); fdr[1] = fdrLabel(fdr); fdt.AddRow(fdr); fdr = fdt.NewRow(); fdr.Geometry = wktReader.Read("POINT (10 20)"); fdr[1] = fdrLabel(fdr); fdt.AddRow(fdr); fdr = fdt.NewRow(); fdr.Geometry = wktReader.Read("POINT (15 7)"); fdr[1] = fdrLabel(fdr); fdt.AddRow(fdr); fdr = fdt.NewRow(); fdr.Geometry = wktReader.Read("POINT (7 -3)"); fdr[1] = fdrLabel(fdr); fdt.AddRow(fdr); return fdt; }
private static void mergeFeature(FeatureDataTable target, IFeatureDataRecord srcFeature, FeatureDataRow targetFeature, bool preserveChanges) { if (targetFeature == null) { targetFeature = target.NewRow(); setFeatureRowFromIFeatureDataRecord(srcFeature, targetFeature); target.AddRow(targetFeature); } else { if (preserveChanges && targetFeature.RowState == DataRowState.Modified) { throw new NotImplementedException("Merging updates to original features state not yet implemented."); } else { setFeatureRowFromIFeatureDataRecord(srcFeature, targetFeature); } } }
/// <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, FeatureDataSet ds) { 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 (_defintionQuery != null && _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.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.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 = new SharpMap.Geometries.Point((double)dr[this.XColumn], (double)dr[this.YColumn]); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { List <Geometry> features = new List <Geometry>(); using (SqlConnection conn = new SqlConnection(_connectionString)) { string strGeom = string.Empty; //TODO: Convert to SQL Server if (this._spatialObjectType == SqlServerSpatialObjectType.Geometry) { strGeom = "geography::STGeomFromText('" + geom.AsText() + "', #SRID#)"; } else { strGeom = "geometry::STGeomFromText('" + geom.AsText() + "', #SRID#)"; } if (SRID > 0) { strGeom = strGeom.Replace("#SRID#", SRID.ToString()); } else { strGeom = strGeom.Replace("#SRID#", "0"); } strGeom = GeometryColumn + ".STIntersects(" + strGeom + ") = 1"; string strSQL = "SELECT g.* , g." + GeometryColumn + ".STAsBinary() As sharpmap_tempgeometry FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(this.DefinitionQuery)) { strSQL += this.DefinitionQuery + " AND "; } strSQL += strGeom; using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { Data.FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
private void DoConversion(ProviderItem input, IEnumerable <ProcessorItem> processors, ProviderItem output) { using (IConfigureFeatureSource csource = (IConfigureFeatureSource)Activator.CreateInstance(input.Builder)) { IFeatureProvider psource = csource.ConstructSourceProvider(_geometryServices); Type srcOidType = GetTypeParamsOfImplementedInterface(psource.GetType(), typeof(IFeatureProvider <>))[0]; List <IProcessFeatureDataRecords> realProcessors = new List <IProcessFeatureDataRecords>(); foreach (ProcessorItem pi in processors) { realProcessors.Add((IProcessFeatureDataRecords)Activator.CreateInstance(pi.ProcessorType)); } FeatureDataRecordProcessor processChain = null; foreach (IProcessFeatureDataRecords processor in realProcessors) { processChain = Equals(processChain, null) ? processor.Processor : ((IEnumerable <IFeatureDataRecord> o, ref int i) => processor.Processor(processChain(o, ref i), ref i)); } processChain = processChain ?? new FeatureDataRecordProcessor((IEnumerable <IFeatureDataRecord> o, ref int i) => o); if (!psource.IsOpen) { psource.Open(); } FeatureQueryExpression exp = csource.ConstructSourceQueryExpression(); FeatureDataTable sourceModel = psource.CreateNewTable(); int index = sourceModel.Columns.IndexOf(sourceModel.PrimaryKey[0]); IEnumerable <IFeatureDataRecord> sourceRecords = processChain(psource.ExecuteFeatureQuery(exp), ref index); //jd: TODO: need to test what happens if the IFeatureDataRecord shape is changed by the processor chain IConvertData converter = null; /* Some Data Providers do not respect the oidType param passed in. * For instance Shapefile will always be IWritableFeatureProvider<UInt32> * so we need to make sure we can coerce OID values */ using ( IConfigureFeatureTarget ctarget = (IConfigureFeatureTarget)Activator.CreateInstance(output.Builder)) { Type oidType = csource.OidType; using (IWritableFeatureProvider ptarget = ctarget.ConstructTargetProvider(oidType, sourceModel.GeometryFactory, _geometryServices.CoordinateSystemFactory, sourceModel)) { if (!ptarget.IsOpen) { ptarget.Open(); } converter = GetConverter(csource.OidType, ctarget.OidType, sourceModel.NewRow(), index, sourceModel.GeometryFactory); Console.WriteLine("Beginning Import."); List <FeatureDataRow> features = new List <FeatureDataRow>(); int count = 0; foreach (IFeatureDataRecord fdr in sourceRecords) { try { features.Add(converter.ConvertRecord(fdr)); if (++count % 100 == 0) { ptarget.Insert(features); features.Clear(); } } catch (GeometryInvalidException ex) { Console.WriteLine("An Error Occured : " + ex.Message); continue; } } if (features.Count > 0) { ptarget.Insert(features); } count += features.Count; features = null; ptarget.Close(); Console.WriteLine(string.Format("{0} records processed", count)); ctarget.PostImport(); } } } Console.WriteLine("Finished"); }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { using (var conn = new SqlConnection(ConnectionString)) { string strGeom = _spatialObject + "::STGeomFromText('" + geom.AsText() + "', #SRID#)"; strGeom = strGeom.Replace("#SRID#", SRID > 0 ? SRID.ToString(CultureInfo.InvariantCulture) : "0"); strGeom = GeometryColumn + ".STIntersects(" + strGeom + ") = 1"; string strSql = "SELECT g.* , g." + GeometryColumn + ".STAsBinary() As sharpmap_tempgeometry FROM " + QualifiedTable + " g " + BuildTableHints() + " WHERE "; if (!String.IsNullOrEmpty(_definitionQuery)) { strSql += DefinitionQuery + " AND "; } strSql += strGeom; string extraOptions = GetExtraOptions(); if (!string.IsNullOrEmpty(extraOptions)) { strSql += " " + extraOptions; } using (var adapter = new SqlDataAdapter(strSql, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { var fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } var tmpGeom = Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"], Factory); if (tmpGeom != null && _spatialObjectType == SqlServerSpatialObjectType.Geography) { FlipXY(tmpGeom); tmpGeom.GeometryChanged(); } fdr.Geometry = tmpGeom; fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// gets realtime data from public transport in city vilnius of lithuania /// </summary> private void GetVilniusTransportData(string line) { if (_isActive) { return; } _isActive = true; //List<FeatureDataRow> newFeatures = new List<FeatureDataRow>(); FeatureDataTable fdt = VehicleDataTable(); string url = "http://www.troleibusai.lt/puslapiai/services/vehiclestate.php?type="; switch (_transportType) { case TransportType.Bus: { url += "bus"; } break; case TransportType.TrolleyBus: { url += "trolley"; } break; } if (!string.IsNullOrEmpty(line)) { url += "&line=" + line; } url += "&app=SharpMap.WinFormSamples"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); { request.Proxy = WebRequest.DefaultWebProxy; } request.Timeout = Timeout; request.ReadWriteTimeout = request.Timeout; request.Accept = "*/*"; request.KeepAlive = false; string xml = string.Empty; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader read = new StreamReader(responseStream)) { xml = read.ReadToEnd(); } } } XmlDocument doc = new XmlDocument(); { doc.LoadXml(xml); XmlNodeList devices = doc.GetElementsByTagName("Device"); foreach (XmlNode dev in devices) { if (dev.Attributes == null) { continue; } double? lat = null, lng = null; FeatureDataRow dr = fdt.NewRow(); dr["Id"] = int.Parse(dev.Attributes["ID"].InnerText); foreach (XmlElement elem in dev.ChildNodes) { // Debug.WriteLine(d.Id + "->" + elem.Name + ": " + elem.InnerText); switch (elem.Name) { case "Lat": lat = double.Parse(elem.InnerText, CultureInfo.InvariantCulture); break; case "Lng": lng = double.Parse(elem.InnerText, CultureInfo.InvariantCulture); break; case "Bearing": if (!string.IsNullOrEmpty(elem.InnerText)) { dr["Bearing"] = double.Parse(elem.InnerText, CultureInfo.InvariantCulture); } break; case "LineNum": dr["Line"] = elem.InnerText; break; case "AreaName": dr["AreaName"] = elem.InnerText; break; case "StreetName": dr["StreetName"] = elem.InnerText; break; case "TrackType": dr["TrackType"] = elem.InnerText; break; case "LastStop": dr["LastStop"] = elem.InnerText; break; case "Time": dr["Time"] = elem.InnerText; break; } } if (lat.HasValue && lng.HasValue) { dr.Geometry = new Point(lng.Value, lat.Value); fdt.Rows.Add(dr); } } } Features.Clear(); foreach (FeatureDataRow featureDataRow in fdt.Rows) { var fdr = Features.NewRow(); fdr.ItemArray = featureDataRow.ItemArray; fdr.Geometry = featureDataRow.Geometry; Features.AddRow(fdr); } Features.AcceptChanges(); _isActive = false; }
/// <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 override void ExecuteIntersectionQuery(BoundingBox bbox, FeatureDataSet ds) { using (var conn = new SqlConnection(ConnectionString)) { //Get bounding box string string strBbox = GetBoxFilterStr(bbox); string strSql = String.Format( "SELECT g.* FROM {0} g {1} WHERE ", QualifiedTable, BuildTableHints()); if (!String.IsNullOrEmpty(DefinitionQuery)) { strSql += DefinitionQuery + " AND "; } strSql += strBbox; string extraOptions = GetExtraOptions(); if (!string.IsNullOrEmpty(extraOptions)) { strSql += " " + extraOptions; } using (var adapter = new SqlDataAdapter(strSql, conn)) { conn.Open(); var ds2 = new System.Data.DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { var fdt = new FeatureDataTable(ds2.Tables[0]); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn) { fdr[col.ColumnName] = dr[col]; } } var geom = dr[GeometryColumn]; Geometry sqlGeometry = null; if (geom != null && geom != DBNull.Value) { sqlGeometry = SqlGeometryConverter.ToSharpMapGeometry((Microsoft.SqlServer.Types.SqlGeometry)geom); } fdr.Geometry = sqlGeometry; fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { using (var conn = new SqlConnection(ConnectionString)) { string strGeom = SpatialObject + "::STGeomFromText('" + geom.AsText() + "', #SRID#)"; strGeom = strGeom.Replace("#SRID#", SRID > 0 ? SRID.ToString(CultureInfo.InvariantCulture) : "0"); strGeom = GeometryColumn + ".STIntersects(" + strGeom + ") = 1"; string strSql = "SELECT g.* FROM " + QualifiedTable + " g " + BuildTableHints() + " WHERE "; if (!String.IsNullOrEmpty(DefinitionQuery)) { strSql += DefinitionQuery + " AND "; } strSql += strGeom; string extraOptions = GetExtraOptions(); if (!string.IsNullOrEmpty(extraOptions)) { strSql += " " + extraOptions; } using (var adapter = new SqlDataAdapter(strSql, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { var fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn) { fdr[col.ColumnName] = dr[col]; } } var ogeom = dr[GeometryColumn]; Geometry sqlGeometry = null; if (ogeom != null && ogeom != DBNull.Value) { sqlGeometry = SqlGeometryConverter.ToSharpMapGeometry((Microsoft.SqlServer.Types.SqlGeometry)ogeom); } fdr.Geometry = sqlGeometry; fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
private void 处理KMLToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == DialogResult.OK) { NetTopologySuite.Geometries.GeometryFactory gFactory = new GeometryFactory(); Dictionary <int, FeatureDataTable> fdtDic = new Dictionary <int, FeatureDataTable>(); XmlDocument doc = new XmlDocument(); doc.Load(ofd.FileName); XmlNode root = doc.DocumentElement; string nameUri = root.NamespaceURI; XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable); xnm.AddNamespace("pre", nameUri); XmlNodeList folderName = root.SelectNodes("pre:Document/pre:Folder/pre:Folder/pre:name", xnm); XmlNode oddNode = null; XmlNode evenNode = null; for (int i = 0; i < folderName.Count; i++) { if (folderName[i].InnerText == "odd num") { oddNode = folderName[i].ParentNode; } if (folderName[i].InnerText == "even num") { evenNode = folderName[i].ParentNode; } } XmlNodeList folders_Odd = null; XmlNodeList folders_Even = null; if (oddNode != null) { folders_Odd = oddNode.SelectNodes("pre:Folder", xnm); } if (evenNode != null) { folders_Even = evenNode.SelectNodes("pre:Folder", xnm); } if (folders_Odd != null) { for (int i = 0; i < folders_Odd.Count; i++) { FeatureDataTable srcfdt = null; string flihgtNameStr = folders_Odd[i].SelectSingleNode("pre:name", xnm).InnerText.Trim(); //寻找偶数 XmlNode sameFlightEven = null; if (folders_Even != null) { for (int j = 0; j < folders_Even.Count; j++) { XmlNode flightN = folders_Odd[i].SelectSingleNode("pre:name", xnm); string tempFlightName = flightN.InnerText.Trim(); if (tempFlightName == flihgtNameStr) { sameFlightEven = flightN.ParentNode; } } } XmlNodeList placemarks_Odd = folders_Odd[i].SelectNodes("pre:Placemark", xnm); XmlNodeList placemarks_even = null; if (sameFlightEven != null) { placemarks_even = folders_Even[i].SelectNodes("pre:Placemark", xnm); } string[] flightName = flihgtNameStr.Split(' '); int flihgtId = Convert.ToInt32(flightName[1]); //if (fdtDic.Keys.Contains(flihgtId)) //{ // srcfdt = fdtDic[flihgtId]; //} //else //{ // srcfdt = new FeatureDataTable(); // srcfdt.Columns.Add("FlightId", typeof(int)); // srcfdt.Columns.Add("Name", typeof(string)); // srcfdt.Columns.Add("OverlapCount", typeof(int)); // fdtDic.Add(flihgtId, srcfdt); //} srcfdt = new FeatureDataTable(); srcfdt.Columns.Add("FlightId", typeof(int)); srcfdt.Columns.Add("Name", typeof(string)); srcfdt.Columns.Add("OverlapCount", typeof(int)); fdtDic.Add(flihgtId, srcfdt); for (int k = 0; k < placemarks_Odd.Count; k++) { XmlNode coordinatesN_odd = placemarks_Odd[k].SelectSingleNode("pre:Polygon/pre:outerBoundaryIs/pre:LinearRing/pre:coordinates", xnm); string placemarkName_odd = placemarks_Odd[k].SelectSingleNode("pre:name", xnm).InnerText; string coordinateStr = coordinatesN_odd.InnerText.Trim(); string[] coordinateArry = coordinateStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); Coordinate[] coordinates = new Coordinate[coordinateArry.Length]; for (int j = 0; j < coordinateArry.Length; j++) { string[] xyh = coordinateArry[j].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); coordinates[j] = new Coordinate(Convert.ToDouble(xyh[0]), Convert.ToDouble(xyh[1]), Convert.ToDouble(xyh[2])); } if (coordinateArry.Length > 3) { GeoAPI.Geometries.IPolygon polygon = gFactory.CreatePolygon(coordinates); FeatureDataRow fdr = srcfdt.NewRow(); fdr["FlightId"] = flihgtId; Debug.WriteLine(flihgtId); fdr["Name"] = placemarkName_odd; fdr["OverlapCount"] = 0; fdr.Geometry = polygon; srcfdt.AddRow(fdr); } if (placemarks_even != null) { if (k >= placemarks_even.Count) { continue; } XmlNode coordinatesN_even = placemarks_even[k].SelectSingleNode("pre:Polygon/pre:outerBoundaryIs/pre:LinearRing/pre:coordinates", xnm); string placemarkName_even = placemarks_even[k].SelectSingleNode("pre:name", xnm).InnerText; string coordStr = coordinatesN_even.InnerText.Trim(); string[] coordinateA_even = coordStr.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); Coordinate[] coor = new Coordinate[coordinateA_even.Length]; for (int j = 0; j < coordinateA_even.Length; j++) { string[] xyh = coordinateA_even[j].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); coor[j] = new Coordinate(Convert.ToDouble(xyh[0]), Convert.ToDouble(xyh[1]), Convert.ToDouble(xyh[2])); } if (coor.Length > 3) { GeoAPI.Geometries.IPolygon polygon = gFactory.CreatePolygon(coor); FeatureDataRow fdr = srcfdt.NewRow(); fdr["FlightId"] = flihgtId; Debug.WriteLine(flihgtId); fdr["Name"] = placemarkName_even; fdr["OverlapCount"] = 0; fdr.Geometry = polygon; srcfdt.AddRow(fdr); } } } } } //对fdtDic中的所有航线进行旁向重叠计算 int index = 0; foreach (var item in fdtDic.Values) { overlapLR(item); if (++index >= 1) { break; } } FeatureDataTable allfdt = null;//所有的航线都放进来了 if (fdtDic.Count > 0) { foreach (FeatureDataTable item in fdtDic.Values) { if (allfdt == null) { allfdt = new FeatureDataTable(); allfdt.Columns.Add("FlightId", typeof(int)); allfdt.Columns.Add("Name", typeof(string)); allfdt.Columns.Add("OverlapCount", typeof(int)); } foreach (var r in item.Rows) { FeatureDataRow srcFdr = r as FeatureDataRow; FeatureDataRow tempfdr = allfdt.NewRow(); tempfdr["FlightId"] = srcFdr["FlightId"]; tempfdr["Name"] = srcFdr["Name"]; tempfdr["OverlapCount"] = srcFdr["OverlapCount"]; if (Convert.ToInt32(srcFdr["OverlapCount"]) > 0) { Debug.WriteLine(Convert.ToInt32(srcFdr["OverlapCount"])); } tempfdr.Geometry = srcFdr.Geometry; allfdt.Rows.Add(tempfdr); Debug.WriteLine(srcFdr["FlightId"]); Debug.WriteLine(srcFdr["Name"]); Debug.WriteLine(srcFdr["OverlapCount"]); Debug.WriteLine(tempfdr.Geometry.Area); Debug.WriteLine(tempfdr.Geometry); //if (++geolength>20) //{ // break; //} } } VectorStyle overlap0 = new VectorStyle(); overlap0.Fill = new SolidBrush(Color.FromArgb(25, Color.Green)); overlap0.Outline = new Pen(Color.Red, 1.0f); overlap0.EnableOutline = true; VectorStyle overlap2 = new VectorStyle(); overlap2.Fill = new SolidBrush(Color.FromArgb(20, Color.Yellow)); overlap2.Outline = new Pen(Color.Yellow, 1.0f); overlap2.EnableOutline = true; VectorStyle overlap3 = new VectorStyle(); overlap3.Fill = new SolidBrush(Color.FromArgb(20, Color.Pink)); overlap3.Outline = new Pen(Color.Yellow, 2.0f); overlap3.EnableOutline = true; VectorStyle overlap4 = new VectorStyle(); overlap4.Fill = new SolidBrush(Color.FromArgb(20, Color.Blue)); overlap4.Outline = new Pen(Color.Pink, 2.0f); overlap4.EnableOutline = true; VectorStyle overlap5 = new VectorStyle(); overlap5.Fill = new SolidBrush(Color.FromArgb(20, Color.Black)); overlap5.Outline = new Pen(Color.PowderBlue, 2.0f); overlap5.EnableOutline = true; VectorStyle defualtStyle = new VectorStyle(); defualtStyle.Fill = new SolidBrush(Color.FromArgb(25, Color.Green)); //overlap0.Outline = new Pen(Color.Yellow, 1.0f); overlap0.EnableOutline = true; Dictionary <int, IStyle> styles = new Dictionary <int, IStyle>(); styles.Add(0, overlap0); styles.Add(1, overlap2); styles.Add(2, overlap3); styles.Add(3, overlap4); styles.Add(4, overlap5); VectorLayer vlayer = new VectorLayer("l"); vlayer.DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(allfdt); vlayer.Theme = new UniqueValuesTheme <int>("OverlapCount", styles, defualtStyle); vlayer.Style.Fill = new SolidBrush(Color.FromArgb(30, Color.Green)); vlayer.Enabled = true; mbox.Map.Layers.Add(vlayer); mbox.Map.ZoomToExtents(); mbox.ActiveTool = MapBox.Tools.Pan; mbox.Refresh(); } } }
/// <summary> /// 计算旁向重叠 /// </summary> /// <param name="flight">包含一条航线上的所有图形属性,所有的几何图形存储位置必须是依次连续存储</param> private void overlapLR(FeatureDataTable flight) { if (flight.Rows.Count < 2) { return; } //List<FeatureDataRow> removeFeature = new List<FeatureDataRow>(); for (int i = 0; i < flight.Rows.Count - 1; i++) { if (i == 8) { break; } FeatureDataRow targetFeature = flight.Rows[i] as FeatureDataRow; Debug.Write("targetFeature"); Debug.WriteLine(targetFeature["Name"]); if (targetFeature.Geometry.Area == 0) { flight.Rows.Remove(targetFeature); i--; continue; } for (int j = i + 1; (j < flight.Rows.Count); j++) { if (targetFeature.Geometry.Area == 0) { flight.Rows.Remove(targetFeature); i--; break; } Debug.WriteLine("{0}:name {1} area {2}", "targetFeature", targetFeature["Name"], targetFeature.Geometry.Area); FeatureDataRow tempFeature = flight.Rows[j] as FeatureDataRow; if (tempFeature.Geometry.Area == 0) { j--; flight.Rows.Remove(tempFeature); continue; } Debug.WriteLine("{0}:name {1} area {2}", "tempFeature", tempFeature["Name"], tempFeature.Geometry.Area); if (targetFeature.Geometry.Intersects(tempFeature.Geometry)) { IGeometry intersection = targetFeature.Geometry.Intersection(tempFeature.Geometry);//相交部分构成新的要素 if (intersection.Area == 0) { continue; } IGeometry targetDiff = targetFeature.Geometry.Difference(tempFeature.Geometry); //几何的集合差更新当前目标要素的几何对象 IGeometry tempDiff = tempFeature.Geometry.Difference(targetFeature.Geometry); //几何的集合差更新对比要素的几何对象 #region 邻接要素去除重合部分后更新(新生成的几何可能是要素集合,如果是集合则要生成新的要素) //IGeometry tempDiff = tempFeature.Geometry.Difference(targetFeature.Geometry); { List <IGeometry> geometries = GeoCollection2GeoList(tempDiff); for (int ll = 0; ll < geometries.Count; ll++) { //if (ll == 0) //{ // tempFeature.Geometry = geometries[ll]; // continue; //} if (geometries[ll].Area > 0) { FeatureDataRow fdr = flight.NewRow(); fdr["FlightId"] = tempFeature["FlightId"]; fdr["Name"] = tempFeature["Name"].ToString() + string.Format("({0})", ll); fdr["OverlapCount"] = tempFeature["OverlapCount"]; fdr.Geometry = geometries[ll]; flight.Rows.InsertAt(fdr, (j + 1)); } } } #endregion #region 重合部分作为新要素生成出来 { List <IGeometry> geometries = GeoCollection2GeoList(intersection); for (int ll = 0; ll < geometries.Count; ll++) { if (geometries[ll].Area > 0) { FeatureDataRow fdr = flight.NewRow(); fdr["FlightId"] = targetFeature["FlightId"]; fdr["Name"] = targetFeature["Name"].ToString() + "::" + tempFeature["Name"].ToString() + string.Format("({0})", ll); int targetOverlap = 0; int tempOverlap = 0; int overlap = 1; if (int.TryParse(targetFeature["OverlapCount"].ToString(), out targetOverlap)) { overlap += targetOverlap; } if (int.TryParse(tempFeature["OverlapCount"].ToString(), out tempOverlap)) { overlap += tempOverlap; } fdr["OverlapCount"] = overlap; fdr.Geometry = geometries[ll]; flight.Rows.InsertAt(fdr, (i + 1)); } } j++; } #endregion #region 目标要素去除重合部分后更新几何(新生成的几何可能是要素集合,如果是集合则要生成新的要素) //IGeometry targetDiff = targetFeature.Geometry.Difference(tempFeature.Geometry); { List <IGeometry> geometries = GeoCollection2GeoList(targetDiff); for (int ll = 0; ll < geometries.Count; ll++) { //if (ll == 0) //{ // targetFeature.Geometry = geometries[ll]; // continue; //} if (geometries[ll].Area > 0) { FeatureDataRow fdr = flight.NewRow(); fdr["FlightId"] = targetFeature["FlightId"]; fdr["Name"] = targetFeature["Name"].ToString() + string.Format("({0})", ll); fdr["OverlapCount"] = targetFeature["OverlapCount"]; fdr.Geometry = geometries[ll]; flight.Rows.InsertAt(fdr, (i + 1)); } } } #endregion flight.Rows.Remove(targetFeature); flight.Rows.Remove(tempFeature); targetFeature = flight.Rows[i] as FeatureDataRow; j--; i--; } else { break; } } } //foreach (var item in removeFeature) //{ // flight.RemoveRow(item); //} //removeFeature.Clear(); }
public FeatureDataTable QueryFeatures(Geometry geom, double distance) { //List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>(); using (OracleConnection conn = new OracleConnection(_ConnectionString)) { string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)"; if (SRID > 0) { strGeom = strGeom.Replace("#SRID#", SRID.ToString(Map.NumberFormatEnUs)); } else { strGeom = strGeom.Replace("#SRID#", "NULL"); } strGeom = "SDO_WITHIN_DISTANCE(g." + GeometryColumn + ", " + strGeom + ", 'distance = " + distance.ToString(Map.NumberFormatEnUs) + "') = 'TRUE'"; string strSQL = "SELECT g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strGeom; using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn)) { DataSet ds = new DataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } return fdt; } else return null; } } }
public override void ExecuteIntersectionQuery(Envelope box, IFeatureCollectionSet fcs, CancellationToken? ct= null) { using (var conn = SpatiaLiteConnection(ConnectionString)) { string cols = "*"; //If using rowid as oid, we need to explicitly request it! if (String.Compare(ObjectIdColumn, "rowid", StringComparison.OrdinalIgnoreCase) == 0) cols = "rowid,*"; var strSql = "SELECT " + cols + ", AsBinary(" + GeometryColumn + ") AS sharpmap_tempgeometry "; strSql += "FROM " + Table + " WHERE "; strSql += GetBoxClause(box); if (!String.IsNullOrEmpty(_definitionQuery)) strSql += " AND " + DefinitionQuery; using (var adapter = new SQLiteDataAdapter(strSql, conn)) { var ds2 = new DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { var fdt = new FeatureDataTable(ds2.Tables[0]); foreach (DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (DataRow dr in ds2.Tables[0].Rows) { var fdr = fdt.NewRow(); foreach (DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdr[col.ColumnName] = dr[col]; if (dr["sharpmap_tempgeometry"] != DBNull.Value) fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory); fdt.AddRow(fdr); } fcs.Add(fdt); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(IGeometry geom, FeatureDataSet ds) { List <IGeometry> features = new List <IGeometry>(); using (OracleConnection conn = new OracleConnection(_ConnectionString)) { string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)"; if (this.SRID > 0) { strGeom = strGeom.Replace("#SRID#", this.SRID.ToString(Map.numberFormat_EnUS)); } else { strGeom = strGeom.Replace("#SRID#", "NULL"); } strGeom = "SDO_RELATE(g." + this.GeometryColumn + ", " + strGeom + ", 'mask=ANYINTERACT querytype=WINDOW') = 'TRUE'"; string strSQL = "SELECT g.* , g." + this.GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " + this.Table + " g WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) { strSQL += this.DefinitionQuery + " AND "; } strSQL += strGeom; using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.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 ds.Tables[0].Rows) { SharpMap.Data.FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.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 the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { using (var conn = new OracleConnection(ConnectionString)) { string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)"; if (SRID > 0) { strGeom = strGeom.Replace("#SRID#", SRID.ToString(Map.NumberFormatEnUs)); } else { strGeom = strGeom.Replace("#SRID#", "NULL"); } strGeom = "SDO_RELATE(g." + GeometryColumn + ", " + strGeom + ", 'mask=ANYINTERACT querytype=WINDOW') = 'TRUE'"; string strSQL = "SELECT g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_definitionQuery)) { strSQL += DefinitionQuery + " AND "; } strSQL += strGeom; using (var adapter = new OracleDataAdapter(strSQL, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { var fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in ds.Tables[0].Rows) { var fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"], Factory); 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(BoundingBox bbox, FeatureDataSet ds) { //List<Geometry> features = new List<Geometry>(); using (NpgsqlConnection conn = new NpgsqlConnection(_ConnectionString)) { string strBbox = "box2d('BOX3D(" + bbox.Min.X.ToString(Map.NumberFormatEnUs) + " " + bbox.Min.Y.ToString(Map.NumberFormatEnUs) + "," + bbox.Max.X.ToString(Map.NumberFormatEnUs) + " " + bbox.Max.Y.ToString(Map.NumberFormatEnUs) + ")'::box3d)"; if (SRID > 0) { strBbox = "setSRID(" + strBbox + "," + SRID.ToString(Map.NumberFormatEnUs) + ")"; } string strSQL = "SELECT *, AsBinary(\"" + GeometryColumn + "\") AS sharpmap_tempgeometry "; strSQL += "FROM " + QualifiedTable + " WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) { strSQL += DefinitionQuery + " AND "; } strSQL += "\"" + GeometryColumn + "\" && " + strBbox; #if DEBUG Debug.WriteLine(string.Format("{0}\n{1}\n", "ExecuteIntersectionQuery: executing sql:", strSQL)); #endif using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(strSQL, conn)) { conn.Open(); DataSet ds2 = new DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]); foreach (DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> protected override void OnExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { using (var conn = new OracleConnection(ConnectionString)) { string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)"; strGeom = strGeom.Replace("#SRID#", SRID > 0 ? SRID.ToString(Map.NumberFormatEnUs) : "NULL"); strGeom = "SDO_RELATE(g." + GeometryColumn + ", " + strGeom + ", 'mask=ANYINTERACT querytype=WINDOW') = 'TRUE'"; string strSql = "SELECT * FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_definitionQuery)) { strSql += DefinitionQuery + " AND "; } strSql += strGeom; using (var adapter = new OracleDataAdapter(strSql, conn)) { using (var sourceDataSet = new DataSet()) { conn.Open(); adapter.Fill(sourceDataSet); conn.Close(); if (sourceDataSet.Tables.Count > 0) { var fdt = new FeatureDataTable(sourceDataSet.Tables[0]); foreach (DataColumn col in sourceDataSet.Tables[0].Columns) { if (string.Compare(col.ColumnName, GeometryColumn, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) != 0) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in sourceDataSet.Tables[0].Rows) { var fdr = fdt.NewRow(); foreach (DataColumn col in sourceDataSet.Tables[0].Columns) { if (string.Compare(col.ColumnName, GeometryColumn, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) != 0) { fdr[col.ColumnName] = dr[col]; } } var sdoGeometry = dr[GeometryColumn] as SdoGeometry; if (sdoGeometry != null) { fdr.Geometry = sdoGeometry.AsGeometry(); } fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } } }
public FeatureDataTable QueryFeatures(Geometry geom, double distance) { //Collection<Geometries.Geometry> features = new Collection<SharpMap.Geometries.Geometry>(); using (NpgsqlConnection conn = new NpgsqlConnection(_ConnectionString)) { string strGeom = "GeomFromText('" + geom.AsText() + "')"; if (SRID > 0) { strGeom = "setSRID(" + strGeom + "," + SRID + ")"; } string strSQL = "SELECT * , AsBinary(\"" + GeometryColumn + "\") As sharpmap_tempgeometry FROM " + QualifiedTable + " WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) { strSQL += DefinitionQuery + " AND "; } strSQL += "\"" + GeometryColumn + "\" && " + "buffer(" + strGeom + "," + distance.ToString(Map.NumberFormatEnUs) + ")"; strSQL += " AND distance(\"" + GeometryColumn + "\", " + strGeom + ")<" + distance.ToString(Map.NumberFormatEnUs); using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(strSQL, conn)) { DataSet ds = new DataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } return(fdt); } else { return(null); } } } }
/// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="RowID"></param> /// <returns>datarow</returns> public FeatureDataRow GetFeature(uint RowID) { using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString)) { string strSQL = "select * from " + this.Table + " WHERE " + this.ObjectIdColumn + "=" + RowID.ToString(); using (System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, conn)) { conn.Open(); System.Data.DataSet ds = new System.Data.DataSet(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); if (ds.Tables[0].Rows.Count > 0) { System.Data.DataRow dr = ds.Tables[0].Rows[0]; SharpMap.Data.FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) fdr[col.ColumnName] = dr[col]; if (dr[this.XColumn] != DBNull.Value && dr[this.YColumn] != DBNull.Value) fdr.Geometry = new SharpMap.Geometries.Point((double)dr[this.XColumn], (double)dr[this.YColumn]); return fdr; } else return null; } else return null; } } }
internal static FeatureProvider CreateFeatureDatasource(IGeometryFactory geoFactory, Boolean includeGeometryCollections) { DataColumn nameColumn = new DataColumn("FeatureName", typeof(String)); FeatureProvider provider = new FeatureProvider(geoFactory, nameColumn); FeatureDataTable <Guid> features = new FeatureDataTable <Guid>("Oid", geoFactory); features.Columns.Add("FeatureName", typeof(String)); FeatureDataRow <Guid> row; row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "An empty point"; row.Geometry = geoFactory.WktReader.Read(EmptyPoint); features.AddRow(row); if (includeGeometryCollections) { row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A geometry collection"; row.Geometry = geoFactory.WktReader.Read(GeometryCollection); features.AddRow(row); } row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A multipolygon"; row.Geometry = geoFactory.WktReader.Read(MultiPolygon); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A linestring"; row.Geometry = geoFactory.WktReader.Read(LineString); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A multilinestring"; row.Geometry = geoFactory.WktReader.Read(MultiLineString); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A polygon"; row.Geometry = geoFactory.WktReader.Read(Polygon); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A point"; row.Geometry = geoFactory.WktReader.Read(Point); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "A multipoint"; row.Geometry = geoFactory.WktReader.Read(MultiPoint); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "An empty multipolygon"; row.Geometry = geoFactory.WktReader.Read(EmptyMultiPolygon); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "An empty multilinestring"; row.Geometry = geoFactory.WktReader.Read(EmptyMultiLineString); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "An empty multipoint"; row.Geometry = geoFactory.WktReader.Read(EmptyMultiPoint); features.AddRow(row); row = features.NewRow(Guid.NewGuid()); row["FeatureName"] = "An empty linestring"; row.Geometry = geoFactory.WktReader.Read(EmptyLineString); features.AddRow(row); provider.Insert((IEnumerable <FeatureDataRow <Guid> >)features); return(provider); }
private void ExecuteIntersectionQuery(Coordinate pt, FeatureDataSet ds) { if (CoordinateTransformation != null) { #if !DotSpatialProjections if (ReverseCoordinateTransformation != null) { pt = GeometryTransform.TransformCoordinate(pt, ReverseCoordinateTransformation.MathTransform); } else { CoordinateTransformation.MathTransform.Invert(); pt = GeometryTransform.TransformCoordinate(pt, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); } #else pt = GeometryTransform.TransformCoordinate(pt, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } //Setup resulting Table var dt = new FeatureDataTable(); dt.Columns.Add("Ordinate X", typeof(Double)); dt.Columns.Add("Ordinate Y", typeof(Double)); for (int i = 1; i <= Bands; i++) dt.Columns.Add(string.Format("Value Band {0}", i), typeof(Double)); //Get location on raster Double[] buffer = new double[1]; Int32[] bandMap = new int[Bands]; for (int i = 1; i <= Bands; i++) bandMap[i - 1] = i; var geoTransform = new GeoTransform(_gdalDataset); var imgPt = geoTransform.GroundToImage(pt); Int32 x = Convert.ToInt32(imgPt.X); Int32 y = Convert.ToInt32(imgPt.Y); //Test if raster ordinates are within bounds if (x < 0) return; if (y < 0) return; if (x >= _imageSize.Width) return; if (y >= _imageSize.Height) return; //Create new row, add ordinates and location geometry FeatureDataRow dr = dt.NewRow(); dr.Geometry = Factory.CreatePoint(pt); dr[0] = pt.X; dr[1] = pt.Y; //Add data from raster for (int i = 1; i <= Bands; i++) { Band band = _gdalDataset.GetRasterBand(i); //DataType dtype = band.DataType; CPLErr res = band.ReadRaster(x, y, 1, 1, buffer, 1, 1, 0, 0); if (res == CPLErr.CE_None) { dr[1 + i] = buffer[0]; } else { dr[1 + i] = Double.NaN; } } //Add new row to table dt.Rows.Add(dr); //Add table to dataset ds.Tables.Add(dt); }
/// <summary> /// Add a list of vector layers to the map. /// </summary> /// <param name="vectorLayers"></param> public void AddVectorLayers(List <FeatureInfo> vectorLayers) { int counter = 0; if (vectorLayers == null) { return; } vectorLayers.ForEach(layer => { VectorLayer vectorLayer = new VectorLayer("VectorLayer-" + counter); GeometryFactory factory = new GeometryFactory(); List <IGeometry> geometries = new List <IGeometry>(); FeatureDataTable featureData = new FeatureDataTable(); featureData.Columns.Add("text", typeof(String)); featureData.Columns.Add("style", typeof(MapExport.Style)); layer.features.ForEach(feature => { FeatureDataRow dataRow = featureData.NewRow(); dataRow["text"] = feature.attributes.text; dataRow["style"] = feature.attributes.style; List <GeoAPI.Geometries.Coordinate> vertices = new List <GeoAPI.Geometries.Coordinate>(); List <List <GeoAPI.Geometries.Coordinate> > holes = new List <List <GeoAPI.Geometries.Coordinate> >(); feature.coordinates.ForEach(coordinate => { double x = coordinate[0]; double y = coordinate[1]; vertices.Add((new GeoAPI.Geometries.Coordinate(x, y))); }); if (feature.holes != null) { feature.holes.ForEach(hole => { var coords = new List <Coordinate>(); hole.ForEach(coordinate => { double x = coordinate[0]; double y = coordinate[1]; coords.Add((new GeoAPI.Geometries.Coordinate(x, y))); }); holes.Add(coords); }); } bool created = false; switch (feature.type) { case "Text": case "Point": case "MultiPoint": if (vertices.Count > 0) { var point = factory.CreatePoint(new GeoAPI.Geometries.Coordinate(vertices[0])); dataRow.Geometry = point; } created = true; break; case "LineString": case "MultiLineString": var lineString = factory.CreateLineString(vertices.ToArray()); dataRow.Geometry = lineString; created = true; break; case "Polygon": var polygon = factory.CreatePolygon(vertices.ToArray()); dataRow.Geometry = polygon; created = true; break; case "MultiPolygon": ILinearRing outer = LinearRing.DefaultFactory.CreateLinearRing(vertices.ToArray()); ILinearRing[] inners = holes.Select(h => { return(LinearRing.DefaultFactory.CreateLinearRing(h.ToArray())); }).ToArray(); var multiPolygon = factory.CreatePolygon(outer, inners); dataRow.Geometry = multiPolygon; created = true; break; case "Circle": var circle = factory.CreatePoint(new GeoAPI.Geometries.Coordinate(vertices[0])); dataRow.Geometry = circle.Buffer(vertices[1][0]); created = true; break; } if (created) { featureData.AddRow(dataRow); } }); vectorLayer.DataSource = new SharpMap.Data.Providers.GeometryFeatureProvider(featureData); vectorLayer.Theme = new CustomTheme(GetFeatureStyle); map.Layers.Add(vectorLayer); LabelLayer labels = new LabelLayer("Labels"); labels.DataSource = vectorLayer.DataSource; labels.Enabled = true; labels.LabelColumn = "text"; labels.Theme = new CustomTheme(GetLabelStyle); labels.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; labels.SmoothingMode = SmoothingMode.HighQuality; labels.SRID = vectorLayer.SRID; map.Layers.Add(labels); counter++; }); }
/// <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(BoundingBox bbox, FeatureDataSet ds) { List <Geometry> features = new List <Geometry>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT " + FeatureColumns + ", ST.AsBinary(" + BuildGeometryExpression() + ") AS sharpmap_tempgeometry "; strSQL += "FROM ST.FilterQuery" + BuildSpatialQuerySuffix() + "(" + BuildEnvelope(bbox) + ")"; if (!String.IsNullOrEmpty(DefinitionQuery)) { strSQL += " WHERE " + DefinitionQuery; } if (!String.IsNullOrEmpty(OrderQuery)) { strSQL += " ORDER BY " + OrderQuery; } using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); DataSet ds2 = new DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]); foreach (DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } if (dr["sharpmap_tempgeometry"] != DBNull.Value) { fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); } fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
public FeatureDataTable QueryFeatures(Geometry geom, double distance) { //List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>(); using (SqlConnection conn = new SqlConnection(ConnectionString)) { string strGeom; if (TargetSRID > 0 && SRID > 0 && SRID != TargetSRID) { strGeom = "ST.Transform(ST.GeomFromText('" + geom.AsText() + "'," + TargetSRID.ToString() + ")," + SRID.ToString() + ")"; } else { strGeom = "ST.GeomFromText('" + geom.AsText() + "', " + SRID.ToString() + ")"; } string strSQL = "SELECT " + FeatureColumns + ", ST.AsBinary(" + BuildGeometryExpression() + ") As sharpmap_tempgeometry "; strSQL += "FROM ST.IsWithinDistanceQuery" + BuildSpatialQuerySuffix() + "(" + strGeom + ", " + distance.ToString(Map.NumberFormatEnUs) + ")"; if (!String.IsNullOrEmpty(DefinitionQuery)) { strSQL += " WHERE " + DefinitionQuery; } if (!String.IsNullOrEmpty(OrderQuery)) { strSQL += " ORDER BY " + OrderQuery; } using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { DataSet ds = new DataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && !col.ColumnName.StartsWith(GeometryColumn + "_Envelope_") && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } if (dr["sharpmap_tempgeometry"] != DBNull.Value) { fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); } fdt.AddRow(fdr); } return(fdt); } else { return(null); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { List<Geometry> features = new List<Geometry>(); using (OracleConnection conn = new OracleConnection(_ConnectionString)) { string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)"; if (SRID > 0) { strGeom = strGeom.Replace("#SRID#", SRID.ToString(Map.NumberFormatEnUs)); } else { strGeom = strGeom.Replace("#SRID#", "NULL"); } strGeom = "SDO_RELATE(g." + GeometryColumn + ", " + strGeom + ", 'mask=ANYINTERACT querytype=WINDOW') = 'TRUE'"; string strSQL = "SELECT g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strGeom; using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> protected override void OnExecuteIntersectionQuery(IGeometry geom, FeatureDataSet ds) { //List<Geometry> features = new List<Geometry>(); using (var conn = new SqlConnection(ConnectionString)) { //TODO: Convert to SQL Server string strGeom = _spatialObject + "::STGeomFromText('" + geom.AsText() + "', #SRID#)"; strGeom = strGeom.Replace("#SRID#", SRID > 0 ? SRID.ToString() : "0"); strGeom = GeometryColumn + ".STIntersects(" + strGeom + ") = 1"; string strSQL = "SELECT g.* , g." + GeometryColumn + ".STAsBinary() As sharpmap_tempgeometry FROM " + Table + " g " + BuildTableHints() + " WHERE "; if (!String.IsNullOrEmpty(_definitionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strGeom; string extraOptions = GetExtraOptions(); if (!string.IsNullOrEmpty(extraOptions)) strSQL += " " + extraOptions; using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"], Factory); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="RowID"></param> /// <returns>datarow</returns> public FeatureDataRow GetFeature(uint RowID) { using (OracleConnection conn = new OracleConnection(_ConnectionString)) { string strSQL = "select g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry from " + Table + " g WHERE " + ObjectIdColumn + "='" + RowID.ToString() + "'"; using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn)) { FeatureDataSet ds = new FeatureDataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"]); return fdr; } else return null; } else return null; } } }
/// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="rowId"></param> /// <returns>datarow</returns> public override FeatureDataRow GetFeature(uint rowId) { using (var conn = new SqlConnection(ConnectionString)) { string strSQL = "select g.* , g." + GeometryColumn + ".STAsBinary() As sharpmap_tempgeometry from " + Table + " g WHERE " + ObjectIdColumn + "=" + rowId + ""; using (var adapter = new SqlDataAdapter(strSQL, conn)) { System.Data.DataSet ds = new System.Data.DataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { var fdt = new FeatureDataTable(ds.Tables[0]); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); if(ds.Tables[0].Rows.Count>0) { System.Data.DataRow dr = ds.Tables[0].Rows[0]; FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"], Factory); return fdr; } return null; } return null; } } }
/// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="rowId"></param> /// <returns>datarow</returns> public override FeatureDataRow GetFeature(uint rowId) { using (var conn = new OleDbConnection(ConnectionString)) { var strSQL = "SELECT * FROM " + Table + " WHERE " + ObjectIdColumn + "=" + rowId.ToString(Map.NumberFormatEnUs); conn.Open(); using (var adapter = new OleDbDataAdapter(strSQL, conn)) { var ds = new DataSet(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { var fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); if (ds.Tables[0].Rows.Count > 0) { var dr = ds.Tables[0].Rows[0]; var fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) fdr[col.Ordinal] = dr[col]; if (dr[XColumn] != DBNull.Value && dr[YColumn] != DBNull.Value) fdr.Geometry = Factory.CreatePoint(new Coordinate((double) dr[XColumn], (double) dr[YColumn])); return fdr; } return null; } 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 override void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds) { //List<Geometry> features = new List<Geometry>(); using (var conn = new SqlConnection(ConnectionString)) { //Get bounding box string string strBbox = GetBoxFilterStr(bbox); //string strSQL = "SELECT g.*, g." + GeometryColumn + ".STAsBinary() AS sharpmap_tempgeometry "; string strSQL = String.Format( "SELECT g.*, g.{0}{1}.STAsBinary() AS sharpmap_tempgeometry FROM {2} g {3} WHERE ", GeometryColumn, MakeValidString, Table, BuildTableHints()); if (!String.IsNullOrEmpty(_definitionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strBbox; string extraOptions = GetExtraOptions(); if (!string.IsNullOrEmpty(extraOptions)) strSQL += " " + extraOptions; 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 != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdt.Columns.Add(col.ColumnName,col.DataType,col.Expression); foreach (System.Data.DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach(System.Data.DataColumn col in ds2.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") fdr[col.ColumnName] = dr[col]; fdr.Geometry = Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"], Factory); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
public override IFeature GetFeatureByOid(object rowId) { using (SQLiteConnection conn = SpatiaLiteConnection(ConnectionString)) { string cols = "*"; //If using rowid as oid, we need to explicitly request it! if (String.Compare(ObjectIdColumn, "rowid", StringComparison.OrdinalIgnoreCase) == 0) cols = "rowid,*"; string strSQL = "SELECT " +cols + ", AsBinary(" + GeometryColumn + ") AS sharpmap_tempgeometry FROM " + Table + " WHERE " + ObjectIdColumn + "=:POid"; using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(strSQL, conn)) { adapter.SelectCommand.Parameters.Add(new SQLiteParameter("POid", rowId)); DataSet ds = new DataSet(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) fdr[col.ColumnName] = dr[col]; if (dr["sharpmap_tempgeometry"] != DBNull.Value) fdr.Geometry = GeometryFromWKB.Parse((byte[]) dr["sharpmap_tempgeometry"], Factory); return fdr; } return null; } return null; } } }
public IList GetFeatures(IEnvelope box) { if (box == null) { throw new ArgumentNullException("box"); } using (SqlConnection conn = new SqlConnection(this._connectionString)) { string strBbox = this.GetBoxFilterStr(box); string strSQL = String.Format( "SELECT g.*, g.{0}{1}.STAsBinary() AS sharpmap_tempgeometry FROM {2} g WHERE ", //"SELECT g.*, g.{0}{1}.STAsText() AS sharpmap_tempgeometry FROM {2} g WHERE ", this.GeometryColumn, this.MakeValidString, this.Table); if (!String.IsNullOrEmpty(this.DefinitionQuery)) { strSQL += this.DefinitionQuery + " AND "; } strSQL += strBbox; Debug.WriteLine(strSQL); Stopwatch watch = new Stopwatch(); watch.Start(); try { using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); System.Data.DataSet dataset = new System.Data.DataSet(); adapter.Fill(dataset); conn.Close(); if (dataset.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(dataset.Tables[0]); foreach (DataColumn col in dataset.Tables[0].Columns) { if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in dataset.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in dataset.Tables[0].Columns) { if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); //fdr.Geometry = SharpMap.Converters.WellKnownText.GeometryFromWKT.Parse(dr["sharpmap_tempgeometry"].ToString()); fdt.AddRow(fdr); } return(fdt); } } return(null); } finally { watch.Stop(); Debug.WriteLine("Elapsed miliseconds: " + watch.ElapsedMilliseconds); } } }
/// <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 override void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds) { //List<Geometry> features = new List<Geometry>(); using (var conn = new SqlConnection(ConnectionString)) { //Get bounding box string string strBbox = GetBoxFilterStr(bbox); //string strSQL = "SELECT g.*, g." + GeometryColumn + ".STAsBinary() AS sharpmap_tempgeometry "; string strSql = String.Format( "SELECT g.*, g.{0}{1}.STAsBinary() AS sharpmap_tempgeometry FROM {2} g {3} WHERE ", GeometryColumn, MakeValidString, QualifiedTable, BuildTableHints()); if (!String.IsNullOrEmpty(_definitionQuery)) { strSql += DefinitionQuery + " AND "; } strSql += strBbox; string extraOptions = GetExtraOptions(); if (!string.IsNullOrEmpty(extraOptions)) { strSql += " " + extraOptions; } using (var adapter = new SqlDataAdapter(strSql, conn)) { conn.Open(); var ds2 = new System.Data.DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { var fdt = new FeatureDataTable(ds2.Tables[0]); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds2.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"], Factory); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
public FeatureDataTable QueryFeatures(Geometry geom, double distance) { //List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>(); using (OracleConnection conn = new OracleConnection(_ConnectionString)) { string strGeom = "MDSYS.SDO_GEOMETRY('" + geom.AsText() + "', #SRID#)"; if (SRID > 0) { strGeom = strGeom.Replace("#SRID#", SRID.ToString(Map.NumberFormatEnUs)); } else { strGeom = strGeom.Replace("#SRID#", "NULL"); } strGeom = "SDO_WITHIN_DISTANCE(g." + GeometryColumn + ", " + strGeom + ", 'distance = " + distance.ToString(Map.NumberFormatEnUs) + "') = 'TRUE'"; string strSQL = "SELECT g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_defintionQuery)) { strSQL += DefinitionQuery + " AND "; } strSQL += strGeom; using (OracleDataAdapter adapter = new OracleDataAdapter(strSQL, conn)) { DataSet ds = new DataSet(); conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds.Tables[0]); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (DataRow dr in ds.Tables[0].Rows) { FeatureDataRow fdr = fdt.NewRow(); foreach (DataColumn col in ds.Tables[0].Columns) { if (col.ColumnName != GeometryColumn && col.ColumnName != "sharpmap_tempgeometry") { fdr[col.ColumnName] = dr[col]; } } fdr.Geometry = GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); fdt.AddRow(fdr); } return(fdt); } else { return(null); } } } }