void cmbFeatureLayer_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selected = cmbFeatureLayer.SelectedItem as VectorLayerViewModel; if (selected != null) { var layer = selected.Model as VectorLayer; SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); layer.DataSource.Open(); layer.DataSource.ExecuteIntersectionQuery(layer.DataSource.GetExtents(), ds); DataTable tbl = ds.Tables[0] as SharpMap.Data.FeatureDataTable; var list = new ObservableCollection <DataColumnViewModel>(); var ignore = new String[] { "BLREGHIER", "BLAUTH" }; foreach (DataColumn col in tbl.Columns) { var vm = new DataColumnViewModel(col); if (!ignore.Contains(col.ColumnName)) { vm.IsSelected = true; } list.Add(vm); } lstFields.ItemsSource = list; } }
public void TestCreateFromFeatureDataTable() { var fds = new SharpMap.Data.FeatureDataSet(); FeatureDataTable fdt = null; try { var p = new Ogr("C:\\Users\\obe.IVV-AACHEN\\Downloads\\SharpMap Codeplex\\SHPFiles\\RxLevel-Idle.shp"); p.SRID = 4326; var layer = string.Empty; if (!string.IsNullOrEmpty(layer)) { p.LayerName = layer; } p.ExecuteIntersectionQuery(p.GetExtents(), fds); fdt = fds.Tables[0]; if (fdt.Rows.Count == 0) { throw new Exception("no data in layer"); } } catch (Exception ex) { throw new IgnoreException("Getting data failed", ex); } Assert.DoesNotThrow(() => Ogr.CreateFromFeatureDataTable(fdt, ((FeatureDataRow)fdt.Rows[0]).Geometry.OgcGeometryType, 4326, "Mapinfo File", "C:\\Users\\obe.IVV-AACHEN\\Downloads\\SharpMap Codeplex\\SHPFiles\\RxLevel-Idle.tab")); }
public static FeatureDataRow FindGeoNearPoint(GeoAPI.Geometries.IPoint point, VectorLayer layer, double amountGrow) { var box = new Envelope(point.Coordinate); box.ExpandBy(amountGrow); var fds = new FeatureDataSet(); layer.DataSource.ExecuteIntersectionQuery(box, fds); FeatureDataRow result = null; var minDistance = double.MaxValue; foreach (FeatureDataTable fdt in fds.Tables) { foreach (FeatureDataRow fdr in fdt.Rows) { if (fdr.Geometry != null) { var distance = point.Distance(fdr.Geometry); if (distance < minDistance) { result = fdr; minDistance = distance; } } } } return result; }
public void TestCreateFromFeatureDataTable() { var fds = new SharpMap.Data.FeatureDataSet(); FeatureDataTable fdt = null; try { var p = new Ogr("C:\\Users\\obe.IVV-AACHEN\\Downloads\\SharpMap Codeplex\\SHPFiles\\RxLevel-Idle.shp"); p.SRID = 4326; var layer = string.Empty; if (!string.IsNullOrEmpty(layer)) p.LayerName = layer; p.ExecuteIntersectionQuery(p.GetExtents(), fds); fdt = fds.Tables[0]; if (fdt.Rows.Count == 0) throw new Exception("no data in layer"); } catch (Exception ex) { throw new IgnoreException("Getting data failed", ex); } Assert.DoesNotThrow(() => Ogr.CreateFromFeatureDataTable(fdt, ((FeatureDataRow)fdt.Rows[0]).Geometry.OgcGeometryType, 4326, "Mapinfo File", "C:\\Users\\obe.IVV-AACHEN\\Downloads\\SharpMap Codeplex\\SHPFiles\\RxLevel-Idle.tab")); }
public void render2d(Project project, PictureBox picBox) { SharpMap.Map myMap = new SharpMap.Map(); foreach (BuildLayer layer in project.getLayers()) { Source source = layer.getSource(); BoundingBox envelope = new BoundingBox(-1000.0, -1000.0, 1000.0, 1000.0);//TODO FeatureDataSet ds = new FeatureDataSet(); source.DataSource.Open(); source.DataSource.ExecuteIntersectionQuery(envelope, ds); source.DataSource.Close(); FeatureDataTable features = (FeatureDataTable)ds.Tables[0]; string label = "Trace test:\n"; foreach (FeatureDataRow row in features) { foreach (Object item in row.ItemArray) label += " - " + item; label += "\n"; } setLabel(label); //Show map //Filters FilterGraph graph = project.getFilterGraph(source.getName()); if (graph != null) { foreach (FeatureFilter filter in graph.getFilters()) { //aplicar filtro segun el tipo Mogre.DefaultSceneManagerFactory dsmf = new DefaultSceneManagerFactory(); Mogre.SceneManager sm = dsmf.CreateInstance("scenemanager"); FilterEnv env = new FilterEnv(sm, "env"); foreach (MogreGis.Resource resource in project.getResources()) { env.getSession().Resources.addResource(resource); } FeatureList list = Feature.DataTableToList(features); filter.process(list, env); //falta devolver la lista y procesarla *************************************** } } SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer(layer.getName()); myLayer.DataSource = source.DataSource; myMap.Layers.Add(myLayer); } myMap.Size = new Size(picBox.Width, picBox.Height); myMap.ZoomToExtents(); picBox.Image = myMap.GetMap(); this.map = myMap; }
public IFeatureReader ExecuteFeatureReader(SpatialPredicate predicate, Envelope envelope) { if (predicate != SpatialPredicate.Intersects) throw new NotSupportedException(); var fds = new FeatureDataSet(); _provider.ExecuteIntersectionQuery(envelope, fds); return new ProviderFeatureDataRowReader(fds.Tables[0]); }
public void TestExecuteIntersectionQueryAgainstEnvelope() { using (var p = CreateProvider()) { var fds = new FeatureDataSet(); Assert.DoesNotThrow(() => p.ExecuteIntersectionQuery(p.GetExtents(), fds)); Assert.AreEqual(1, fds.Tables.Count); var table = fds.Tables[0]; Assert.AreEqual(_tableName, table.TableName); Assert.AreEqual(4, table.Rows.Count); } }
public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox box, SharpMap.Data.FeatureDataSet ds) { Rectangle r = new Rectangle((float)box.Left, (float)box.Bottom, (float)box.Right, (float)box.Top, (float)0.0, (float)0.0); FdoFeature[] matches = _data.Intersects(r); FeatureDataTable table = new FeatureDataTable(); foreach (DataColumn col in _data.Columns) { table.Columns.Add(col.ColumnName, col.DataType, col.Expression); } //Filter the initial result set by inverting the operands. This weeds out non-matches on point intersection tests. IEnvelope env = Converter.EnvelopeFromBoundingBox(box); FdoGeometry poly = new FdoGeometry(Converter.CreatePolygonFromEnvelope(env)); foreach (FdoFeature feat in matches) { FdoGeometry geom = feat.DesignatedGeometry; if (geom != null) { if (geom.Contains(env) || geom.Intersects(poly)) { FeatureDataRow row = table.NewRow(); bool add = true; foreach (DataColumn col in _data.Columns) { if (col.ColumnName == _data.GeometryColumn) { try { row.Geometry = Converter.FromFdoGeometry(geom, _geomFactory); } catch //Can't help you if you fail conversion. { add = false; } } else { row[col.ColumnName] = feat[col.ColumnName]; } } if (add) { table.AddRow(row); } } } } ds.Tables.Add(table); }
/// <summary> /// Returns all features with the view box /// </summary> /// <param name="bbox">view box</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(SharpMap.Geometries.BoundingBox bbox, SharpMap.Data.FeatureDataSet ds) { List <Geometries.Geometry> features = new List <SharpMap.Geometries.Geometry>(); using (SqlConnection conn = new SqlConnection(_ConnectionString)) { string strSQL = "SELECT *, " + this.GeometryColumn + " AS sharpmap_tempgeometry "; strSQL += "FROM " + this.Table + " WHERE "; strSQL += GetBoxClause(bbox); if (_defintionQuery != null && _defintionQuery != "") { strSQL += " AND " + this.DefinitionQuery; } using (SqlDataAdapter adapter = new SqlDataAdapter(strSQL, conn)) { conn.Open(); System.Data.DataSet ds2 = new System.Data.DataSet(); adapter.Fill(ds2); conn.Close(); if (ds2.Tables.Count > 0) { FeatureDataTable fdt = new FeatureDataTable(ds2.Tables[0]); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) { fdt.Columns.Add(col.ColumnName, col.DataType, col.Expression); } } foreach (System.Data.DataRow dr in ds2.Tables[0].Rows) { SharpMap.Data.FeatureDataRow fdr = fdt.NewRow(); foreach (System.Data.DataColumn col in ds2.Tables[0].Columns) { if (col.ColumnName != this.GeometryColumn && col.ColumnName != "sharpmap_tempgeometry" && !col.ColumnName.StartsWith("Envelope_")) { fdr[col.ColumnName] = dr[col]; } } if (dr["sharpmap_tempgeometry"] != DBNull.Value) { fdr.Geometry = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])dr["sharpmap_tempgeometry"]); } fdt.AddRow(fdr); } ds.Tables.Add(fdt); } } } }
public void TestIndexing() { var fds = new FeatureDataSet { DataSetName = "Indexing" }; var ds = (DataSet)fds; for (var i = 0; i < 10; i++) ds.Tables.Add(i%2 == 0 ? CreateFeatureDataTable("T" + i) : CreateDataTable("T" + i, true)); Assert.AreEqual(10, ds.Tables.Count); Assert.AreEqual(5, fds.Tables.Count); for (var i = 0; i < 5; i++) Assert.IsTrue(ReferenceEquals(ds.Tables[2*i], fds.Tables[i])); }
public JsonResult GetData(float w, float n, float e, float s, int z) { string format = String.Format("~/App_Data/berlin/{0}", "osmbuildings.shp"); string path = this.HttpContext.Server.MapPath(format); if (!System.IO.File.Exists(path)) throw new FileNotFoundException("file not found", path); Point start = this.GeoToPixel(n, w, z); var meta = new { n, w, s, e, x = start.X, y = start.Y, z }; Envelope bbox = new Envelope(); bbox.ExpandToInclude(new Coordinate(n, w)); bbox.ExpandToInclude(new Coordinate(s, e)); FeatureDataSet ds = new FeatureDataSet(); using (ShapeFile provider = new ShapeFile(path)) { provider.DoTrueIntersectionQuery = true; provider.Open(); provider.ExecuteIntersectionQuery(bbox, ds); provider.Close(); } int zz = MaxZoom - z; List<object> data = new List<object>(); FeatureDataTable table = ds.Tables[0]; foreach (FeatureDataRow row in table) { int c = (short)(row["height"]); if (c == 0) c = 5; // default value for "null" (zero) heights int h = c * ScaleZ >> zz; if (h <= 1) h = 1; IGeometry geometry = row.Geometry; Coordinate[] coords = geometry.Coordinates; int total = coords.Length; double[] values = new double[total * 2]; int i = 0; foreach (Coordinate curr in coords) { Point p = this.GeoToPixel(curr.X, curr.Y, z); values[i++] = p.X - start.X; values[i++] = p.Y - start.Y; } data.Add(new object[] { h, values }); } return this.Json(new { meta, data }, JsonRequestBehavior.AllowGet); }
public void TestSerializationOfDataset() { var fds = new FeatureDataSet { DataSetName = "Serialization", Namespace = "ns" }; using (var p = Serialization.ProviderTest.CreateProvider("managedspatialite")) { p.Open(); p.ExecuteIntersectionQuery(p.GetExtents(), fds); p.Close(); } // add second datatable for multi-layer queries var l2 = CreateFeatureDataTable("layer 2"); l2.ExtendedProperties.Add("dummy", 5); fds.Tables.Add(l2); // add second datatable and relation var l3 = CreateFeatureDataTable("layer 3"); fds.Tables.Add(l3); fds.Relations.Add(l2.Columns["oid"], l3.Columns["oid"]); FeatureDataSet deserializedFds = null; Assert.DoesNotThrow(() => deserializedFds = SandD(fds, GetFormatter())); Assert.That(deserializedFds.Namespace, Is.EqualTo(fds.Namespace)); Assert.That(deserializedFds.DataSetName, Is.EqualTo(fds.DataSetName)); Assert.That(deserializedFds.Locale, Is.EqualTo(fds.Locale)); Assert.That(deserializedFds.EnforceConstraints, Is.EqualTo(fds.EnforceConstraints)); Assert.That(deserializedFds.Prefix, Is.EqualTo(fds.Prefix)); Assert.That(deserializedFds.Tables.Count, Is.EqualTo(fds.Tables.Count)); var deserializedLayer2Table = deserializedFds.Tables.First(fdt => fdt.TableName == "layer 2"); var deserializedLayer3Table = deserializedFds.Tables.First(fdt => fdt.TableName == "layer 3"); Assert.That(deserializedLayer2Table.ExtendedProperties.ContainsKey("dummy"), "DataSet.ExtendedProperties not serialized"); Assert.That(deserializedLayer2Table.ExtendedProperties.ContainsValue("5")); Assert.That(deserializedFds.Relations.Count, Is.EqualTo(1), "Relations not serialized"); Assert.That(deserializedFds.Relations[0].ParentTable, Is.EqualTo(deserializedLayer2Table), "Wrong parent relation"); Assert.That(deserializedFds.Relations[0].ChildTable, Is.EqualTo(deserializedLayer3Table), "Wrong child relation"); Assert.That(deserializedLayer2Table.Constraints.Count, Is.EqualTo(1), "Constraints not serialized"); var cons = deserializedLayer2Table.Constraints[0] as UniqueConstraint; Assert.NotNull(cons, "Wrong contraint"); Assert.IsTrue(cons.IsPrimaryKey, "Constraint was a primary key"); }
public void TestQuery() { var p = new SharpMap.Data.Providers.WFS("http://geo.vliz.be/geoserver/wfs?service=WFS&request=GetCapabilities", "nsTmp", "elevation_10m", SharpMap.Data.Providers.WFS.WFSVersionEnum.WFS1_1_0); p.FeatureTypeInfo.Geometry._GeometryName = "the_geom"; //p.FeatureTypeInfo.Geometry._GeometryType = var ext = p.GetExtents(); var g = p.GetGeometriesInView(new GeoAPI.Geometries.Envelope(-90, 90, -180, 180)); Assert.That(g.Count > 0); var fds = new FeatureDataSet(); Assert.DoesNotThrow(() => p.ExecuteIntersectionQuery(p.GetExtents(), fds)); }
public void TestCreateJoin() { var fds = new FeatureDataSet {DataSetName = "Join"}; var ds = (DataSet) fds; var t1 = CreateFeatureDataTable("T1"); fds.Tables.Add(t1); Assert.AreEqual(1, ((DataSet)fds).Tables.Count); var t2 = CreateDataTable("T2"); ds.Tables.Add(t2); Assert.AreEqual(2, ds.Tables.Count); Assert.AreEqual(1, fds.Tables.Count); Assert.DoesNotThrow( () => fds.Relations.Add(t1.Columns[0], t2.Columns[0])); }
private static void TestProvider(IProvider provider, GpkgContent content) { int numFeatures = 0; Assert.DoesNotThrow(() => numFeatures = provider.GetFeatureCount(), "GetFeatureCount threw exception:\n\tConnection{0}\n\t{1}", provider.ConnectionID, content.TableName); var extent = provider.GetExtents(); Collection<uint> oids = null; Assert.DoesNotThrow(() => oids = provider.GetObjectIDsInView(extent), "GetObjectIDsInView threw exception:\n\tConnection{0}\n\t{1}", provider.ConnectionID, content.TableName); Assert.AreEqual(numFeatures, oids.Count); foreach (var oid in oids) { IGeometry geom = null; Assert.DoesNotThrow(() => geom = provider.GetGeometryByID(oid), "GetGeometryByID threw exception:\n\tConnection{0}\n\t{1}", provider.ConnectionID, content.TableName); FeatureDataRow feat = null; Assert.DoesNotThrow(() => feat = provider.GetFeature(oid), "GetFeature threw exception:\n\tConnection{0}\n\t{1}", provider.ConnectionID, content.TableName); Assert.IsTrue(geom.EqualsExact(feat.Geometry)); } Collection<IGeometry> geoms = null; Assert.DoesNotThrow(() => geoms = provider.GetGeometriesInView(extent), "GetFeature threw exception:\n\tConnection{0}\n\t{1}", provider.ConnectionID, content.TableName); Assert.AreEqual(numFeatures, geoms.Count); var fds = new FeatureDataSet(); Assert.DoesNotThrow(() => provider.ExecuteIntersectionQuery(extent, fds), "GetFeature threw exception:\n\tConnection{0}\n\t{1}", provider.ConnectionID, content.TableName); Assert.AreEqual(numFeatures, fds.Tables[0].Rows.Count); }
/// <summary> /// This method returns a FeatureDataTable containing all the rows from the shapefile that intersect the testGeometry. /// The ShapeFile.ExecuteIntersectionQuery method only tests bounding boxes so we use the FilterDelegate property to add a true /// intersection test using NetTopologySuite /// </summary> /// <param name="pathToShapefile">The path to the shapefile</param> /// <param name="testGeometry">The geometry that we want to test against</param> /// <returns></returns> public FeatureDataTable GetIntersectingFeaturesUsingFilterDelegate(string pathToShapefile, Geometry testGeometry) { //create a new shapefile provider using (ShapeFile shapefile = new ShapeFile(pathToShapefile)) { //create an nts GeometryFactory GeometryFactory geometryFactory = new GeometryFactory(); //convert the testGeometry into the equivalent NTS geometry GeoAPI.Geometries.IGeometry testGeometryAsNtsGeom = GeometryConverter.ToNTSGeometry(testGeometry, geometryFactory); Geometry check = GeometryConverter.ToSharpMapGeometry(testGeometryAsNtsGeom); if (!check.Equals(testGeometry)) throw new ApplicationException("conversion error"); //set the shapefile providers' FilterDelegate property to a new anonymous method //this delegate method will be called for each potential row shapefile.FilterDelegate = delegate(FeatureDataRow featureDataRow) { //get the geometry from the featureDataRow Geometry rowGeometry = featureDataRow.Geometry; //convert it to the equivalent NTS geometry GeoAPI.Geometries.IGeometry compareGeometryAsNtsGeometry = GeometryConverter.ToNTSGeometry(rowGeometry, geometryFactory); //do the test. Note that the testGeometryAsNtsGeometry is available here because it is //declared in the same scope as the anonymous method. bool intersects = testGeometryAsNtsGeom.Intersects(compareGeometryAsNtsGeometry); //return the result return intersects; }; //create a new FeatureDataSet FeatureDataSet featureDataSet = new FeatureDataSet(); //open the shapefile shapefile.Open(); //call ExecuteIntersectionQuery. The FilterDelegate will be used to limit the result set shapefile.ExecuteIntersectionQuery(testGeometry, featureDataSet); //close the shapefile shapefile.Close(); //return the populated FeatureDataTable return featureDataSet.Tables[0]; } }
private bool ProcessPoint(IProvider featureProvider, VectorLayer pointLayer, Point p, Dictionary <string, FeatureCountPair> map, Taxon taxon) { SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); featureProvider.ExecuteIntersectionQuery(p.GetBoundingBox(), ds); DataTable tbl = ds.Tables[0] as SharpMap.Data.FeatureDataTable; var found = false; for (int i = 0; i < tbl.Rows.Count; ++i) { var data = tbl.Rows[i] as FeatureDataRow; string featurekey = MakeFeatureKey(data, taxon); if (data.Geometry is MultiPolygon) { MultiPolygon mp = data.Geometry as MultiPolygon; foreach (SharpMap.Geometries.Polygon polygon in mp) { if (MapControl.PointInsidePolygon(p, polygon)) { IncrementFeaturePointCount(map, featurekey, data, taxon); found = true; } } } else if (data.Geometry is Polygon) { var polygon = data.Geometry as Polygon; if (MapControl.PointInsidePolygon(p, polygon)) { IncrementFeaturePointCount(map, featurekey, data, taxon); found = true; } } else { // ??? Dunno... IncrementFeaturePointCount(map, featurekey, data, taxon); found = true; } } return(found); }
public void TestExecuteIntersectionQueryAgainstEnvelopeEqualsGetOidsInView() { using (var p = CreateProvider()) { var ext =p.GetExtents(); var fds = new FeatureDataSet(); Assert.DoesNotThrow(() => p.ExecuteIntersectionQuery(ext, fds)); Assert.AreEqual(1, fds.Tables.Count); var table = fds.Tables[0]; Assert.AreEqual(_tableName, table.TableName); Assert.AreEqual(4, table.Rows.Count); var oids = p.GetObjectIDsInView(ext); Assert.AreEqual(table.Rows.Count, oids.Count); foreach (FeatureDataRow row in table.Select()) Assert.IsTrue(oids.Contains((uint)(int)row[0])); } }
public void ExecuteIntersectionQueryReturnsExpectedFeatures() { DataTable source = CreateDataTableSource(); DataTablePoint provider = new DataTablePoint(source, "oid", "x", "y"); var query = new Envelope(400, 600, 400, 600); FeatureDataTable expected = new FeatureDataTable(); expected.TableName = "PointSource"; foreach (DataColumn column in source.Columns) { expected.Columns.Add(column.ColumnName, column.DataType); } foreach (DataRowView rowView in source.DefaultView) { if (query.Contains(new Coordinate((double) rowView["x"], (double) rowView["y"]))) { expected.ImportRow(rowView.Row); } } FeatureDataSet dataSet = new FeatureDataSet(); provider.ExecuteIntersectionQuery(query, dataSet); Assert.IsNotNull(dataSet); Assert.IsNotNull(dataSet.Tables); Assert.AreEqual(1, dataSet.Tables.Count); FeatureDataTable actual = dataSet.Tables[0]; Assert.AreEqual(expected.Rows.Count, actual.Rows.Count); foreach (DataRowView expectedRowView in expected.DefaultView) { DataRow[] actualRows = actual.Select("oid = " + expectedRowView["oid"]); Assert.AreEqual(1, actualRows.Length); Assert.AreEqual(expectedRowView["oid"], actualRows[0]["oid"]); Assert.AreEqual(expectedRowView["x"], actualRows[0]["x"]); Assert.AreEqual(expectedRowView["y"], actualRows[0]["y"]); } }
public void TestCreateFromFeatureDataTable(string filePath) { var fds = new SharpMap.Data.FeatureDataSet(); filePath = filePath.Replace("\\", new string(System.IO.Path.DirectorySeparatorChar, 1)); if (!System.IO.File.Exists(filePath)) { throw new IgnoreException($"'{filePath}' not found."); } FeatureDataTable fdt = null; try { var p = new Ogr(filePath); p.SRID = 4326; var layer = string.Empty; if (!string.IsNullOrEmpty(layer)) { p.LayerName = layer; } p.ExecuteIntersectionQuery(p.GetExtents(), fds); fdt = fds.Tables[0]; if (fdt.Rows.Count == 0) { throw new Exception("no data in layer"); } } catch (Exception ex) { throw new IgnoreException("Getting data failed", ex); } Assert.DoesNotThrow(() => Ogr.CreateFromFeatureDataTable(fdt, ((FeatureDataRow)fdt.Rows[0]).Geometry.OgcGeometryType, 4326, "Mapinfo File", filePath)); }
public JsonResult GetData(string layer, int z, int x, int y) { if (String.IsNullOrEmpty(layer)) throw new ArgumentNullException("layer"); Map map = ShapefileHelper.Spherical(); IQueryable<VectorLayer> coll = map.Layers .AsQueryable() .OfType<VectorLayer>() .Where(l => l.Enabled && l.IsQueryEnabled) .Where(l => String.Equals(l.LayerName, layer)); VectorLayer query = coll.SingleOrDefault(); if (query == null) throw new ArgumentException("Layer not found: " + layer); if (query.SRID != 4326) throw new ArgumentException("Only EPSG:4326 supported"); using (Utf8Grid grid = new Utf8Grid(UtfGridResolution, x, y, z)) { Envelope bbox = this.GetBoundingBoxInLatLngWithMargin(x, y, z); FeatureDataSet ds = new FeatureDataSet(); query.ExecuteIntersectionQuery(bbox, ds); IEnumerable<GeoJSON> data = GeoJSONHelper.GetData(ds); int i = 1; foreach (GeoJSON val in data) { IGeometry geom = val.Geometry; IDictionary<string, object> dict = val.Values; grid.FillPolygon(geom, i, dict); i = i + 1; } Utf8GridResults results = grid.CreateUtfGridJson(); return this.Json(new { keys = results.Keys, data = results.Data, grid = results.Grid, }, JsonRequestBehavior.AllowGet); } }
private IEnumerable<GeoJSON> GeoData(Map map, BoundingBox bbox) { List<GeoJSON> items = new List<GeoJSON>(); // Only queryable data! IQueryable<ICanQueryLayer> collection = 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); // 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); } return items; }
public void TestCreateFromFeatureDataTable(string filePath, int srid, string driver, string connection) { var fds = new SharpMap.Data.FeatureDataSet(); if (!Path.IsPathRooted(filePath)) filePath = TestUtility.GetPathToTestFile(filePath); if (!System.IO.File.Exists(filePath)) throw new IgnoreException($"'{filePath}' not found."); FeatureDataTable fdt = null; try { var p = new OgrProvider(filePath); if (p.SRID == 0) p.SRID = srid; else srid = p.SRID; string layer = string.Empty; if (!string.IsNullOrEmpty(layer)) p.LayerName = layer; p.ExecuteIntersectionQuery(p.GetExtents(), fds); fdt = fds.Tables[0]; if (fdt.Rows.Count == 0) throw new Exception("no data in layer"); p.Dispose(); } catch (Exception ex) { throw new IgnoreException("Getting data failed", ex); } Assert.DoesNotThrow(() => OgrProvider.CreateFromFeatureDataTable(fdt, ((FeatureDataRow)fdt.Rows[0]).Geometry.OgcGeometryType, srid, driver, connection)); }
void ICanQueryLayer.ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { if (!((ICanQueryLayer)this).IsQueryEnabled) return; ((ICanQueryLayer)_baseLayer).ExecuteIntersectionQuery(box, ds); }
public void RenderLayer(IVectorLayer layer, Map map, System.Drawing.Graphics g) { if (map.Center == null) { throw (new ApplicationException("Cannot render map. View center not specified")); } 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()); } //List<SharpMap.Geometries.Geometry> features = this.DataSource.GetGeometriesInView(map.Envelope); if (layer.DataSource == null) { throw (new ApplicationException("DataSource property not set on layer '" + layer.LayerName + "'")); } //If thematics is enabled, we use a slighty different rendering approach if (layer.Theme != null) { SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); layer.DataSource.Open(); layer.DataSource.ExecuteIntersectionQuery(envelope, ds); layer.DataSource.Close(); FeatureDataTable features = (FeatureDataTable)ds.Tables[0]; if (layer.CoordinateTransformation != null) { for (int i = 0; i < features.Count; i++) { features[i].Geometry = GeometryTransform.TransformGeometry(features[i].Geometry, layer.CoordinateTransformation.MathTransform); } } //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (layer.Style.EnableOutline) { //foreach (SharpMap.Geometries.Geometry feature in features) for (int i = 0; i < features.Count; i++) { SharpMap.Data.FeatureDataRow feature = features[i]; //Draw background of all line-outlines first if (feature.Geometry is SharpMap.Geometries.LineString) { IVectorStyle outlinestyle1 = layer.Theme.GetStyle(feature); if (outlinestyle1.Enabled && outlinestyle1.EnableOutline) { SharpMap.Rendering.VectorRenderer.DrawLineString(g, feature.Geometry as LineString, outlinestyle1.Outline, map); } } else if (feature.Geometry is SharpMap.Geometries.MultiLineString) { IVectorStyle outlinestyle2 = layer.Theme.GetStyle(feature); if (outlinestyle2.Enabled && outlinestyle2.EnableOutline) { SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlinestyle2.Outline, map); } } } } for (int i = 0; i < features.Count; i++) { SharpMap.Data.FeatureDataRow feature = features[i]; IVectorStyle style = layer.Theme.GetStyle(feature); RenderGeometry(g, map, layer.ClippingEnabled, feature.Geometry, style); } } else { layer.DataSource.Open(); Collection <Geometry> geoms = layer.DataSource.GetGeometriesInView(envelope); layer.DataSource.Close(); if (layer.CoordinateTransformation != null) { for (int i = 0; i < geoms.Count; i++) { geoms[i] = GeometryTransform.TransformGeometry(geoms[i], layer.CoordinateTransformation.MathTransform); } } //Linestring outlines is drawn by drawing the layer once with a thicker line //before drawing the "inline" on top. if (layer.Style.EnableOutline) { foreach (SharpMap.Geometries.Geometry geom in geoms) { if (geom != null) { //Draw background of all line-outlines first switch (geom.GetType().FullName) { case "SharpMap.Geometries.LineString": SharpMap.Rendering.VectorRenderer.DrawLineString(g, geom as LineString, layer.Style.Outline, map); break; case "SharpMap.Geometries.MultiLineString": SharpMap.Rendering.VectorRenderer.DrawMultiLineString(g, geom as MultiLineString, layer.Style.Outline, map); break; default: break; } } } } for (int i = 0; i < geoms.Count; i++) { if (geoms[i] != null) { RenderGeometry(g, map, layer.ClippingEnabled, geoms[i], layer.Style); } } } //base.Render(g, map); }
public void ExecuteIntersectionQuery(SharpMap.Geometries.Geometry geom, SharpMap.Data.FeatureDataSet ds) { ExecuteIntersectionQuery(geom.GetBoundingBox(), ds); }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="geometry">Geometry to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Geometry geometry, FeatureDataSet ds) { if (CoordinateTransformation != null) { #if !DotSpatialProjections CoordinateTransformation.MathTransform.Invert(); geometry = GeometryTransform.TransformGeometry(geometry, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); #else geometry = GeometryTransform.TransformGeometry(geometry, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } lock (_dataSource) { _dataSource.Open(); _dataSource.ExecuteIntersectionQuery(geometry, ds); _dataSource.Close(); } }
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; //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); } } }
/// <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(); DataSource.Open(); DataSource.ExecuteIntersectionQuery(envelope, ds); DataSource.Close(); FeatureDataTable features = ds.Tables[0]; 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); } else if (feature.Geometry is MultiLineString) { VectorRenderer.DrawMultiLineString(g, feature.Geometry as MultiLineString, outlineStyle.Outline, map); } } } 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; DataSource.Open(); Collection<Geometry> geoms = DataSource.GetGeometriesInView(envelope); 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); else if (geom is MultiLineString) VectorRenderer.DrawMultiLineString(g, geom as MultiLineString, Style.Outline, map); } } } for (int i = 0; i < geoms.Count; i++) { if (geoms[i] != null) RenderGeometry(g, map, geoms[i], Style); } } base.Render(g, map); }
private void mapImage_MapQueriedDataSet(SharpMap.Data.FeatureDataSet data) { dataGridView1.DataSource = data as System.Data.DataSet; }
private void ExecuteIntersectionQuery(Coordinate pt, FeatureDataSet ds) { if (CoordinateTransformation != null) { #if !DotSpatialProjections if (ReverseCoordinateTransformation != null) { pt = GeometryTransform.TransformCoordinate(pt, ReverseCoordinateTransformation.MathTransform); } else { CoordinateTransformation.MathTransform.Invert(); pt = GeometryTransform.TransformCoordinate(pt, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); } #else pt = GeometryTransform.TransformCoordinate(pt, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } //Setup resulting Table var dt = new FeatureDataTable(); dt.Columns.Add("Ordinate X", typeof(Double)); dt.Columns.Add("Ordinate Y", typeof(Double)); for (int i = 1; i <= Bands; i++) dt.Columns.Add(string.Format("Value Band {0}", i), typeof(Double)); //Get location on raster Double[] buffer = new double[1]; Int32[] bandMap = new int[Bands]; for (int i = 1; i <= Bands; i++) bandMap[i - 1] = i; var geoTransform = new GeoTransform(_gdalDataset); var imgPt = geoTransform.GroundToImage(pt); Int32 x = Convert.ToInt32(imgPt.X); Int32 y = Convert.ToInt32(imgPt.Y); //Test if raster ordinates are within bounds if (x < 0) return; if (y < 0) return; if (x >= _imageSize.Width) return; if (y >= _imageSize.Height) return; //Create new row, add ordinates and location geometry FeatureDataRow dr = dt.NewRow(); dr.Geometry = Factory.CreatePoint(pt); dr[0] = pt.X; dr[1] = pt.Y; //Add data from raster for (int i = 1; i <= Bands; i++) { Band band = _gdalDataset.GetRasterBand(i); //DataType dtype = band.DataType; CPLErr res = band.ReadRaster(x, y, 1, 1, buffer, 1, 1, 0, 0); if (res == CPLErr.CE_None) { dr[1 + i] = buffer[0]; } else { dr[1 + i] = Double.NaN; } } //Add new row to table dt.Rows.Add(dr); //Add table to dataset ds.Tables.Add(dt); }
public FeatureDataViewManager(FeatureDataSet dataSet, Boolean locked) { throw new NotImplementedException(); }
/// <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(); }
void ICanQueryLayer.ExecuteIntersectionQuery(IGeometry geometry, FeatureDataSet ds) { if (!((ICanQueryLayer)this).IsQueryEnabled) return; ((ICanQueryLayer)_baseLayer).ExecuteIntersectionQuery(geometry, ds); }
/// <summary> /// Copies the structure of the FeatureDataSet, /// including all FeatureDataTable schemas, relations, /// and constraints. Does not copy any data. /// </summary> /// <returns></returns> public new FeatureDataSet Clone() { FeatureDataSet copy = base.Clone() as FeatureDataSet; return(copy); }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="geometry">Geometry to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(IGeometry geometry, FeatureDataSet ds) { foreach (Layer layer in Layers) { if (layer is ICanQueryLayer) { FeatureDataSet dsTmp = new FeatureDataSet(); ((ICanQueryLayer)layer).ExecuteIntersectionQuery(geometry, dsTmp); ds.Tables.AddRange(dsTmp.Tables.ToArray()); } } }
/// <summary> /// Copies the structure of the FeatureDataSet, including all FeatureDataTable schemas, relations, and constraints. Does not copy any data. /// </summary> /// <returns></returns> public new FeatureDataSet Clone() { FeatureDataSet cln = ((FeatureDataSet)(base.Clone())); return(cln); }
public override void Render(IGraphics g, Map 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 (_logger.IsDebugEnabled) _logger.Debug("Drawing " + file); OpenDataset(file); base.Render(g, map); _envelope = null; if (_gdalDataset != null) { _gdalDataset.Dispose(); _gdalDataset = null; } } } } catch (Exception) { _shapeFile.Close(); } }
private static IEnumerable<GeoJSON> QueryData(BoundingBox bbox, ICanQueryLayer layer) { if (layer == null) throw new ArgumentNullException("layer"); // Query for data FeatureDataSet ds = new FeatureDataSet(); layer.ExecuteIntersectionQuery(bbox, ds); IEnumerable<GeoJSON> data = GeoJSONHelper.GetData(ds); // 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) { GeometryFactory gf = new GeometryFactory(); data = data.Select(d => { Geometry converted = GeometryTransform.TransformGeometry(d.Geometry, transform, gf); d.SetGeometry(converted); return d; }); } return data; }
/// <summary> /// Returns the data associated with the centroid of the bounding box. /// </summary> /// <param name="box">Envelope to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Envelope box, FeatureDataSet ds) { var pt = new Coordinate(box.MinX + 0.5 * box.Width, box.MaxY - 0.5 * box.Height); ExecuteIntersectionQuery(pt, ds); }
private FeatureDataRow FindGeoNearPoint(object/*Coordinate*/ coord) { var mapPosition = (Coordinate) coord; var env = new Envelope(mapPosition); env.ExpandBy(5 * Map.PixelWidth); var g = NetTopologySuite.Geometries.Prepared.PreparedGeometryFactory.Prepare(Map.Factory.ToGeometry(env)); var fdrs = new List<Tuple<double, FeatureDataRow>>(); var fds = new FeatureDataSet(); var tableCount = 0; var layersToQuery = GetLayersToQuery(Map); for (var i = layersToQuery.Count - 1; i >= 0; i--) { if (_cts.Token.IsCancellationRequested) { Logger.Debug("Cancellation requested"); return null; } var l = layersToQuery[i]; if (l.Enabled && l.MinVisible < Map.Zoom && l.MaxVisible >= Map.Zoom) { if (!l.IsQueryEnabled) continue; l.ExecuteIntersectionQuery(env, fds); for (var j = tableCount; j < fds.Tables.Count; j++) { var fdt = fds.Tables[j]; for (var k = 0; k < fdt.Rows.Count; k++) { var fdr = (FeatureDataRow) fdt.Rows[k]; if (g.Intersects(fdr.Geometry)) { var distance = g.Geometry.InteriorPoint.Distance(fdr.Geometry); if (fdr.Geometry.Dimension == Dimension.Surface) distance += 5* Map.PixelWidth; fdrs.Add(Tuple.Create(distance, fdr)); } } } tableCount = fds.Tables.Count; } } if (fdrs.Count > 0) { fdrs.Sort((t1, t2) => t1.Item1.CompareTo(t2.Item1)); return fdrs[0].Item2; } return null; }
/// <summary> /// Returns the data associated with all the geometries that are intersected by 'geom' /// </summary> /// <param name="geometry">Geometry to intersect with</param> /// <param name="ds">FeatureDataSet to fill data into</param> public void ExecuteIntersectionQuery(Geometry geometry, FeatureDataSet ds) { ExecuteIntersectionQuery(geometry.EnvelopeInternal, 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(BoundingBox box, FeatureDataSet ds) { if (CoordinateTransformation != null) { #if !DotSpatialProjections CoordinateTransformation.MathTransform.Invert(); box = GeometryTransform.TransformBox(box, CoordinateTransformation.MathTransform); CoordinateTransformation.MathTransform.Invert(); #else box = GeometryTransform.TransformBox(box, CoordinateTransformation.Target, CoordinateTransformation.Source); #endif } _dataSource.Open(); _dataSource.ExecuteIntersectionQuery(box, ds); _dataSource.Close(); }