public override void ExecuteIntersectionQuery(BoundingBox box, FeatureDataSet ds) { var table = CreateTable(); table.BeginLoadData(); foreach (var kvp in Matrix) { var id = kvp.Key; if (box.Intersects(kvp.Value.EnvelopeInternal)) { var val = Matrix[kvp.Key, MatrixVector]; if (!Valid(val)) continue; var row = (FeatureDataRow) table.LoadDataRow(new object[] { id, val }, LoadOption.Upsert); var sval = Scale(val); row.Geometry = CreateCircle(kvp.Value, sval); } } table.EndLoadData(); ds.Tables.Add(table); }
/// <summary> /// Method to convert a <see cref="T:SharpMap.Data.FeatureDataSet"/> to a series of <see cref="GeoJSON"/> objects /// </summary> /// <param name="data">The feature dataset</param> /// <returns>A series of <see cref="GeoJSON"/> objects</returns> public static IEnumerable<GeoJSON> GetData(FeatureDataSet data) { if (data == null) throw new ArgumentNullException("data"); using (data) { foreach (FeatureDataTable table in data.Tables) { var columns = table.Columns; var keys = new string[columns.Count]; for (var i = 0; i < columns.Count; i++) keys[i] = columns[i].ColumnName; var rows = table.Rows; for (int i = 0; i < rows.Count; i++) { var row = (FeatureDataRow)rows[i]; var geometry = row.Geometry; var values = new Dictionary<string, object>(); for (var j = 0; j < keys.Length; j++) values.Add(keys[j], row[j]); yield return new GeoJSON(geometry, values); } } } }
/// <summary> /// Method to perform the intersection query against the data source /// </summary> /// <param name="geom">The geometry to use as filter</param> /// <param name="ds">The feature data set to store the results in</param> protected override void OnExecuteIntersectionQuery(IGeometry geom, FeatureDataSet ds) { ExecuteIntersectionQuery(geom.EnvelopeInternal, ds); //index of last added feature data table var index = ds.Tables.Count - 1; if (index < 0) return; var res = CloneTableStructure(ds.Tables[index]); res.BeginLoadData(); var fdt = ds.Tables[index]; foreach (FeatureDataRow row in fdt.Rows) { if (PreparedGeometry.Intersects(row.Geometry)) { var fdr = (FeatureDataRow)res.LoadDataRow(row.ItemArray, true); fdr.Geometry = row.Geometry; } } res.EndLoadData(); ds.Tables.RemoveAt(index); ds.Tables.Add(res); }
public void TestMap() { var m = new Map(new Size(1024, 786)) {BackColor = Color.FloralWhite}; const string samplePath = @"D:\GIS\FileGDB\samples\data\Topo.gdb"; var p = new FileGdbProvider(samplePath); foreach (var fc in p.GetFeatureClasses("\\USA")) { if (fc.StartsWith("\\USA\\T")) continue; Console.WriteLine(fc); var pUse = new FileGdbProvider(samplePath) { Table = fc }; var vl = new VectorLayer("Layer:" + fc, pUse) { SmoothingMode = SmoothingMode.HighQuality, Style = {Fill = RandomBrush(), Line = RandomPen()} }; m.Layers.Add(vl); var fds = new FeatureDataSet(); vl.ExecuteIntersectionQuery(vl.Envelope, fds); fds.Tables[0].TableName = fc; var res = fds.Tables[0].Rows[0].ItemArray; foreach (DataColumn col in fds.Tables[0].Columns) Console.Write(string.Format("{0} [{1}], ", col.ColumnName, col.DataType)); Console.WriteLine(); foreach (var item in res) Console.Write(string.Format(CultureInfo.InvariantCulture, "{0}, ", item)); Console.WriteLine(); Console.WriteLine(pUse.GetGeometryByID(1)); var r = pUse.GetFeature(1); foreach (var item in r.ItemArray) Console.Write(string.Format(CultureInfo.InvariantCulture, "{0}, ", item)); Console.WriteLine(); Console.WriteLine(); } Console.WriteLine(); p.Dispose(); m.ZoomToExtents(); var b = m.GetMap(); b.Save("fgdb-usa-states.bmp"); //var fds = new FeatureDataSet(); //lc.ExecuteIntersectionQuery(m.GetExtents().GetCentroid(), fds); //fds.Tables[0].TableName = lc.LayerName; //fds.Tables[0].WriteXml(Console.Out); }
public static IEnumerable<IFeature> DataSetToFeatures(FeatureDataSet dataSet) { var features = new Features(); foreach (FeatureDataTable table in dataSet.Tables) { foreach (FeatureDataRow row in table) { IFeature feature = features.New(); feature.Geometry = row.Geometry; foreach (DataColumn column in table.Columns) feature[column.ColumnName] = row[column.ColumnName]; features.Add(feature); } } return features; }
/// <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 (SqlConnection conn = new SqlConnection(ConnectionString)) { //Get bounding box string string strBbox = GetBoxFilterStr(bbox); string strSQL = String.Format( "SELECT g.* FROM {0} g {1} WHERE ", Table, BuildTableHints()); if (!String.IsNullOrEmpty(DefinitionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strBbox; 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) 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]; fdr.Geometry = SqlGeometryConverter.ToSharpMapGeometry((Microsoft.SqlServer.Types.SqlGeometry)dr[GeometryColumn]); fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
public override void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds) { var fdt = CreateTable(); fdt.BeginLoadData(); foreach (var relation in Matrix.Relations(RestrictId)) { var origin = relation.Key; var destin = relation.Value; var box = origin.Value.EnvelopeInternal; box.ExpandToInclude(destin.Value.EnvelopeInternal); if (!bbox.Intersects(box)) continue; var val = Matrix[origin.Key, destin.Key]; if (!Valid(val)) continue; var fdr = (FeatureDataRow)fdt.LoadDataRow(new object[] { CreateOid(origin.Key, destin.Key), val }, true); var sval = Scale(val); if (origin.Key == destin.Key) { fdr.Geometry = CreateCircle(origin.Value, sval); } else { fdr.Geometry = CreateLoad(origin.Value, destin.Value, sval); val = Matrix[destin.Key, origin.Key]; if (Valid(val)) { sval = Scale(val); fdr = (FeatureDataRow)fdt.LoadDataRow(new object[] { CreateOid(destin.Key, origin.Key), val }, true); fdr.Geometry = CreateLoad(destin.Value, origin.Value, sval); } } } fdt.EndLoadData(); ds.Tables.Add(fdt); }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom'. /// </summary> /// <param name="geom">The geometry.</param> /// <param name="ds">The <see cref="FeatureDataSet"/> to fill data into.</param> public override void ExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { //Use the spatial index to get a list of features whose boundingbox intersects bbox var objectlist = GetObjectIDsInView(geom.GetBoundingBox()); if (objectlist.Count == 0) return; var dt = DbaseFile.NewTable; var preparedGeometry = new NetTopologySuite.Geometries.Prepared.PreparedGeometryFactory() .Create(Converters.NTS.GeometryConverter.ToNTSGeometry(geom, _factory)); for (int i = 0; i < objectlist.Count; i++) { var testGeom = GetGeometryByID(objectlist[i]); var testNtsGeom = Converters.NTS.GeometryConverter.ToNTSGeometry(testGeom, _factory); if (preparedGeometry.Intersects(testNtsGeom)) { var fdr = GetFeature(objectlist[i], dt); if (fdr != null) dt.AddRow(fdr); } } if (dt.Rows.Count > 0) ds.Tables.Add(dt); }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="spatialWhere">Geometry to intersect with</param> /// <param name="fds">FeatureDataSet to fill data into</param> protected virtual void ExecuteIntersectionQueryInternal(object spatialWhere, FeatureDataSet fds) { var fdt = CreateNewTable(true); fdt.BeginLoadData(); using (var cn = CreateOpenDbConnection()) { using (var cmd = cn.CreateCommand()) { string from = null; var spatialWhereString = string.Empty; var env = spatialWhere as Envelope; if (env != null) { from = GetFrom(env, cmd); spatialWhereString = GetSpatialWhere(env, cmd); } else { var geom = spatialWhere as IGeometry; if (geom != null) { from = GetFrom(geom, cmd); spatialWhereString = GetSpatialWhere(geom, cmd); } } cmd.CommandText = FeatureColumns.GetSelectClause(from) #pragma warning disable 612,618 + (string.IsNullOrEmpty(DefinitionQuery) #pragma warning restore 612,618 ? FeatureColumns.GetWhereClause(spatialWhereString) : (" WHERE " + _definitionQuery + (string.IsNullOrEmpty(spatialWhereString) ? "" : " AND " + spatialWhereString))) + FeatureColumns.GetGroupByClause() + FeatureColumns.GetOrderByClause(); var numColumns = fdt.Columns.Count; var geomIndex = numColumns; Logger.Debug(t => t("Executing query:\n{0}", PrintCommand(cmd))); using (var dr = cmd.ExecuteReader()) { while (dr.Read()) { var data = new object[numColumns + 1]; if (dr.GetValues(data) > 0) { var loadData = new object[geomIndex]; Array.Copy(data, 0, loadData, 0, geomIndex); var row = (FeatureDataRow)fdt.LoadDataRow(loadData, true); row.Geometry = GeometryFromWKB.Parse((byte[])data[geomIndex], Factory); } } } } } fdt.EndLoadData(); fds.Tables.Add(fdt); }
/// <summary> /// Method to perform the intersection query against the data source /// </summary> /// <param name="geom">The geometry to use as filter</param> /// <param name="ds">The feature data set to store the results in</param> protected override void OnExecuteIntersectionQuery(IGeometry geom, FeatureDataSet ds) { ExecuteIntersectionQueryInternal(geom, ds); }
protected void RenderInternal(Graphics g, Map map, BoundingBox envelope, ITheme theme) { FeatureDataSet ds = new FeatureDataSet(); lock (_dataSource) { DataSource.Open(); DataSource.ExecuteIntersectionQuery(envelope, ds); DataSource.Close(); } foreach (FeatureDataTable features in ds.Tables) { if (CoordinateTransformation != null) { for (int i = 0; i < features.Count; i++) #if !DotSpatialProjections { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation. MathTransform); } } #else { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation.Source, CoordinateTransformation.Target); } #endif //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++) { FeatureDataRow feature = features[i]; VectorStyle outlineStyle = Theme.GetStyle(feature) as VectorStyle; if (outlineStyle == null) { continue; } if (!(outlineStyle.Enabled && outlineStyle.EnableOutline)) { continue; } if (!(outlineStyle.MinVisible <= map.Zoom && map.Zoom <= outlineStyle.MaxVisible)) { continue; } using (outlineStyle = outlineStyle.Clone()) { //Draw background of all line-outlines first if (feature.Geometry is LineString) { VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } else if (feature.Geometry is MultiLineString) { VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } } } } for (int i = 0; i < features.Count; i++) { FeatureDataRow feature = features[i]; VectorStyle style = Theme.GetStyle(feature) as VectorStyle; if (style == null) { continue; } if (!style.Enabled) { continue; } if (!(style.MinVisible <= map.Zoom && map.Zoom <= style.MaxVisible)) { continue; } using (var clone = style.Clone()) { RenderGeometry(g, map, feature.Geometry, clone); } } } }
public override void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { GetNonSpatialColumns(); using (var conn = GetConnection(ConnectionString)) { var strSql = "SELECT " + _columns + ", \"" + GeometryColumn + "\" AS \"_smtmp_\" "; strSql += "FROM " + Table + " WHERE "; // Attribute constraint if (!String.IsNullOrEmpty(_definitionQuery)) strSql += DefinitionQuery + " AND "; // Spatial constraint strSql += GetBoxClause(box); using (var cmd = new SQLiteCommand(strSql, conn)) { using (var reader = cmd.ExecuteReader()) { var geomIndex = reader.FieldCount - 1; var fdt = CreateTableFromReader(reader, geomIndex); var dataTransfer = new object[geomIndex]; var geoReader = new GaiaGeoReader(Factory.CoordinateSequenceFactory, Factory.PrecisionModel, _ordinates); fdt.BeginLoadData(); while (reader.Read()) { IGeometry g = null; if (!reader.IsDBNull(geomIndex)) g = geoReader.Read((byte[])reader.GetValue(geomIndex)); //No geometry, no feature! if (g == null) continue; //If not using RTree index we need to filter in code if (_spatiaLiteIndex != SpatiaLiteIndex.RTree && !box.Intersects(g.EnvelopeInternal)) continue; //Get all the attribute data var count = reader.GetValues(dataTransfer); System.Diagnostics.Debug.Assert(count == dataTransfer.Length); var fdr = (FeatureDataRow)fdt.LoadDataRow(dataTransfer, true); fdr.Geometry = g; } reader.Close(); fdt.EndLoadData(); ds.Tables.Add(fdt); } } } }
/// <summary> /// Retrieves all features within the given BoundingBox. /// </summary> /// <param name="bbox">Bounds of the region to search.</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(BoundingBox bbox, FeatureDataSet ds) { DataRow[] rows; if (Table.Rows.Count == 0) { return; } string statement = XColumn + " > " + bbox.Left.ToString(Map.NumberFormatEnUs) + " AND " + XColumn + " < " + bbox.Right.ToString(Map.NumberFormatEnUs) + " AND " + YColumn + " > " + bbox.Bottom.ToString(Map.NumberFormatEnUs) + " AND " + YColumn + " < " + bbox.Top.ToString(Map.NumberFormatEnUs); rows = Table.Select(statement); FeatureDataTable fdt = new FeatureDataTable(Table); foreach (DataColumn col in Table.Columns) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } foreach (DataRow dr in rows) { fdt.ImportRow(dr); FeatureDataRow fdr = fdt.Rows[fdt.Rows.Count - 1] as FeatureDataRow; fdr.Geometry = new Point((double) dr[XColumn], (double) dr[YColumn]); } ds.Tables.Add(fdt); }
static void Main(string[] args) { string appPath = typeof(Program).Assembly.Location.Substring(0, typeof(Program).Assembly.Location.LastIndexOf("\\")); // delete old db if (System.IO.File.Exists(string.Format(@"{0}\Data\db.sqlite", appPath))) { System.IO.File.Delete(string.Format(@"{0}\Data\db.sqlite", appPath)); } // initialize sqlite String slPath = appPath.Substring(0, appPath.LastIndexOf('\\')); slPath = slPath.Substring(0, slPath.LastIndexOf('\\')); slPath = slPath.Substring(0, slPath.LastIndexOf('\\')); slPath = slPath + "\\SpatialLite"; String path = Environment.GetEnvironmentVariable("path"); if (path == null) { path = ""; } if (!path.ToLowerInvariant().Contains(slPath.ToLowerInvariant())) { Environment.SetEnvironmentVariable("path", slPath + ";" + path); } var cn = new SQLiteConnection(string.Format(@"Data Source={0}\Data\db.sqlite;Version=3;", appPath)); cn.Open(); SQLiteCommand cm = new SQLiteCommand(String.Format("SELECT load_extension('{0}');", "libspatialite-4.dll"), cn); cm.ExecuteNonQuery(); // create geometry table cm = new SQLiteCommand( @"CREATE TABLE WorldGeom (" + @"ID INTEGER PRIMARY KEY AUTOINCREMENT, " + @"Geometry BLOB NOT NULL);", cn); cm.ExecuteNonQuery(); // create feature data table cm = new SQLiteCommand( @"CREATE TABLE WorldData (" + @"ID INTEGER PRIMARY KEY AUTOINCREMENT, " + @"ISO2 VARCHAR(2) NOT NULL, " + @"ISO3 VARCHAR(3) NOT NULL, " + @"Name TEXT NOT NULL, " + @"Region TEXT NOT NULL, " + @"Area DOUBLE NOT NULL, " + @"Pop DOUBLE NOT NULL);", cn); cm.ExecuteNonQuery(); // copy shape data to sqlite var shapeFile = appPath + @"\Data\world_countries_boundary_file_world_2002.shp"; var shp = new SharpMap.Data.Providers.ShapeFile(shapeFile); shp.Open(); FeatureDataSet ds = new FeatureDataSet(); shp.ExecuteIntersectionQuery(new SharpMap.Geometries.BoundingBox(double.MinValue, double.MinValue, double.MaxValue, double.MaxValue), ds); foreach (FeatureDataRow row in ds.Tables[0].Rows) { var bytes = SharpMap.Converters.WellKnownBinary.GeometryToWKB.Write(row.Geometry); cm = new SQLiteCommand("INSERT INTO WorldGeom (Geometry) VALUES (GeomFromWkb(@wkb, -1))", cn); cm.Parameters.Add("Geometry", DbType.Object); cm.Parameters.AddWithValue("@wkb", bytes); cm.ExecuteNonQuery(); cm = new SQLiteCommand("INSERT INTO WorldData (ISO2, ISO3, Name, Region, Area, Pop) VALUES (@iso2, @iso3, @name, @region, @area, @pop)", cn); cm.Parameters.AddWithValue("@iso2", row["ISO_2_CODE"]); cm.Parameters.AddWithValue("@iso3", row["ISO_3_CODE"]); cm.Parameters.AddWithValue("@name", row["NAME"]); cm.Parameters.AddWithValue("@region", row["REGION"]); cm.Parameters.AddWithValue("@area", row["AREA"]); cm.Parameters.AddWithValue("@pop", row["POP2005"]); cm.ExecuteNonQuery(); } shp.Close(); // create spatial index cm = new SQLiteCommand("SELECT CreateMbrCache('WorldGeom', 'Geometry');", cn); cm.ExecuteNonQuery(); }
/// <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 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> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics g, Map map) { if (Style.Enabled && Style.MaxVisible >= map.Zoom && Style.MinVisible < map.Zoom) { if (DataSource == null) { throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'")); } g.TextRenderingHint = TextRenderingHint; g.SmoothingMode = SmoothingMode; BoundingBox envelope = map.Envelope; //View to render var lineClipping = new CohenSutherlandLineClipping(envelope.Min.X, envelope.Min.Y, envelope.Max.X, envelope.Max.Y); if (CoordinateTransformation != null) { #if !DotSpatialProjections CoordinateTransformation.MathTransform.Invert(); envelope = GeometryTransform.TransformBox(envelope, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); #else envelope = GeometryTransform.TransformBox(envelope, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } FeatureDataSet ds = new FeatureDataSet(); DataSource.Open(); DataSource.ExecuteIntersectionQuery(envelope, ds); DataSource.Close(); if (ds.Tables.Count == 0) { base.Render(g, map); return; } FeatureDataTable features = ds.Tables[0]; //Initialize label collection List <BaseLabel> labels = new List <BaseLabel>(); //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection //Render labels for (int i = 0; i < features.Count; i++) { FeatureDataRow feature = features[i]; if (CoordinateTransformation != null) #if !DotSpatialProjections { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation. MathTransform); } #else { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation.Source, CoordinateTransformation.Target); } #endif LabelStyle style; if (Theme != null) //If thematics is enabled, lets override the style { style = Theme.GetStyle(feature) as LabelStyle; } else { style = Style; } float rotationStyle = style != null ? style.Rotation : 0f; float rotationColumn = 0f; if (!String.IsNullOrEmpty(RotationColumn)) { Single.TryParse(feature[RotationColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs, out rotationColumn); } float rotation = rotationStyle + rotationColumn; int priority = Priority; if (_getPriorityMethod != null) { priority = _getPriorityMethod(feature); } else if (!String.IsNullOrEmpty(PriorityColumn)) { Int32.TryParse(feature[PriorityColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs, out priority); } string text; if (_getLabelMethod != null) { text = _getLabelMethod(feature); } else { text = feature[LabelColumn].ToString(); } if (!String.IsNullOrEmpty(text)) { // for lineal geometries, try clipping to ensure proper labeling if (feature.Geometry is ILineal) { if (feature.Geometry is LineString) { feature.Geometry = lineClipping.ClipLineString(feature.Geometry as LineString); } else if (feature.Geometry is MultiLineString) { feature.Geometry = lineClipping.ClipLineString(feature.Geometry as MultiLineString); } } if (feature.Geometry is GeometryCollection) { if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All) { foreach (Geometry geom in (feature.Geometry as GeometryCollection)) { BaseLabel lbl = CreateLabel(geom, text, rotation, priority, style, map, g); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter) { BaseLabel lbl = CreateLabel(feature.Geometry, text, rotation, priority, style, map, g); if (lbl != null) { labels.Add(lbl); } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First) { if ((feature.Geometry as GeometryCollection).Collection.Count > 0) { BaseLabel lbl = CreateLabel((feature.Geometry as GeometryCollection).Collection[0], text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest) { GeometryCollection coll = (feature.Geometry as GeometryCollection); if (coll.NumGeometries > 0) { double largestVal = 0; int idxOfLargest = 0; for (int j = 0; j < coll.NumGeometries; j++) { Geometry geom = coll.Geometry(j); if (geom is LineString && ((LineString)geom).Length > largestVal) { largestVal = ((LineString)geom).Length; idxOfLargest = j; } if (geom is MultiLineString && ((MultiLineString)geom).Length > largestVal) { largestVal = ((MultiLineString)geom).Length; idxOfLargest = j; } if (geom is Polygon && ((Polygon)geom).Area > largestVal) { largestVal = ((Polygon)geom).Area; idxOfLargest = j; } if (geom is MultiPolygon && ((MultiPolygon)geom).Area > largestVal) { largestVal = ((MultiPolygon)geom).Area; idxOfLargest = j; } } BaseLabel lbl = CreateLabel(coll.Geometry(idxOfLargest), text, rotation, priority, style, map, g); if (lbl != null) { labels.Add(lbl); } } } } else { BaseLabel lbl = CreateLabel(feature.Geometry, text, rotation, priority, style, map, g); if (lbl != null) { labels.Add(lbl); } } } } if (labels.Count > 0) //We have labels to render... { if (Style.CollisionDetection && _labelFilter != null) { _labelFilter(labels); } for (int i = 0; i < labels.Count; i++) { // Don't show the label if not necessary if (!labels[i].Show) { continue; } if (labels[i] is Label) { var label = labels[i] as Label; VectorRenderer.DrawLabel(g, label.Location, label.Style.Offset, label.Style.Font, label.Style.ForeColor, label.Style.BackColor, Style.Halo, label.Rotation, label.Text, map); } else if (labels[i] is PathLabel) { var plbl = labels[i] as PathLabel; var lblStyle = plbl.Style; g.DrawString(lblStyle.Halo, new SolidBrush(lblStyle.ForeColor), plbl.Text, lblStyle.Font.FontFamily, (int)lblStyle.Font.Style, lblStyle.Font.Size, lblStyle.GetStringFormat(), lblStyle.IgnoreLength, plbl.Location); } } } } base.Render(g, map); }
public override void Handle() { string queryLayers = this.context.Request.Params["LAYERS"]; string styles = this.context.Request.Params["STYLES"]; string crs = this.context.Request.Params["CRS"]; string queryBBOX = this.context.Request.Params["BBOX"]; string queryWidth = this.context.Request.Params["WIDTH"]; string queryHeight = this.context.Request.Params["HEIGHT"]; string format = this.context.Request.Params["FORMAT"]; string transparent = this.context.Request.Params["TRANSPARENT"]; string background = this.context.Request.Params["BGCOLOR"]; if (queryLayers == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (styles == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (crs == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } if (!this.Check(String.Format("EPSG:{0}", this.map.Layers[0].SRID), crs)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (queryBBOX == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (queryWidth == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (queryHeight == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (format == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } //Set background color of map if (!this.Check("TRUE", transparent)) { if (background != null) { try { this.map.BackColor = ColorTranslator.FromHtml(background); } catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; } } else { this.map.BackColor = Color.White; } } else { this.map.BackColor = Color.Transparent; } //Parse map size int width; if (!Int32.TryParse(queryWidth, out width)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH"); return; } if (this.description.MaxWidth > 0 && width > this.description.MaxWidth) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large"); return; } int height; if (!Int32.TryParse(queryHeight, out height)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT"); return; } if (this.description.MaxHeight > 0 && height > this.description.MaxHeight) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large"); return; } this.map.Size = new Size(width, height); BoundingBox bbox = this.ParseBBOX(queryBBOX); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } this.map.PixelAspectRatio = (width / (double)height) / (bbox.Width / bbox.Height); this.map.Center = bbox.GetCentroid(); this.map.Zoom = bbox.Width; //Set layers on/off if (!String.IsNullOrEmpty(queryLayers)) //If LAYERS is empty, use default layer on/off settings { string[] layers = queryLayers.Split(new[] { ',' }); if (this.description.LayerLimit > 0) { if (layers.Length == 0 && this.map.Layers.Count > this.description.LayerLimit || layers.Length > this.description.LayerLimit) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested"); return; } } foreach (ILayer layer in this.map.Layers) { layer.Enabled = false; } foreach (string layer in layers) { ILayer lay = this.map.GetLayerByName(layer); if (lay == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, String.Format("Unknown layer '{0}'", layer)); return; } lay.Enabled = true; } } bool json = this.Check("text/json", format); if (json) { List <GeoJSON> items = new List <GeoJSON>(); //Only queryable data! IQueryable <ICanQueryLayer> collection = this.map.Layers.AsQueryable() .OfType <ICanQueryLayer>().Where(l => l.Enabled && l.IsQueryEnabled); foreach (ICanQueryLayer layer in collection) { //Query for data FeatureDataSet ds = new FeatureDataSet(); layer.ExecuteIntersectionQuery(bbox, ds); IEnumerable <GeoJSON> data = GeoJSONHelper.GetData(ds); //Filter only visible items //double f = bbox.GetArea() / (width * height); //data = data.Where(i => //{ // Geometry g = i.Geometry; // BoundingBox p = g.GetBoundingBox(); // double area = p.GetArea(); // return area == 0 || area > f; //}); //Reproject geometries if needed IMathTransform transform = null; if (layer is VectorLayer) { ICoordinateTransformation transformation = (layer 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); }); } items.AddRange(data); } StringWriter writer = new StringWriter(); GeoJSONWriter.Write(items, writer); string buffer = writer.ToString(); this.context.Response.Clear(); this.context.Response.ContentType = "text/json"; this.context.Response.BufferOutput = true; this.context.Response.Write(buffer); this.context.Response.End(); } else { //Get the image format requested ImageCodecInfo imageEncoder = this.GetEncoderInfo(format); if (imageEncoder == null) { WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter"); return; } //Render map Image img = this.map.GetMap(); //Png can't stream directy. Going through a memorystream instead MemoryStream ms = new MemoryStream(); img.Save(ms, imageEncoder, null); img.Dispose(); byte[] buffer = ms.ToArray(); this.context.Response.Clear(); this.context.Response.ContentType = imageEncoder.MimeType; this.context.Response.BufferOutput = true; this.context.Response.BinaryWrite(buffer); this.context.Response.End(); } }
/// <summary> /// Method to render this layer to the map, applying <paramref name="theme"/>. /// </summary> /// <param name="g">The graphics object</param> /// <param name="map">The map object</param> /// <param name="envelope">The envelope to render</param> /// <param name="theme">The theme to apply</param> protected void RenderInternal(Graphics g, Map map, Envelope envelope, ITheme theme) { var ds = new FeatureDataSet(); lock (_dataSource) { DataSource.Open(); DataSource.ExecuteIntersectionQuery(envelope, ds); DataSource.Close(); } foreach (FeatureDataTable features in ds.Tables) { if (CoordinateTransformation != null) { for (int i = 0; i < features.Count; i++) #if !DotSpatialProjections { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation.MathTransform, GeometryServiceProvider.Instance.CreateGeometryFactory((int)CoordinateTransformation.TargetCS.AuthorityCode)); } } #else { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation.Source, CoordinateTransformation.Target, CoordinateTransformation.TargetFactory); } #endif //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (Style.EnableOutline) { for (int i = 0; i < features.Count; i++) { var feature = features[i]; var outlineStyle = theme.GetStyle(feature) as VectorStyle; if (outlineStyle == null) { continue; } if (!(outlineStyle.Enabled && outlineStyle.EnableOutline)) { continue; } if (!(outlineStyle.MinVisible <= map.Zoom && map.Zoom <= outlineStyle.MaxVisible)) { continue; } using (outlineStyle = outlineStyle.Clone()) { if (outlineStyle != null) { //Draw background of all line-outlines first if (feature.Geometry is ILineString) { VectorRenderer.DrawLineString(g, feature.Geometry as ILineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } else if (feature.Geometry is IMultiLineString) { VectorRenderer.DrawMultiLineString(g, feature.Geometry as IMultiLineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } } } } } for (int i = 0; i < features.Count; i++) { var feature = features[i]; var style = theme.GetStyle(feature); if (style == null) { continue; } if (!style.Enabled) { continue; } if (!(style.MinVisible <= map.Zoom && map.Zoom <= style.MaxVisible)) { continue; } IStyle[] stylesToRender = GetStylesToRender(style); if (stylesToRender == null) { return; } foreach (var vstyle in stylesToRender) { if (!(vstyle is VectorStyle) || !vstyle.Enabled) { continue; } using (var clone = (vstyle as VectorStyle).Clone()) { if (clone != null) { RenderGeometry(g, map, feature.Geometry, clone); } } } } } }
/// <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); } } } }
/// <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> /// Method to render this layer to the map, applying <paramref name="theme"/>. /// </summary> /// <param name="g">The graphics object</param> /// <param name="map">The map object</param> /// <param name="envelope">The envelope to render</param> /// <param name="theme">The theme to apply</param> protected void RenderInternal(Graphics g, MapViewport map, Envelope envelope, ITheme theme) { var canvasArea = RectangleF.Empty; var combinedArea = RectangleF.Empty; var ds = new FeatureDataSet(); lock (_dataSource) { // Is datasource already open? bool wasOpen = DataSource.IsOpen; if (!wasOpen) { DataSource.Open(); } DataSource.ExecuteIntersectionQuery(envelope, ds); if (!wasOpen) { DataSource.Close(); } } double scale = map.GetMapScale((int)g.DpiX); double zoom = map.Zoom; Func <MapViewport, FeatureDataRow, IStyle> evalStyle; if (theme is IThemeEx) { evalStyle = new ThemeExEvaluator((IThemeEx)theme).GetStyle; } else { evalStyle = new ThemeEvaluator(theme).GetStyle; } foreach (FeatureDataTable features in ds.Tables) { // Transform geometries if necessary if (CoordinateTransformation != null) { for (int i = 0; i < features.Count; i++) { features[i].Geometry = ToTarget(features[i].Geometry); } } //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (Style.EnableOutline) { for (int i = 0; i < features.Count; i++) { var feature = features[i]; var outlineStyle = evalStyle(map, feature) as VectorStyle; if (outlineStyle == null) { continue; } if (!(outlineStyle.Enabled && outlineStyle.EnableOutline)) { continue; } var compare = outlineStyle.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale; if (!(outlineStyle.MinVisible <= compare && compare <= outlineStyle.MaxVisible)) { continue; } using (outlineStyle = outlineStyle.Clone()) { if (outlineStyle != null) { //Draw background of all line-outlines first if (feature.Geometry is ILineString) { canvasArea = VectorRenderer.DrawLineStringEx(g, feature.Geometry as ILineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } else if (feature.Geometry is IMultiLineString) { canvasArea = VectorRenderer.DrawMultiLineStringEx(g, feature.Geometry as IMultiLineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } combinedArea = canvasArea.ExpandToInclude(combinedArea); } } } } for (int i = 0; i < features.Count; i++) { var feature = features[i]; var style = evalStyle(map, feature); if (style == null) { continue; } if (!style.Enabled) { continue; } double compare = style.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale; if (!(style.MinVisible <= compare && compare <= style.MaxVisible)) { continue; } IEnumerable <IStyle> stylesToRender = GetStylesToRender(style); if (stylesToRender == null) { return; } foreach (var vstyle in stylesToRender) { if (!(vstyle is VectorStyle) || !vstyle.Enabled) { continue; } using (var clone = (vstyle as VectorStyle).Clone()) { if (clone != null) { canvasArea = RenderGeometryEx(g, map, feature.Geometry, clone); combinedArea = canvasArea.ExpandToInclude(combinedArea); } } } } } CanvasArea = combinedArea; }
/// <summary> /// Returns the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="fcs">FeatureCollectionSet to fill data into</param> protected override void OnExecuteIntersectionQuery(IGeometry geom, IFeatureCollectionSet fcs, CancellationToken? cancellationToken=null) { using (var conn = new OracleConnection(ConnectionString)) { var 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'"; var strSQL = "SELECT g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry FROM " + Table + " g WHERE "; if (!String.IsNullOrEmpty(_definitionQuery)) strSQL += DefinitionQuery + " AND "; strSQL += strGeom; var ds = new FeatureDataSet(); using (var adapter = new OracleDataAdapter(strSQL, conn)) { conn.Open(); adapter.Fill(ds); conn.Close(); if (ds.Tables.Count <= 0) { return; } 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); } fcs.Add(fdt); } } }
public void RenderLayer(ILabelLayer layer, Map map, Graphics g) { if (layer.Style.Enabled && layer.Style.MaxVisible >= map.Zoom && layer.Style.MinVisible < map.Zoom) { if (layer.DataSource == null) { throw (new ApplicationException("DataSource property not set on layer '" + layer.LayerName + "'")); } g.TextRenderingHint = layer.TextRenderingHint; g.SmoothingMode = layer.SmoothingMode; SharpMap.Geometries.BoundingBox envelope = map.Envelope; //View to render if (layer.CoordinateTransformation != null) { envelope = GeometryTransform.TransformBox(envelope, layer.CoordinateTransformation.MathTransform.Inverse()); } FeatureDataSet ds = new FeatureDataSet(); layer.DataSource.Open(); layer.DataSource.ExecuteIntersectionQuery(envelope, ds); layer.DataSource.Close(); if (ds.Tables.Count == 0) { //base.Render(g, map); return; } FeatureDataTable features = (FeatureDataTable)ds.Tables[0]; //Initialize label collection List <Label> labels = new List <Label>(); LabelLayer.GetLabelMethod lblDelegate = layer.LabelStringDelegate; //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection //Render labels for (int i = 0; i < features.Count; i++) { FeatureDataRow feature = features[i]; if (layer.CoordinateTransformation != null) { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, layer.CoordinateTransformation.MathTransform); } ILabelStyle style = null; if (layer.Theme != null) //If thematics is enabled, lets override the style { style = layer.Theme.GetStyle(feature); } else { style = layer.Style; } float rotation = 0; if (!String.IsNullOrEmpty(layer.RotationColumn)) { float.TryParse(feature[layer.RotationColumn].ToString(), NumberStyles.Any, Map.numberFormat_EnUS, out rotation); } string text; if (lblDelegate != null) { text = lblDelegate(feature); } else { text = feature[layer.LabelColumn].ToString(); } if (text != null && text != String.Empty) { if (feature.Geometry is GeometryCollection) { if (layer.MultipartGeometryBehaviour == SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.All) { foreach (SharpMap.Geometries.Geometry geom in (feature.Geometry as GeometryCollection)) { SharpMap.Rendering.Label lbl = CreateLabel(layer, geom, text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } } else if (layer.MultipartGeometryBehaviour == SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.CommonCenter) { Label lbl = CreateLabel(layer, feature.Geometry, text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } else if (layer.MultipartGeometryBehaviour == SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.First) { if ((feature.Geometry as GeometryCollection).Collection.Count > 0) { SharpMap.Rendering.Label lbl = CreateLabel(layer, (feature.Geometry as GeometryCollection).Collection[0], text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } } else if (layer.MultipartGeometryBehaviour == SharpMap.Layers.LabelLayer.MultipartGeometryBehaviourEnum.Largest) { GeometryCollection coll = (feature.Geometry as 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(layer, coll.Geometry(idxOfLargest), text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } } } else { SharpMap.Rendering.Label lbl = CreateLabel(layer, feature.Geometry, text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } } } if (labels.Count > 0) //We have labels to render... { if (layer.Style.CollisionDetection && layer.LabelFilter != null) { layer.LabelFilter(labels); } for (int i = 0; i < labels.Count; i++) { VectorRenderer.DrawLabel(g, labels[i].LabelPoint, labels[i].Style.Offset, labels[i].Style.Font, labels[i].Style.ForeColor, labels[i].Style.BackColor, layer.Style.Halo, labels[i].Rotation, labels[i].Text, map); } } labels = null; } //base.Render(g, map); }
public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox box, FeatureDataSet ds) { if (_LabelInfo == null) return; ds.Tables.Add(_LabelInfo); // Destroy internal reference _LabelInfo = null; }
/// <summary> /// Returns all features with the view box /// </summary> /// <param name="bbox">view box</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(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); } } } }
public override void Handle() { string queryLayers = this.context.Request.Params["LAYERS"]; string styles = this.context.Request.Params["STYLES"]; string crs = this.context.Request.Params["CRS"]; string queryBBOX = this.context.Request.Params["BBOX"]; string queryWidth = this.context.Request.Params["WIDTH"]; string queryHeight = this.context.Request.Params["HEIGHT"]; string format = this.context.Request.Params["FORMAT"]; string transparent = this.context.Request.Params["TRANSPARENT"]; string background = this.context.Request.Params["BGCOLOR"]; if (queryLayers == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (styles == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (crs == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } if (!this.Check(String.Format("EPSG:{0}", this.map.Layers[0].SRID), crs)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (queryBBOX == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (queryWidth == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (queryHeight == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (format == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } //Set background color of map if (!this.Check("TRUE", transparent)) { if (background != null) { try { this.map.BackColor = ColorTranslator.FromHtml(background); } catch { WmsException.ThrowWmsException("Invalid parameter BGCOLOR"); return; } } else this.map.BackColor = Color.White; } else this.map.BackColor = Color.Transparent; //Parse map size int width; if (!Int32.TryParse(queryWidth, out width)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter WIDTH"); return; } if (this.description.MaxWidth > 0 && width > this.description.MaxWidth) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter WIDTH too large"); return; } int height; if (!Int32.TryParse(queryHeight, out height)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Invalid parameter HEIGHT"); return; } if (this.description.MaxHeight > 0 && height > this.description.MaxHeight) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Parameter HEIGHT too large"); return; } this.map.Size = new Size(width, height); BoundingBox bbox = this.ParseBBOX(queryBBOX); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } this.map.PixelAspectRatio = (width / (double)height) / (bbox.Width / bbox.Height); this.map.Center = bbox.GetCentroid(); this.map.Zoom = bbox.Width; //Set layers on/off if (!String.IsNullOrEmpty(queryLayers)) //If LAYERS is empty, use default layer on/off settings { string[] layers = queryLayers.Split(new[] { ',' }); if (this.description.LayerLimit > 0) { if (layers.Length == 0 && this.map.Layers.Count > this.description.LayerLimit || layers.Length > this.description.LayerLimit) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.OperationNotSupported, "Too many layers requested"); return; } } foreach (ILayer layer in this.map.Layers) layer.Enabled = false; foreach (string layer in layers) { ILayer lay = this.map.GetLayerByName(layer); if (lay == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, String.Format("Unknown layer '{0}'", layer)); return; } lay.Enabled = true; } } bool json = this.Check("text/json", format); if (json) { List<GeoJSON> items = new List<GeoJSON>(); //Only queryable data! IQueryable<ICanQueryLayer> collection = this.map.Layers.AsQueryable() .OfType<ICanQueryLayer>().Where(l => l.Enabled && l.IsQueryEnabled); foreach (ICanQueryLayer layer in collection) { //Query for data FeatureDataSet ds = new FeatureDataSet(); layer.ExecuteIntersectionQuery(bbox, ds); IEnumerable<GeoJSON> data = GeoJSONHelper.GetData(ds); //Filter only visible items //double f = bbox.GetArea() / (width * height); //data = data.Where(i => //{ // Geometry g = i.Geometry; // BoundingBox p = g.GetBoundingBox(); // double area = p.GetArea(); // return area == 0 || area > f; //}); //Reproject geometries if needed IMathTransform transform = null; if (layer is VectorLayer) { ICoordinateTransformation transformation = (layer 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; }); } items.AddRange(data); } StringWriter writer = new StringWriter(); GeoJSONWriter.Write(items, writer); string buffer = writer.ToString(); this.context.Response.Clear(); this.context.Response.ContentType = "text/json"; this.context.Response.BufferOutput = true; this.context.Response.Write(buffer); this.context.Response.End(); } else { //Get the image format requested ImageCodecInfo imageEncoder = this.GetEncoderInfo(format); if (imageEncoder == null) { WmsException.ThrowWmsException("Invalid MimeType specified in FORMAT parameter"); return; } //Render map Image img = this.map.GetMap(); //Png can't stream directy. Going through a memorystream instead MemoryStream ms = new MemoryStream(); img.Save(ms, imageEncoder, null); img.Dispose(); byte[] buffer = ms.ToArray(); this.context.Response.Clear(); this.context.Response.ContentType = imageEncoder.MimeType; this.context.Response.BufferOutput = true; this.context.Response.BinaryWrite(buffer); this.context.Response.End(); } }
protected void RenderInternal(Graphics g, Map map, BoundingBox envelope, ITheme theme) { FeatureDataSet ds = new FeatureDataSet(); lock (_dataSource) { DataSource.Open(); DataSource.ExecuteIntersectionQuery(envelope, ds); DataSource.Close(); } foreach (FeatureDataTable features in ds.Tables) { if (CoordinateTransformation != null) { for (int i = 0; i < features.Count; i++) #if !DotSpatialProjections { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation. MathTransform); } } #else { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation.Source, CoordinateTransformation.Target); } #endif if (Style.EnableOutline) { for (int i = 0; i < features.Count; i++) { FeatureDataRow feature = features[i]; VectorStyle outlineStyle = Theme.GetStyle(feature) as VectorStyle; if (outlineStyle == null) { continue; } if (!(outlineStyle.Enabled && outlineStyle.EnableOutline)) { continue; } if (!(outlineStyle.MinVisible <= map.Zoom && map.Zoom <= outlineStyle.MaxVisible)) { continue; } outlineStyle = outlineStyle.Clone(); if (feature.Geometry is LineString) { VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlineStyle.Outline, map, outlineStyle.LineOffset, Style, RenderType.All); } else if (feature.Geometry is MultiLineString) { VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlineStyle.Outline, map, outlineStyle.LineOffset, Style, RenderType.All); } } } for (int i = 0; i < features.Count; i++) { FeatureDataRow feature = features[i]; VectorStyle style = Theme.GetStyle(feature) as VectorStyle; if (style == null) { continue; } if (!style.Enabled) { continue; } if (!(style.MinVisible <= map.Zoom && map.Zoom <= style.MaxVisible)) { continue; } RenderGeometry(g, map, feature.Geometry, style.Clone(), RenderType.All); } } }
/// <summary> /// /// </summary> /// <param name="box"></param> /// <param name="ds"></param> public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox box, FeatureDataSet ds) { // Identifies all the features within the given BoundingBox GisSharpBlog.NetTopologySuite.Geometries.Envelope envelope = GeometryConverter.ToNTSEnvelope(box); List<GisSharpBlog.NetTopologySuite.Features.Feature> results = new List<GisSharpBlog.NetTopologySuite.Features.Feature>(features.Count); foreach (GisSharpBlog.NetTopologySuite.Features.Feature feature in features) if (envelope.Intersects(feature.Geometry.EnvelopeInternal)) results.Add(feature); // Fill DataSet SharpMap.Data.FeatureDataTable dataTable = CreateFeatureDataTable(); foreach (GisSharpBlog.NetTopologySuite.Features.Feature feature in results) CreateNewRow(dataTable, feature); ds.Tables.Add(dataTable); }
public override void Render(Graphics g, MapViewport map) { try { _shapeFile.Open(); var ds = new FeatureDataSet(); _shapeFile.ExecuteIntersectionQuery(map.Envelope, ds); var dt = ds.Tables[0]; foreach (FeatureDataRow fdr in dt.Rows) { if (fdr.Geometry.EnvelopeInternal.Intersects(map.Envelope)) { var file = fdr[_fieldName] as string; if (!Path.IsPathRooted(file)) { file = Path.Combine(Path.GetDirectoryName(_fileName), file); } if (file == null) { continue; } if (_logger.IsDebugEnabled) { _logger.Debug("Drawing " + file); } if (!_openDatasets.ContainsKey(file)) { OpenDataset(file); _openDatasets.Add(file, new CacheHolder() { Bands = Bands, Dataset = _gdalDataset, Envelope = _envelope, HistoBounds = HistoBounds, ImageSize = _imageSize, Projection = Projection }); } else { CacheHolder hld = _openDatasets[file]; Bands = hld.Bands; _gdalDataset = hld.Dataset; _envelope = hld.Envelope; HistoBounds = hld.HistoBounds; _imageSize = hld.ImageSize; Projection = hld.Projection; } base.Render(g, map); _envelope = null; _gdalDataset = null; } } } catch (Exception) { _shapeFile.Close(); } }
/// <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(Graphics g, Map map) { if (map.Center == null) { throw (new ApplicationException("Cannot render map. View center not specified")); } g.SmoothingMode = SmoothingMode; BoundingBox envelope = map.Envelope; //View to render if (CoordinateTransformation != null) { #if !DotSpatialProjections CoordinateTransformation.MathTransform.Invert(); envelope = GeometryTransform.TransformBox(envelope, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); #else envelope = GeometryTransform.TransformBox(envelope, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } //List<SharpMap.Geometries.Geometry> features = this.DataSource.GetGeometriesInView(map.Envelope); if (DataSource == null) { throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'")); } //If thematics is enabled, we use a slighty different rendering approach if (Theme != null) { FeatureDataSet ds = new FeatureDataSet(); lock (_dataSource) { DataSource.Open(); DataSource.ExecuteIntersectionQuery(envelope, ds); DataSource.Close(); } foreach (FeatureDataTable features in ds.Tables) { if (CoordinateTransformation != null) { for (int i = 0; i < features.Count; i++) #if !DotSpatialProjections { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation. MathTransform); } } #else { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, CoordinateTransformation.Source, CoordinateTransformation.Target); } #endif //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++) { FeatureDataRow feature = features[i]; VectorStyle outlineStyle = Theme.GetStyle(feature) as VectorStyle; if (outlineStyle == null) { continue; } if (!(outlineStyle.Enabled && outlineStyle.EnableOutline)) { continue; } if (!(outlineStyle.MinVisible <= map.Zoom && map.Zoom <= outlineStyle.MaxVisible)) { continue; } //Draw background of all line-outlines first if (feature.Geometry is LineString) { VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } else if (feature.Geometry is MultiLineString) { VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlineStyle.Outline, map, outlineStyle.LineOffset); } } } for (int i = 0; i < features.Count; i++) { FeatureDataRow feature = features[i]; VectorStyle style = Theme.GetStyle(feature) as VectorStyle; if (style == null) { continue; } if (!style.Enabled) { continue; } if (!(style.MinVisible <= map.Zoom && map.Zoom <= style.MaxVisible)) { continue; } RenderGeometry(g, map, feature.Geometry, style); } } } else { //if style is not enabled, we don't need to render anything if (!Style.Enabled) { return; } Collection <Geometry> geoms = null; // Is datasource already open? lock (_dataSource) { bool alreadyOpen = DataSource.IsOpen; // If not open yet, open it if (!alreadyOpen) { DataSource.Open(); } // Read data geoms = DataSource.GetGeometriesInView(envelope); // If was not open, close it if (!alreadyOpen) { DataSource.Close(); } } if (CoordinateTransformation != null) { for (int i = 0; i < geoms.Count; i++) #if !DotSpatialProjections { geoms[i] = GeometryTransform.TransformGeometry(geoms[i], CoordinateTransformation.MathTransform); } } #else { geoms[i] = GeometryTransform.TransformGeometry(geoms[i], CoordinateTransformation.Source, CoordinateTransformation.Target); } #endif //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (Style.EnableOutline) { foreach (Geometry geom in geoms) { if (geom != null) { //Draw background of all line-outlines first if (geom is LineString) { VectorRenderer.DrawLineString(g, geom as LineString, Style.Outline, map, Style.LineOffset); } else if (geom is MultiLineString) { VectorRenderer.DrawMultiLineString(g, geom as MultiLineString, Style.Outline, map, Style.LineOffset); } } } } for (int i = 0; i < geoms.Count; i++) { if (geoms[i] != null) { RenderGeometry(g, map, geoms[i], Style); } } } base.Render(g, map); }
/// <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)) { //TODO: Convert to SQL Server string strGeom = "geography::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(_defintionQuery)) { strSQL += 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); } } } }
/// <summary> /// Method to perform the actual intersection query against a bounding box /// </summary> /// <param name="box">The bounding box</param> /// <param name="ds">The feature data set to store the results in.</param> protected virtual void ExecuteIntersectionQueryInternal(Envelope box, FeatureDataSet ds) { ExecuteIntersectionQueryInternal((object)box, ds); }
/// <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; 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.RelateQuery" + BuildSpatialQuerySuffix() + "(" + strGeom + ", 'intersects')"; if (!String.IsNullOrEmpty(DefinitionQuery)) { strSQL += " WHERE " + DefinitionQuery; } if (!String.IsNullOrEmpty(OrderQuery)) { strSQL += " ORDER BY " + 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 (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); } ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="box">Geometry to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public override sealed void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { Initialize(); ExecuteIntersectionQueryInternal(box, ds); }
/// <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 void GetFeaturesInView(BoundingBox bbox, FeatureDataSet ds) { ExecuteIntersectionQuery(bbox, ds); }
public void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { ExecuteIntersectionQuery(_geometryFactory.ToGeometry(box), ds); }
/// <summary> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics g, MapViewport map) { if (DataSource == null) { throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'")); } g.TextRenderingHint = TextRenderingHint; g.SmoothingMode = SmoothingMode; var mapEnvelope = map.Envelope; var layerEnvelope = ToSource(mapEnvelope); //View to render var lineClipping = new CohenSutherlandLineClipping(mapEnvelope.MinX, mapEnvelope.MinY, mapEnvelope.MaxX, mapEnvelope.MaxY); var ds = new FeatureDataSet(); DataSource.Open(); DataSource.ExecuteIntersectionQuery(layerEnvelope, ds); DataSource.Close(); if (ds.Tables.Count == 0) { base.Render(g, map); return; } var features = ds.Tables[0]; //Initialize label collection var labels = new List <BaseLabel>(); //List<System.Drawing.Rectangle> LabelBoxes; //Used for collision detection //Render labels for (int i = 0; i < features.Count; i++) { var feature = features[i]; feature.Geometry = ToTarget(feature.Geometry); LabelStyle style; if (Theme != null) //If thematics is enabled, lets override the style { style = Theme.GetStyle(feature) as LabelStyle; } else { style = Style; } // Do we need to render at all? if (!style.Enabled) { continue; } // Rotation float rotationStyle = style != null ? style.Rotation : 0f; float rotationColumn = 0f; if (!String.IsNullOrEmpty(RotationColumn)) { Single.TryParse(feature[RotationColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs, out rotationColumn); } float rotation = rotationStyle + rotationColumn; // Priority int priority = Priority; if (_getPriorityMethod != null) { priority = _getPriorityMethod(feature); } else if (!String.IsNullOrEmpty(PriorityColumn)) { Int32.TryParse(feature[PriorityColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs, out priority); } // Text string text; if (_getLabelMethod != null) { text = _getLabelMethod(feature); } else { text = feature[LabelColumn].ToString(); } if (!String.IsNullOrEmpty(text)) { // for lineal geometries, try clipping to ensure proper labeling if (feature.Geometry is ILineal) { if (feature.Geometry is ILineString) { feature.Geometry = lineClipping.ClipLineString(feature.Geometry as ILineString); } else if (feature.Geometry is IMultiLineString) { feature.Geometry = lineClipping.ClipLineString(feature.Geometry as IMultiLineString); } } if (feature.Geometry is IGeometryCollection) { if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All) { foreach (var geom in (feature.Geometry as IGeometryCollection)) { BaseLabel lbl = CreateLabel(feature, geom, text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter) { BaseLabel lbl = CreateLabel(feature, feature.Geometry, text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First) { if ((feature.Geometry as IGeometryCollection).NumGeometries > 0) { BaseLabel lbl = CreateLabel(feature, (feature.Geometry as IGeometryCollection).GetGeometryN(0), text, rotation, style, map, g); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest) { var coll = (feature.Geometry as IGeometryCollection); if (coll.NumGeometries > 0) { var largestVal = 0d; var idxOfLargest = 0; for (var j = 0; j < coll.NumGeometries; j++) { var geom = coll.GetGeometryN(j); if (geom is ILineString && ((ILineString)geom).Length > largestVal) { largestVal = ((ILineString)geom).Length; idxOfLargest = j; } if (geom is IMultiLineString && ((IMultiLineString)geom).Length > largestVal) { largestVal = ((IMultiLineString)geom).Length; idxOfLargest = j; } if (geom is IPolygon && ((IPolygon)geom).Area > largestVal) { largestVal = ((IPolygon)geom).Area; idxOfLargest = j; } if (geom is IMultiPolygon && ((IMultiPolygon)geom).Area > largestVal) { largestVal = ((IMultiPolygon)geom).Area; idxOfLargest = j; } } BaseLabel lbl = CreateLabel(feature, coll.GetGeometryN(idxOfLargest), text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } } else { BaseLabel lbl = CreateLabel(feature, feature.Geometry, text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } } if (labels.Count > 0) //We have labels to render... { if (Style.CollisionDetection && _labelFilter != null) { _labelFilter(labels); } for (int i = 0; i < labels.Count; i++) { // Don't show the label if not necessary if (!labels[i].Show) { continue; } if (labels[i] is Label) { var label = labels[i] as Label; if (label.Style.IsTextOnPath == false || label.TextOnPathLabel == null) { VectorRenderer.DrawLabel(g, label.Location, label.Style.Offset, label.Style.GetFontForGraphics(g), label.Style.ForeColor, label.Style.BackColor, label.Style.Halo, label.Rotation, label.Text, map, label.Style.HorizontalAlignment, label.LabelPoint); } else { if (label.Style.BackColor != null && label.Style.BackColor != System.Drawing.Brushes.Transparent) { //draw background if (label.TextOnPathLabel.RegionList.Count > 0) { g.FillRectangles(labels[i].Style.BackColor, labels[i].TextOnPathLabel.RegionList.ToArray()); //g.FillPolygon(labels[i].Style.BackColor, labels[i].TextOnPathLabel.PointsText.ToArray()); } } label.TextOnPathLabel.DrawTextOnPath(); } } else if (labels[i] is PathLabel) { var plbl = labels[i] as PathLabel; var lblStyle = plbl.Style; g.DrawString(lblStyle.Halo, new SolidBrush(lblStyle.ForeColor), plbl.Text, lblStyle.Font.FontFamily, (int)lblStyle.Font.Style, lblStyle.Font.Size, lblStyle.GetStringFormat(), lblStyle.IgnoreLength, plbl.Location); } } } base.Render(g, map); }
public void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { ((ICanQueryLayer)_innerLayer).ExecuteIntersectionQuery(box, ds); }
///// <summary> ///// Spacial Reference ID ///// </summary> //public int SRID //{ // get // { // if (_srid == -2) // { // string strSQL = "select SRID from USER_SDO_GEOM_METADATA WHERE TABLE_NAME='" + Table + "'"; // using (OracleConnection conn = new OracleConnection(ConnectionString)) // { // using (OracleCommand command = new OracleCommand(strSQL, conn)) // { // try // { // conn.Open(); // _srid = (int) (decimal) command.ExecuteScalar(); // conn.Close(); // } // catch // { // _srid = -1; // } // } // } // } // return _srid; // } // set { throw (new ApplicationException("Spatial Reference ID cannot by set on a Oracle table")); } //} /// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="oid"></param> /// <returns>datarow</returns> public override IFeature GetFeatureByOid(object oid) { using (var conn = new OracleConnection(ConnectionString)) { string strSQL = "select g.* , g." + GeometryColumn + ").Get_WKB() As sharpmap_tempgeometry from " + Table + " g WHERE " + ObjectIdColumn + "=:POid"; using (var adapter = new OracleDataAdapter(strSQL, conn)) { adapter.SelectCommand.Parameters.Add("POid", oid); var ds = new FeatureDataSet(); 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); if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; 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); return fdr; } } return null; } } }
public void ExecuteIntersectionQuery(Geometry geometry, FeatureDataSet ds) { ((ICanQueryLayer)_innerLayer).ExecuteIntersectionQuery(geometry, ds); }
/// <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); } } } }
/// <summary> /// Method to perform the actual intersection query against a bounding box /// </summary> /// <param name="box">The bounding box</param> /// <param name="ds">The feature data set to store the results in.</param> protected virtual void ExecuteIntersectionQueryInternal(Envelope box, FeatureDataSet ds, CancellationToken? cancellationToken = null) { ExecuteIntersectionQueryInternal((object)box, ds, cancellationToken); }
/// <summary> /// Returns the features that intersects with 'geom' [NOT IMPLEMENTED] /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds) { throw new NotImplementedException(); }
/// <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 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> /// Throws NotSupportedException. /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds) { throw new NotSupportedException("ExecuteIntersectionQuery(Geometry) is not supported by the DataTablePoint."); //When relation model has been implemented the following will complete the query /* ExecuteIntersectionQuery(geom.GetBoundingBox(), ds); if (ds.Tables.Count > 0) { for(int i=ds.Tables[0].Count-1;i>=0;i--) { if (!geom.Intersects(ds.Tables[0][i].Geometry)) ds.Tables.RemoveAt(i); } } */ }
public void GetFeaturesInView(BoundingBox bbox, FeatureDataSet ds) { GetFeaturesInView(bbox, ds); }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="box">Geometry to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { if (_labelInfo == null) return; ds.Tables.Add(_labelInfo); // Destroy internal reference _labelInfo = null; }
/// <summary> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics g, MapViewport map) { if (DataSource == null) { throw (new ApplicationException("DataSource property not set on layer '" + LayerName + "'")); } var layerEnvelope = ToSource(map.Envelope); //View to render List <BaseLabel> labels = null; using (var ds = new FeatureDataSet()) { DataSource.Open(); DataSource.ExecuteIntersectionQuery(layerEnvelope, ds); DataSource.Close(); if (ds.Tables.Count > 0) { g.TextRenderingHint = TextRenderingHint; g.SmoothingMode = SmoothingMode; labels = CreateLabelDefinitions(g, map, ds.Tables[0]); } } if (labels == null || labels.Count == 0) { // Obsolete (and will cause infinite loop) //base.Render(g, map); return; } if (Style.CollisionDetection) { _labelFilter?.Invoke(labels); } var combinedArea = RectangleF.Empty; for (int i = 0; i < labels.Count; i++) { var baseLabel = labels[i]; if (!baseLabel.Show) { continue; } var font = baseLabel.Style.GetFontForGraphics(g); if (labels[i] is Label) { var label = baseLabel as Label; var canvasArea = VectorRenderer.DrawLabelEx( g, label.Location, label.Style.Offset, font, label.Style.ForeColor, label.Style.BackColor, label.Style.Halo, label.Rotation, label.Text, map, label.Style.HorizontalAlignment, label.LabelPoint); combinedArea = canvasArea.ExpandToInclude(combinedArea); } else if (labels[i] is PathLabel) { var pathLabel = labels[i] as PathLabel; var lblStyle = pathLabel.Style; var background = pathLabel.AffectedArea.ExteriorRing.TransformToImage(map); if (lblStyle.BackColor != null && lblStyle.BackColor != Brushes.Transparent) { using (var gp = new GraphicsPath()) { gp.AddPolygon(background); g.FillPath(lblStyle.BackColor, gp); } } g.DrawString(lblStyle.Halo, new SolidBrush(lblStyle.ForeColor), pathLabel.Text, font.FontFamily, (int)font.Style, font.Size, lblStyle.GetStringFormat(), lblStyle.IgnoreLength, pathLabel.Location, pathLabel.Box.Height); combinedArea = background.ToRectangleF().ExpandToInclude(combinedArea); } } CanvasArea = combinedArea; // Obsolete (and will cause infinite loop) //base.Render(g, map); }
/// <summary> /// /// </summary> /// <param name="geom"></param> /// <param name="ds"></param> public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds) { GisSharpBlog.NetTopologySuite.Geometries.Geometry geometry = GeometryConverter.ToNTSGeometry(geom, geometryFactory); SharpMap.Data.FeatureDataTable dataTable = CreateFeatureDataTable(); foreach (GisSharpBlog.NetTopologySuite.Features.Feature feature in features) if (feature.Geometry.Intersects(geometry)) CreateNewRow(dataTable, feature); ds.Tables.Add(dataTable); }
/// <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<Geometries.Geometry> features = new List<GeoAPI.Geometries.IGeometry>(); using (var conn = DbProvider.CreateConnection()) { conn.ConnectionString = ConnectionString; conn.Open(); var strSQL = "SELECT * FROM " + Table + " WHERE "; //If a definition query has been specified, add this as a filter on the query strSQL += GetDefinitionQueryConstraint(true); //Limit to the points within the boundingbox strSQL += GetSpatialConstraint(bbox); using (var cmd = conn.CreateCommand()) { cmd.CommandText = strSQL; using (var reader = cmd.ExecuteReader()) { if (reader == null) { throw new InvalidOperationException(); } //Set up result table var fdt = new FeatureDataTable(); fdt.TableName = Table; for (var c = 0; c < reader.FieldCount; c++) { var fieldType = reader.GetFieldType(c); if (fieldType == null) { throw new Exception("Failed to retrieve field type for column: " + c); } fdt.Columns.Add(reader.GetName(c), fieldType); } var dataTransfer = new object[reader.FieldCount]; //Get factory and precision model var factory = Factory; var pm = factory.PrecisionModel; fdt.BeginLoadData(); while (reader.Read()) { var count = reader.GetValues(dataTransfer); System.Diagnostics.Debug.Assert(count == dataTransfer.Length); var fdr = (FeatureDataRow)fdt.LoadDataRow(dataTransfer, true); var c = new Coordinate(Convert.ToDouble(fdr[XColumn]), Convert.ToDouble(fdr[YColumn])); pm.MakePrecise(c); fdr.Geometry = Factory.CreatePoint(c); } fdt.EndLoadData(); 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 (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); } } } }
public override void Handle() { string layers = this.context.Request.Params["LAYERS"]; string styles = this.context.Request.Params["STYLES"]; string crs = this.context.Request.Params["CRS"]; string queryBBOX = this.context.Request.Params["BBOX"]; string queryWidth = this.context.Request.Params["WIDTH"]; string queryHeight = this.context.Request.Params["HEIGHT"]; string format = this.context.Request.Params["FORMAT"]; string queryLayers = this.context.Request.Params["QUERY_LAYERS"]; string infoFormat = this.context.Request.Params["INFO_FORMAT"]; string xAxis = this.context.Request.Params["X"]; string yAxis = this.context.Request.Params["Y"]; string iParam = this.context.Request.Params["I"]; string jParam = this.context.Request.Params["J"]; if (layers == null) { WmsException.ThrowWmsException("Required parameter LAYERS not specified"); return; } if (styles == null) { WmsException.ThrowWmsException("Required parameter STYLES not specified"); return; } if (crs == null) { WmsException.ThrowWmsException("Required parameter CRS not specified"); return; } if (!this.Check(String.Format("EPSG:{0}", this.map.Layers[0].SRID), crs)) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidCRS, "CRS not supported"); return; } if (queryBBOX == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter BBOX not specified"); return; } if (queryWidth == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter WIDTH not specified"); return; } if (queryHeight == null) { WmsException.ThrowWmsException(WmsException.WmsExceptionCode.InvalidDimensionValue, "Required parameter HEIGHT not specified"); return; } if (format == null) { WmsException.ThrowWmsException("Required parameter FORMAT not specified"); return; } if (queryLayers == null) { WmsException.ThrowWmsException("Required parameter QUERY_LAYERS not specified"); return; } if (infoFormat == null) { WmsException.ThrowWmsException("Required parameter INFO_FORMAT not specified"); return; } //parameters X&Y are not part of the 1.3.0 specification, but are included for backwards compatability with 1.1.1 // (OpenLayers likes it when used together with 1.1.1 services) if (xAxis == null && iParam == null) { WmsException.ThrowWmsException("Required parameter I not specified"); return; } if (yAxis == null && jParam == null) { WmsException.ThrowWmsException("Required parameter J not specified"); return; } try { //sets the map size to the size of the client in order to calculate the coordinates of the projection of the client this.map.Size = new Size(Convert.ToInt16(queryWidth), Convert.ToInt16(queryHeight)); } catch { WmsException.ThrowWmsException("Invalid parameters for HEIGHT or WITDH"); return; } //sets the boundingbox to the boundingbox of the client in order to calculate the coordinates of the projection of the client BoundingBox bbox = this.ParseBBOX(queryBBOX); if (bbox == null) { WmsException.ThrowWmsException("Invalid parameter BBOX"); return; } this.map.ZoomToBox(bbox); //sets the point clicked by the client Single x = 0; Single y = 0; //tries to set the x to the Param I, if the client send an X, it will try the X, if both fail, exception is thrown if (xAxis != null) { try { x = Convert.ToSingle(xAxis); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } } if (iParam != null) { try { x = Convert.ToSingle(iParam); } catch { WmsException.ThrowWmsException("Invalid parameters for I"); } } //same procedure for J (Y) if (yAxis != null) { try { y = Convert.ToSingle(yAxis); } catch { WmsException.ThrowWmsException("Invalid parameters for J"); } } if (jParam != null) { try { y = Convert.ToSingle(jParam); } catch { WmsException.ThrowWmsException("Invalid parameters for J"); } } Point p = this.map.ImageToWorld(new PointF(x, y)); int fc; try { fc = Convert.ToInt16(this.context.Request.Params["FEATURE_COUNT"]); if (fc < 1) { fc = 1; } } catch { fc = 1; } String vstr = "GetFeatureInfo results: \n"; string[] requestLayers = queryLayers.Split(new[] { ',' }); foreach (string item in requestLayers) { bool found = false; foreach (ILayer mapLayer in this.map.Layers) { if (!String.Equals(mapLayer.LayerName, item, StringComparison.InvariantCultureIgnoreCase)) { continue; } found = true; if (!(mapLayer is ICanQueryLayer)) { continue; } ICanQueryLayer layer = mapLayer as ICanQueryLayer; bool enabled = layer.Enabled && layer.IsQueryEnabled; if (!enabled) { continue; } Single queryBoxMinX = x - (this.pixelSensitivity); Single queryBoxMinY = y - (this.pixelSensitivity); Single queryBoxMaxX = x + (this.pixelSensitivity); Single queryBoxMaxY = y + (this.pixelSensitivity); Point minXY = this.map.ImageToWorld(new PointF(queryBoxMinX, queryBoxMinY)); Point maxXY = this.map.ImageToWorld(new PointF(queryBoxMaxX, queryBoxMaxY)); BoundingBox queryBox = new BoundingBox(minXY, maxXY); FeatureDataSet fds = new FeatureDataSet(); layer.ExecuteIntersectionQuery(queryBox, fds); if (this.intersectDelegate != null) { fds.Tables[0] = this.intersectDelegate(fds.Tables[0], queryBox); } if (fds.Tables.Count != 0) { if (fds.Tables[0].Rows.Count != 0) { //if featurecount < fds...count, select smallest bbox, because most likely to be clicked vstr = String.Format("{0}\n Layer: '{1}'\n Featureinfo:\n", vstr, item); 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++) { FeatureDataRow fdr = fds.Tables[0].Rows[l] as FeatureDataRow; area[l] = fdr.Geometry.GetBoundingBox().GetArea(); keys[l] = l; } Array.Sort(area, keys); if (fds.Tables[0].Rows.Count < fc) { fc = fds.Tables[0].Rows.Count; } for (int k = 0; k < fc; k++) { for (int j = 0; j < fds.Tables[0].Rows[keys[k]].ItemArray.Length; j++) { vstr = String.Format("{0} '{1}'", vstr, fds.Tables[0].Rows[keys[k]].ItemArray[j].ToString()); } if ((k + 1) < fc) { vstr = String.Format("{0},\n", vstr); } } } else { vstr = String.Format("{0}\nSearch returned no results on layer: {1} ", vstr, item); } } else { vstr = String.Format("{0}\nSearch returned no results on layer: {1}", vstr, item); } } if (found) { continue; } WmsException.ThrowWmsException(WmsException.WmsExceptionCode.LayerNotDefined, String.Format("Unknown layer '{0}'", item)); return; } this.context.Response.Clear(); this.context.Response.ContentType = "text/plain"; this.context.Response.Charset = "windows-1252"; this.context.Response.Write(vstr); this.context.Response.Flush(); this.context.Response.End(); }
/// <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 the features that intersects with 'geom' /// </summary> /// <param name="geom"></param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, FeatureDataSet ds) { List<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>(); 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); } } } }
/// <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<Geometries.Geometry> features = new List<SharpMap.Geometries.Geometry>(); using (var conn = new OleDbConnection(ConnectionString)) { conn.Open(); var strSQL = "SELECT * FROM " + Table + " WHERE "; //If a definition query has been specified, add this as a filter on the query strSQL += GetDefinitionQueryConstraint(true); //Limit to the points within the boundingbox strSQL += GetSpatialConstraint(bbox); using (var cmd = new OleDbCommand(strSQL, conn)) { using (var reader = cmd.ExecuteReader()) { if (reader == null) throw new InvalidOperationException(); //Set up result table var fdt = new FeatureDataTable(); fdt.TableName = Table; for (var c = 0; c < reader.FieldCount; c++) { var fieldType = reader.GetFieldType(c); if (fieldType == null) throw new Exception("Failed to retrieve field type for column: " + c); fdt.Columns.Add(reader.GetName(c), fieldType); } var dataTransfer = new object[reader.FieldCount]; //Get factory and precision model var factory = Factory; var pm = factory.PrecisionModel; fdt.BeginLoadData(); while (reader.Read()) { var count = reader.GetValues(dataTransfer); System.Diagnostics.Debug.Assert(count == dataTransfer.Length); var fdr = (FeatureDataRow) fdt.LoadDataRow(dataTransfer, true); var c = new Coordinate(Convert.ToDouble(fdr[XColumn]), Convert.ToDouble(fdr[YColumn])); pm.MakePrecise(c); fdr.Geometry = Factory.CreatePoint(c); } fdt.EndLoadData(); ds.Tables.Add(fdt); } } } }
/// <summary> /// Returns a datarow based on a RowID /// </summary> /// <param name="RowID"></param> /// <returns>datarow</returns> public SharpMap.Data.FeatureDataRow GetFeature(uint RowID) { using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "select " + this.FeatureColumns + ", ST.AsBinary(" + this.BuildGeometryExpression() + ") As sharpmap_tempgeometry from " + this.Table + " WHERE " + this.ObjectIdColumn + "='" + RowID.ToString() + "'"; using (SqlDataAdapter adapter = new SqlDataAdapter(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 (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); 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) 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"]); return fdr; } else return null; } else return null; } } }