Ejemplo n.º 1
0
        /// <summary>
        /// 通过射线来判定第一个相交的要素
        /// </summary>
        /// <param name="ray"></param>
        /// <returns></returns>
        public bool GetSelectedFeatureByRayCasting(Ray ray)
        {
            //计算Ray于地球的交点
            bool isIntersect = _scene.Ellipsoid.Intersections(ray, out Geodetic2D result);

            //ImGui.Text(string.Format("Latitude:{0},logitude:{1}",result.Latitude,result.Longitude));
            SelectedFeatures.Clear();
            var geoFactory = new NetTopologySuite.Geometries.GeometryFactory();

            if (isIntersect)
            {
                //是否考虑根据当前精度生成一个合适的Enve
                //这里一律采用0.001经纬度的精度
                var env        = new GeoAPI.Geometries.Envelope(new Coordinate(result.Longitude * 180 / Math.PI - 0.001, result.Latitude * 180 / Math.PI - 0.001), new Coordinate(result.Longitude * 180 / Math.PI + 0.001, result.Latitude * 180 / Math.PI + 0.001));
                var selectedff = _quadTree.Query(env);
                foreach (var item in selectedff)
                {
                    if (item.Geometry.Intersects(geoFactory.ToGeometry(env)))
                    {
                        SelectedFeatures.Add(item);
                    }
                }
                return(true);
            }
            return(false);
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        /// <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 override void ExecuteIntersectionQuery(BoundingBox bbox, FeatureDataSet ds)
        {
            DataRow[] rows;

            if (Table.Rows.Count == 0)
            {
                return;
            }

            string statement = XColumn + " >= " + bbox.MinX.ToString("R", Map.NumberFormatEnUs) + " AND " +
                               XColumn + " <= " + bbox.MaxX.ToString("R", Map.NumberFormatEnUs) + " AND " +
                               YColumn + " >= " + bbox.MinY.ToString("R", Map.NumberFormatEnUs) + " AND " +
                               YColumn + " <= " + bbox.MaxY.ToString("R", 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 = Factory.CreatePoint(new Coordinate((double)dr[XColumn], (double)dr[YColumn]));
            }

            ds.Tables.Add(fdt);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns geometries within the specified bounding box
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection <Geometry> GetGeometriesInView(BoundingBox bbox)
        {
            var geoms = new Collection <Geometry>();

            OgrDataSource ogrDataSource;

            using (var ogrLayer = GetLayer(_layerIndex, out ogrDataSource))
            {
                ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
                try
                {
                    var        reader = new OgrGeometryReader(Factory);
                    OgrFeature ogrFeature;
                    while ((ogrFeature = ogrLayer.GetNextFeature()) != null)
                    {
                        using (var gr = ogrFeature.GetGeometryRef())
                        {
                            //var geom = ParseOgrGeometry(gr, Factory);
                            var geom = reader.Read(gr);
                            if (geom != null)
                            {
                                geoms.Add(geom);
                            }
                        }
                        ogrFeature.Dispose();
                    }
                    ogrDataSource.Dispose();
                }
                catch (Exception ex)
                {
                    _log.Debug(t => t(ex.Message));
                }
            }
            return(geoms);
        }
        /// <summary>
        /// Returns the data associated with all the geometries that are intersected by 'geom'
        /// </summary>
        /// <param name="bbox">Geometry to intersect with</param>
        public virtual IEnumerable <IFeature> GetFeatures(Envelope bbox)
        {
            ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            ogrLayer.ResetReading();
            FeatureDataTable featureDataTable = CreateFeatureDataTableStructure();

            try
            {
                int featureCount = (int)ogrLayer.GetFeatureCount(1);
                for (int i = 0; i < featureCount; i++)
                {
                    using (var ogrFeature = ogrLayer.GetNextFeature())
                    {
                        if (ogrFeature == null)
                        {
                            break;
                        }
                        FeatureDataRow feature = featureDataTable.NewRow();
                        feature.Id = ogrFeature.GetFID();
                        SetFeatureValuesInRow(featureDataTable, ogrFeature, feature);
                        feature.Geometry = ParseOgrGeometry(ogrFeature.GetGeometryRef());
                        featureDataTable.AddRow(feature);
                    }
                }
            }
            catch (ApplicationException e)
            {
                throw new IOException(string.Format("Unable to read the following file: {0}", path), e);
            }

            return(featureDataTable);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Returns geometries within the specified bounding box
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection <Geometry> GetGeometriesInView(BoundingBox bbox)
        {
            var geoms = new Collection <Geometry>();

            _ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            _ogrLayer.ResetReading();

            try
            {
                OgrFeature ogrFeature;
                while ((ogrFeature = _ogrLayer.GetNextFeature()) != null)
                {
                    using (var gr = ogrFeature.GetGeometryRef())
                    {
                        var geom = ParseOgrGeometry(gr, Factory);
                        if (geom != null)
                        {
                            geoms.Add(geom);
                        }
                    }
                    ogrFeature.Dispose();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return(geoms);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Boundingbox of dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public GeoAPI.Geometries.Envelope GetExtents()
        {
            GeoAPI.Geometries.Envelope box = null;
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(_ConnectionString))
            {
                string strSQL = "Select Min(" + this.XColumn + ") as MinX, Min(" + this.YColumn + ") As MinY, " +
                                "Max(" + this.XColumn + ") As MaxX, Max(" + this.YColumn + ") As MaxY FROM " + this.Table;
                if (!String.IsNullOrEmpty(_defintionQuery))                 //If a definition query has been specified, add this as a filter on the query
                {
                    strSQL += " WHERE " + _defintionQuery;
                }

                using (System.Data.OleDb.OleDbCommand command = new OleDbCommand(strSQL, conn))
                {
                    conn.Open();
                    using (System.Data.OleDb.OleDbDataReader dr = command.ExecuteReader())
                    {
                        if (dr.Read())
                        {
                            //If the read row is OK, create a point geometry from the XColumn and YColumn and return it
                            if (dr[0] != DBNull.Value && dr[1] != DBNull.Value && dr[2] != DBNull.Value && dr[3] != DBNull.Value)
                            {
                                box = SharpMap.Converters.Geometries.GeometryFactory.CreateEnvelope((double)dr[0], (double)dr[1], (double)dr[2], (double)dr[3]);
                            }
                        }
                    }
                    conn.Close();
                }
            }
            return(box);
        }
Ejemplo n.º 8
0
        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);
        }
Ejemplo n.º 9
0
        public void TestGetExtents()
        {
            var sq = GetTestProvider();

            GeoAPI.Geometries.Envelope extents = sq.GetExtents();

            Assert.IsNotNull(extents);
        }
Ejemplo n.º 10
0
 public void TestGetExtents()
 {
     foreach (var sq in GetTestProvider())
     {
         GeoAPI.Geometries.Envelope extents = sq.GetExtents();
         Assert.IsNotNull(extents);
     }
 }
Ejemplo n.º 11
0
        public AgsMap(AgsDataFrame dataFrame, int width, int height, GeoAPI.Geometries.Envelope extent)
        {
            _service = dataFrame.Service as AgsMapService;

            DataFrame = dataFrame;
            Width     = width;
            Height    = height;
            Extent    = extent;
        }
        /// <summary>
        /// Transforms a <see cref="BoundingBox"/>
        /// </summary>
        /// <param name="box">Geometry to transform</param>
        /// <param name="from">Source Projection</param>
        /// <param name="to">Target Projection</param>
        /// <returns>Transformed BoundingBox</returns>
        public static BoundingBox TransformBox(BoundingBox box, ProjectionInfo from, ProjectionInfo to)
        {
            var corners = new[] { box.MinX, box.MinY, box.MinX, box.MaxY, box.MaxX, box.MaxY, box.MaxX, box.MinY };
            Reproject.ReprojectPoints(corners, null, from, to, 0, 4);

            var res = new BoundingBox(corners[0], corners[4], corners[1], corners[5]);
            res.ExpandToInclude(new BoundingBox(corners[2], corners[6], corners[3], corners[7]));
            return res;
        }
Ejemplo n.º 13
0
        public void GetExtents_ValidDatasource()
        {
            Map         map    = new Map(new Size(400, 200));
            VectorLayer vLayer = new VectorLayer("Geom layer", CreateDatasource());

            map.Layers.Add(vLayer);
            BoundingBox box = map.GetExtents();

            Assert.AreEqual(new BoundingBox(0, 50, 0, 346.3493254), box);
        }
Ejemplo n.º 14
0
 public override Collection<uint> GetObjectIDsInView(BoundingBox bbox)
 {
     var res = new Collection<uint>();
     foreach (var kvp in Matrix)
     {
         if (bbox.Intersects(kvp.Value.EnvelopeInternal))
             res.Add(kvp.Key);
     }
     return res;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Returns the data associated with all the geometries that are intersected by 'geom'
        /// </summary>
        /// <param name="bbox">Geometry to intersect with</param>
        /// <param name="ds">FeatureDataSet to fill data into</param>
        public override void ExecuteIntersectionQuery(BoundingBox bbox, FeatureDataSet ds)
        {
            OgrDataSource ogrDataSource;

            using (var ogrLayer = GetLayer(_layerIndex, out ogrDataSource))
            {
                ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
                ExecuteIntersectionQuery(ds, ogrLayer);
                ogrDataSource.Dispose();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Transforms a <see cref="BoundingBox"/>
        /// </summary>
        /// <param name="box">Geometry to transform</param>
        /// <param name="from">Source Projection</param>
        /// <param name="to">Target Projection</param>
        /// <returns>Transformed BoundingBox</returns>
        public static BoundingBox TransformBox(BoundingBox box, ProjectionInfo from, ProjectionInfo to)
        {
            var corners = new[] { box.MinX, box.MinY, box.MinX, box.MaxY, box.MaxX, box.MaxY, box.MaxX, box.MinY };

            Reproject.ReprojectPoints(corners, null, from, to, 0, 4);

            var res = new BoundingBox(corners[0], corners[4], corners[1], corners[5]);

            res.ExpandToInclude(new BoundingBox(corners[2], corners[6], corners[3], corners[7]));
            return(res);
        }
Ejemplo n.º 17
0
        public override Collection <uint> GetObjectIDsInView(BoundingBox bbox)
        {
            var res = new Collection <uint>();

            foreach (var kvp in Matrix)
            {
                if (bbox.Intersects(kvp.Value.EnvelopeInternal))
                {
                    res.Add(kvp.Key);
                }
            }
            return(res);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Returns features within the specified bounding box.
        /// </summary>
        /// <param name="envelope"></param>
        /// <returns></returns>
        public override Collection <Geometry> GetGeometriesInView(BoundingBox envelope)
        {
            // Identifies all the features within the given BoundingBox
            var geoms = new Collection <Geometry>();

            foreach (var feature in _features)
            {
                if (envelope.Intersects(feature.Geometry.EnvelopeInternal))
                {
                    geoms.Add(feature.Geometry);
                }
            }
            return(geoms);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection <uint> GetObjectIDsInView(BoundingBox bbox)
        {
            _ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            _ogrLayer.ResetReading();

            var        objectIDs = new Collection <uint>();
            OgrFeature ogrFeature;

            while ((ogrFeature = _ogrLayer.GetNextFeature()) != null)
            {
                objectIDs.Add((uint)ogrFeature.GetFID());
                ogrFeature.Dispose();
            }
            return(objectIDs);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the object IDs in the view.
        /// </summary>
        /// <param name="bbox">The bbox.</param>
        /// <param name="ct">A cancellation token</param>
        /// <returns></returns>
        public override IEnumerable <object> GetOidsInView(BoundingBox bbox, CancellationToken?ct = null)
        {
            // Identifies all the features within the given BoundingBox
            Envelope envelope = bbox;
            var      geoms    = new Collection <object>();

            for (int i = 0; i < _features.Count; i++)
            {
                if (envelope.Intersects(_features[i].Geometry.EnvelopeInternal))
                {
                    geoms.Add(Convert.ToUInt32(i));
                }
            }
            return(geoms);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Gets the object IDs in the view.
        /// </summary>
        /// <param name="bbox">The bbox.</param>
        /// <returns></returns>
        public override Collection <uint> GetObjectIDsInView(BoundingBox bbox)
        {
            // Identifies all the features within the given BoundingBox
            Envelope          envelope = bbox;
            Collection <uint> geoms    = new Collection <uint>();

            for (int i = 0; i < _features.Count; i++)
            {
                if (envelope.Intersects(_features[i].Geometry.EnvelopeInternal))
                {
                    geoms.Add(Convert.ToUInt32(i));
                }
            }
            return(geoms);
        }
        private void FormMovingObjectOverTileLayer_Load(object sender, EventArgs e)
        {
            //Lisbon...
            var mathTransform = LayerTools.Wgs84toGoogleMercator.MathTransform;

            GeoAPI.Geometries.Envelope geom = GeometryTransform.TransformBox(
                new Envelope(-9.205626, -9.123736, 38.690993, 38.740837),
                mathTransform);

            var map = new SharpMap.Map();
            //Google Background
            TileAsyncLayer layer2 = new TileAsyncLayer(KnownTileSources.Create(KnownTileSource.BingRoads), "TileLayer - Bing");

            map.BackgroundLayer.Add(layer2);

            var gf = new GeometryFactory(new PrecisionModel(), 3857);

            //Adds a static layer
            var staticLayer = new VectorLayer("Fixed Marker");
            //position = geom.GetCentroid();
            var aux = new List <IGeometry>();

            aux.Add(gf.CreatePoint(geom.Centre));
            staticLayer.Style.Symbol = Resources.PumpSmall;
            var geoProviderFixed = new SharpMap.Data.Providers.GeometryProvider(aux);

            staticLayer.DataSource = geoProviderFixed;
            map.Layers.Add(staticLayer);


            //Adds a moving variable layer
            VectorLayer pushPinLayer = new VectorLayer("PushPins");

            position = geom.Centre;
            geos.Add(gf.CreatePoint(position));
            pushPinLayer.Style.Symbol = Resources.OutfallSmall;
            var geoProvider = new SharpMap.Data.Providers.GeometryProvider(geos);

            pushPinLayer.DataSource = geoProvider;
            map.VariableLayers.Add(pushPinLayer);

            map.ZoomToBox(geom);


            this.mapBox1.Map = map;

            this.mapBox1.Refresh();
        }
        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public virtual Envelope GetExtents()
        {
            if (this.envelope == null)
            {
                using (var ogrEnvelope = new OgrEnvelope())
                {
                    int i = ogrLayer.GetExtent(ogrEnvelope, 1);

                    envelope = new Envelope(ogrEnvelope.MinX, ogrEnvelope.MaxX,
                                            ogrEnvelope.MinY, ogrEnvelope.MaxY);
                }
            }


            return(envelope);
        }
Ejemplo n.º 24
0
        public override Collection<Geometry> GetGeometriesInView(BoundingBox bbox)
        {
            var res = new Collection<Geometry>();
            foreach (var origin in Matrix)
            {
                if (!bbox.Intersects(origin.Value.EnvelopeInternal))
                    continue;

                var val = Matrix[origin.Key, MatrixVector];
                if (!Valid(val))
                    continue;
                var sval = Scale(val);
                res.Add(CreateCircle(origin.Value, sval));
            }
            return res;
        }
Ejemplo n.º 25
0
        ///// <summary>
        ///// Loads a Ogr datasource with the first layer
        ///// </summary>
        ///// <param name="datasource">datasource</param>
        ///// <param name="name">Returns the name of the loaded layer</param>
        /////<remarks>
        /////This constructor is obsolete!
        /////If you want this functionality use
        /////<example>
        /////SharpMap.Data.Providers.Ogr prov = new SharpMap.Data.Providers.Ogr(datasource);
        /////string layerName = prov.Layername;
        /////</example>
        /////</remarks>
        //[Obsolete("This constructor does not work well with VB.NET. Use LayerName property instead")]
        //public Ogr(string datasource, out string name)
        //    : this(datasource, 0, out name)
        //{
        //}

        #endregion

        #region IProvider Members

        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public override BoundingBox GetExtents()
        {
            if (_bbox == null)
            {
                OgrEnvelope ogrEnvelope = new OgrEnvelope();
                if (_ogrLayer != null)
                {
                    _ogrLayer.GetExtent(ogrEnvelope, 1);
                }

                _bbox = new BoundingBox(ogrEnvelope.MinX, ogrEnvelope.MaxX,
                                        ogrEnvelope.MinY, ogrEnvelope.MaxY);
            }

            return(_bbox);
        }
Ejemplo n.º 26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="envelope"></param>
        /// <param name="ds"></param>
        public override void ExecuteIntersectionQuery(BoundingBox envelope, FeatureDataSet ds)
        {
            // Identifies all the features within the given BoundingBox
            var dataTable = CreateFeatureDataTable();

            dataTable.BeginLoadData();
            foreach (Feature feature in _features)
            {
                if (envelope.Intersects(feature.Geometry.EnvelopeInternal))
                {
                    CreateNewRow(dataTable, feature);
                }
            }
            dataTable.EndLoadData();

            ds.Tables.Add(dataTable);
        }
Ejemplo n.º 27
0
        ///// <summary>
        ///// Loads a Ogr datasource with the first layer
        ///// </summary>
        ///// <param name="datasource">datasource</param>
        ///// <param name="name">Returns the name of the loaded layer</param>
        /////<remarks>
        /////This constructor is obsolete!
        /////If you want this functionality use
        /////<example>
        /////SharpMap.Data.Providers.Ogr prov = new SharpMap.Data.Providers.Ogr(datasource);
        /////string layerName = prov.Layername;
        /////</example>
        /////</remarks>
        //[Obsolete("This constructor does not work well with VB.NET. Use LayerName property instead")]
        //public Ogr(string datasource, out string name)
        //    : this(datasource, 0, out name)
        //{
        //}

        #endregion

        #region IProvider Members

        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public override BoundingBox GetExtents()
        {
            if (_bbox == null)
            {
                OgrEnvelope ogrEnvelope = new OgrEnvelope();
                using (var ogrLayer = GetLayer(LayerIndex))
                {
                    if (ogrLayer != null)
                    {
                        ogrLayer.GetExtent(ogrEnvelope, 1);
                    }
                }

                _bbox = new BoundingBox(ogrEnvelope.MinX, ogrEnvelope.MaxX,
                                        ogrEnvelope.MinY, ogrEnvelope.MaxY);
            }

            return(_bbox);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection <uint> GetObjectIDsInView(BoundingBox bbox)
        {
            var           objectIDs = new Collection <uint>();
            OgrDataSource ogrDataSource;

            using (var ogrLayer = GetLayer(_layerIndex, out ogrDataSource))
            {
                ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);

                OgrFeature ogrFeature;
                while ((ogrFeature = ogrLayer.GetNextFeature()) != null)
                {
                    objectIDs.Add((uint)ogrFeature.GetFID());
                    ogrFeature.Dispose();
                }
                ogrDataSource.Dispose();
            }
            return(objectIDs);
        }
Ejemplo n.º 29
0
        public override GeoAPI.Geometries.Envelope GetFeatureExtent(string where)
        {
            FieldSelection fieldSelection = new FieldSelection(this, GeometryField.Name);
            QueryFilter    queryFilter    = new QueryFilter(GeometryField.Name, where);
            RecordSet      recordSet      = _service.MapServer.QueryFeatureData(DataFrame.Name, _mapLayerInfo.LayerID, queryFilter);
            DataTable      table          = RecordSetToTable(recordSet, fieldSelection);

            GeoAPI.Geometries.Envelope extent = new GeoAPI.Geometries.Envelope();

            foreach (DataRow row in table.Rows)
            {
                if (!row.IsNull(0))
                {
                    extent.ExpandToInclude(((IGeometry)row[0]).EnvelopeInternal);
                }
            }

            return(extent);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Boundingbox of dataset
 /// </summary>
 /// <returns>boundingbox</returns>
 public GeoAPI.Geometries.Envelope GetExtents()
 {
     using (SqlConnection conn = new SqlConnection(_ConnectionString))
     {
         string strSQL = string.Format("SELECT ST.AsBinary(ST.EnvelopeQueryWhere('{0}', '{1}', '{2}'))", this.Table, this.GeometryColumn, this.DefinitionQuery.Replace("'", "''"));
         using (SqlCommand command = new SqlCommand(strSQL, conn))
         {
             conn.Open();
             object result = command.ExecuteScalar();
             conn.Close();
             if (result == System.DBNull.Value)
             {
                 return(null);
             }
             GeoAPI.Geometries.Envelope bbox = SharpMap.Converters.WellKnownBinary.GeometryFromWKB.Parse((byte[])result).EnvelopeInternal;
             return(bbox);
         }
     }
 }
Ejemplo n.º 31
0
        //void mapBox1_MouseClick(object sender, MouseEventArgs e)
        //{
        //    if (mouseState == "query")
        //    {
        //        GeoAPI.Geometries.Coordinate coord = this.mapBox1.Map.ImageToWorld(new PointF(e.X, e.Y));
        //        FeatureDataSet ds;
        //        ds = QueryMapByClick(coord);
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            string s = "";
        //            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
        //            {
        //                s = s + dr[i].ToString() + ",";
        //            }
        //            MessageBox.Show(s);
        //            //Console.WriteLine(s);
        //        }
        //    }

        //}

        private FeatureDataSet QueryMapByClick(GeoAPI.Geometries.Coordinate coord)
        {
            FeatureDataSet ds = new FeatureDataSet();

            SharpMap.Layers.VectorLayer vlayer = this.mapBox1.Map.Layers[0] as VectorLayer;
            if (!vlayer.DataSource.IsOpen)
            {
                vlayer.DataSource.Open();
            }

            GeoAPI.Geometries.Envelope env = new GeoAPI.Geometries.Envelope();
            env.Init(coord.X - 0.01, coord.X + 0.01, coord.Y - 0.01, coord.Y + 0.01);

            vlayer.DataSource.ExecuteIntersectionQuery(env, ds);
            if (ds.Tables.Count > 0)
            {
                ShowSelectLayer(ds.Tables[0]);
            }
            return(ds);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Transforms a <see cref="Envelope"/>.
        /// </summary>
        /// <param name="box">BoundingBox to transform</param>
        /// <param name="transform">Math Transform</param>
        /// <returns>Transformed object</returns>
        public static GeoAPI.Geometries.Envelope TransformBox(GeoAPI.Geometries.Envelope box, IMathTransform transform)
        {
            if (box == null)
            {
                return(null);
            }
            double[][] corners = new double[4][];
            corners[0] = transform.Transform(ToArray(box.MinX, box.MinY)); //LL
            corners[1] = transform.Transform(ToArray(box.MaxX, box.MaxY)); //UR
            corners[2] = transform.Transform(ToArray(box.MinX, box.MaxY)); //UL
            corners[3] = transform.Transform(ToArray(box.MaxX, box.MinY)); //LR

            Envelope result = GeometryFactory.CreateEnvelope();

            foreach (double[] p in corners)
            {
                result.ExpandToInclude(p[0], p[1]);
            }
            return(result);
        }
Ejemplo n.º 33
0
        public override Collection <Geometry> GetGeometriesInView(BoundingBox bbox)
        {
            var res = new Collection <Geometry>();

            foreach (var origin in Matrix)
            {
                if (!bbox.Intersects(origin.Value.EnvelopeInternal))
                {
                    continue;
                }

                var val = Matrix[origin.Key, MatrixVector];
                if (!Valid(val))
                {
                    continue;
                }
                var sval = Scale(val);
                res.Add(CreateCircle(origin.Value, sval));
            }
            return(res);
        }
Ejemplo n.º 34
0
        private string BuildEnvelope(GeoAPI.Geometries.Envelope bbox)
        {
/*
 *                      if (this.TargetSRID > 0 && !string.IsNullOrEmpty(SrsWkt).SrsWkt > 0 && this.SrsWkt != this.TargetSRID)
 *                              return string.Format(SharpMap.Map.numberFormat_EnUS,
 *                                      "ST.Transform(ST.MakeEnvelope({0},{1},{2},{3},{4}),{5})",
 *                                              bbox.MinX,
 *                                              bbox.MinY,
 *                                              bbox.MaxX,
 *                                              bbox.MaxY,
 *                                              this.TargetSRID,
 *                                              this.SrsWkt);
 *                      else
 */
            return(string.Format(SharpMap.Map.numberFormat_EnUS,
                                 "ST.MakeEnvelope({0},{1},{2},{3},{4})",
                                 bbox.MinX,
                                 bbox.MinY,
                                 bbox.MaxX,
                                 bbox.MaxY,
                                 this.SrsWkt));
        }
Ejemplo n.º 35
0
        // applies map projection transfrom to get reprojected envelope
        private void ApplyTransformToEnvelope()
        {
            double[] leftBottom, leftTop, rightTop, rightBottom;
            double left, right, bottom, top;

            _envelope = GetExtent();

            if (_transform == null)
                return;

            // set envelope
#if !DotSpatialProjections
            _envelope = GeometryTransform.TransformBox(_envelope, _transform.MathTransform);
#else
            _envelope = GeometryTransform.TransformBox(_envelope, _transform.Source, _transform.Target);
#endif
            // do same to histo rectangle
            leftBottom = new double[] { _histoBounds.Left, _histoBounds.Bottom };
            leftTop = new double[] { _histoBounds.Left, _histoBounds.Top };
            rightBottom = new double[] { _histoBounds.Right, _histoBounds.Bottom };
            rightTop = new double[] { _histoBounds.Right, _histoBounds.Top };

            // transform corners into new projection
#if !DotSpatialProjections
            leftBottom = _transform.MathTransform.Transform(leftBottom);
            leftTop = _transform.MathTransform.Transform(leftTop);
            rightBottom = _transform.MathTransform.Transform(rightBottom);
            rightTop = _transform.MathTransform.Transform(rightTop);
#else
            Reproject.ReprojectPoints(leftBottom, null, _transform.Source, _transform.Target, 0, 1);
            Reproject.ReprojectPoints(leftTop, null, _transform.Source, _transform.Target, 0, 1);
            Reproject.ReprojectPoints(rightBottom, null, _transform.Source, _transform.Target, 0, 1);
            Reproject.ReprojectPoints(rightTop, null, _transform.Source, _transform.Target, 0, 1);
#endif
            // find extents
            left = Math.Min(leftBottom[0], Math.Min(leftTop[0], Math.Min(rightBottom[0], rightTop[0])));
            right = Math.Max(leftBottom[0], Math.Max(leftTop[0], Math.Max(rightBottom[0], rightTop[0])));
            bottom = Math.Min(leftBottom[1], Math.Min(leftTop[1], Math.Min(rightBottom[1], rightTop[1])));
            top = Math.Max(leftBottom[1], Math.Max(leftTop[1], Math.Max(rightBottom[1], rightTop[1])));

            // set histo rectangle
            _histoBounds = new Rectangle((int)left, (int)bottom, (int)right, (int)top);
        }
Ejemplo n.º 36
0
        // add image pixels to the map
        
#if !DotSpatialProjections
        protected virtual void GetPreview(Dataset dataset, Size size, Graphics g,
                                          BoundingBox displayBbox, ICoordinateSystem mapProjection, Map map)
Ejemplo n.º 37
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection<uint> GetObjectIDsInView(BoundingBox bbox)
        {
            _ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            _ogrLayer.ResetReading();

            var objectIDs = new Collection<uint>();
            OgrFeature ogrFeature;
            while ((ogrFeature = _ogrLayer.GetNextFeature()) != null)
            {
                objectIDs.Add((uint)ogrFeature.GetFID());
                ogrFeature.Dispose();
            }
            return objectIDs;
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Returns geometries within the specified bounding box
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection<Geometry> GetGeometriesInView(BoundingBox bbox)
        {
            var geoms = new Collection<Geometry>();

            _ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            _ogrLayer.ResetReading();

            try
            {
                OgrFeature ogrFeature;
                while ((ogrFeature = _ogrLayer.GetNextFeature()) != null)
                {
                    using (var gr = ogrFeature.GetGeometryRef())
                    {
                        var geom = ParseOgrGeometry(gr, Factory);
                        if (geom != null) 
                            geoms.Add(geom);
                    }
                    ogrFeature.Dispose();
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return geoms;
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Returns geometry Object IDs whose bounding box intersects 'bbox'
        /// </summary>
        /// <param name="bbox"></param>
        /// <returns></returns>
        public override Collection<uint> GetObjectIDsInView(BoundingBox bbox)
        {
            DataRow[] drow;
            Collection<uint> objectlist = new Collection<uint>();

            if (Table.Rows.Count == 0)
            {
                return null;
            }

            string strSQL = 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);

            drow = Table.Select(strSQL);

            foreach (DataRow dr in drow)
            {
                objectlist.Add((uint) (int) dr[0]);
            }

            return objectlist;
        }
Ejemplo n.º 40
0
        // faster than rotated display
#if !DotSpatialProjections
        private void GetNonRotatedPreview(Dataset dataset, Size size, Graphics g,
                                          BoundingBox bbox, ICoordinateSystem mapProjection)
Ejemplo n.º 41
0
 /// <summary>
 /// Returns the data associated with the centroid of the bounding box.
 /// </summary>
 /// <param name="box">BoundingBox to intersect with</param>
 /// <param name="ds">FeatureDataSet to fill data into</param>
 public void ExecuteIntersectionQuery(BoundingBox box, FeatureDataSet ds)
 {
     var pt = new GeoPoint(box.MinX + 0.5 * box.Width,
                           box.MaxY - 0.5 * box.Height);
     ExecuteIntersectionQuery(pt, ds);
 }
Ejemplo n.º 42
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="envelope"></param>
        /// <param name="ds"></param>
        public override void ExecuteIntersectionQuery(BoundingBox envelope, IFeatureCollectionSet ds, CancellationToken? ct = null)
        {
            // Identifies all the features within the given BoundingBox
            var dataTable = CreateFeatureDataTable();
            dataTable.BeginLoadData();
            foreach (Feature feature in _features)
            {
                if (envelope.Intersects(feature.Geometry.EnvelopeInternal))
                    CreateNewRow(dataTable, feature);
            }
            dataTable.EndLoadData();

            ds.Add(dataTable);
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Returns features within the specified bounding box.
 /// </summary>
 /// <param name="envelope"></param>
 /// <returns></returns>
 public override IEnumerable<Geometry> GetGeometriesInView(BoundingBox envelope, CancellationToken? ct=null)
 {
     // Identifies all the features within the given BoundingBox
     var geoms = new Collection<Geometry>();
     foreach (var feature in _features)
         if (envelope.Intersects(feature.Geometry.EnvelopeInternal))
             geoms.Add(feature.Geometry);
     return geoms;
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Returns the data associated with all the geometries that are intersected by 'geom'
 /// </summary>
 /// <param name="bbox">Geometry to intersect with</param>
 /// <param name="ds">FeatureDataSet to fill data into</param>
 public override void ExecuteIntersectionQuery(BoundingBox bbox, FeatureDataSet ds)
 {
     _ogrLayer.SetSpatialFilterRect(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
     ExecuteIntersectionQuery(ds);
 }
Ejemplo n.º 45
0
        /// <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 override 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 = Factory.CreatePoint(new Coordinate((double) dr[XColumn], (double) dr[YColumn]));
            }

            ds.Tables.Add(fdt);
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Gets the object IDs in the view.
 /// </summary>
 /// <param name="bbox">The bbox.</param>
 /// <returns></returns>
 public override Collection<uint> GetObjectIDsInView(BoundingBox bbox)
 {
     // Identifies all the features within the given BoundingBox
     Envelope envelope = bbox;
     Collection<uint> geoms = new Collection<uint>();
     for (int i = 0; i < _features.Count; i++)
         if (envelope.Intersects(_features[i].Geometry.EnvelopeInternal))
             geoms.Add(Convert.ToUInt32(i));
     return geoms;
 }
Ejemplo n.º 47
0
        ///// <summary>
        ///// Loads a Ogr datasource with the first layer
        ///// </summary>
        ///// <param name="datasource">datasource</param>
        ///// <param name="name">Returns the name of the loaded layer</param>
        /////<remarks>
        /////This constructor is obsolete!
        /////If you want this functionality use
        /////<example>
        /////SharpMap.Data.Providers.Ogr prov = new SharpMap.Data.Providers.Ogr(datasource);
        /////string layerName = prov.Layername;
        /////</example>
        /////</remarks>
        //[Obsolete("This constructor does not work well with VB.NET. Use LayerName property instead")]
        //public Ogr(string datasource, out string name)
        //    : this(datasource, 0, out name)
        //{
        //}

        #endregion

        #region IProvider Members

        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public override BoundingBox GetExtents()
        {
            if (_bbox == null)
            {
                OgrEnvelope ogrEnvelope = new OgrEnvelope();
                if (_ogrLayer != null) _ogrLayer.GetExtent(ogrEnvelope, 1);

                _bbox = new BoundingBox(ogrEnvelope.MinX, ogrEnvelope.MaxX,
                                        ogrEnvelope.MinY, ogrEnvelope.MaxY);
            }

            return _bbox;
        }
Ejemplo n.º 48
0
        /// <summary>
        /// initialize a Gdal based raster layer
        /// </summary>
        /// <param name="strLayerName">Name of layer</param>
        /// <param name="imageFilename">location of image</param>
        public GdalRasterLayer(string strLayerName, string imageFilename)
        {
            LayerName = strLayerName;
            Filename = imageFilename;

            Gdal.AllRegister();

            try
            {
                _gdalDataset = Gdal.OpenShared(_Filename, Access.GA_ReadOnly);

                // have gdal read the projection
                _projectionWkt = _gdalDataset.GetProjectionRef();

                // no projection info found in the image...check for a prj
                if (_projectionWkt == "" &&
                    File.Exists(imageFilename.Substring(0, imageFilename.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)) + ".prj"))
                {
                    _projectionWkt =
                        File.ReadAllText(imageFilename.Substring(0, imageFilename.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)) + ".prj");
                }

                _imagesize = new Size(_gdalDataset.RasterXSize, _gdalDataset.RasterYSize);
                _envelope = GetExtent();
                _histoBounds = new Rectangle((int)_envelope.MinX, (int)_envelope.MinY, (int)_envelope.Width,
                                             (int)_envelope.Height);
                _lbands = _gdalDataset.RasterCount;
            }
            catch (Exception ex)
            {
                _gdalDataset = null;
                throw new Exception("Couldn't load " + imageFilename + "\n\n" + ex.Message + ex.InnerException);
            }
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Gets the object IDs in the view.
 /// </summary>
 /// <param name="bbox">The bbox.</param>
 /// <param name="ct">A cancellation token</param>
 /// <returns></returns>
 public override IEnumerable<object> GetOidsInView(BoundingBox bbox, CancellationToken? ct= null)
 {
     // Identifies all the features within the given BoundingBox
     Envelope envelope = bbox;
     var geoms = new Collection<object>();
     for (int i = 0; i < _features.Count; i++)
         if (envelope.Intersects(_features[i].Geometry.EnvelopeInternal))
             geoms.Add(Convert.ToUInt32(i));
     return geoms;
 }
Ejemplo n.º 50
0
        private void GetNonRotatedPreview(Dataset dataset, Size size, Graphics g,
                                          BoundingBox bbox, ProjectionInfo mapProjection)
#endif
        {
            double[] geoTrans = new double[6];
            dataset.GetGeoTransform(geoTrans);

            // default transform
            if (!_useRotation && !_haveSpot || (geoTrans[0] == 0 && geoTrans[3] == 0))
                geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 };
            Bitmap bitmap = null;
            _geoTransform = new GeoTransform(geoTrans);
            int DsWidth = 0;
            int DsHeight = 0;
            BitmapData bitmapData = null;
            double[] intVal = new double[Bands];
            int p_indx;
            double bitScalar = 1.0;

            double dblImginMapW = 0, dblImginMapH = 0, dblLocX = 0, dblLocY = 0;

            int iPixelSize = 3; //Format24bppRgb = byte[b,g,r] 

            if (dataset != null)
            {
                //check if image is in bounding box
                if ((bbox.MinX > _envelope.MaxX) || (bbox.MaxX < _envelope.MinX)
                    || (bbox.MaxY < _envelope.MinY) || (bbox.MinY > _envelope.MaxY))
                    return;

                DsWidth = _imagesize.Width;
                DsHeight = _imagesize.Height;

                _histogram = new List<int[]>();
                for (int i = 0; i < _lbands + 1; i++)
                    _histogram.Add(new int[256]);

                double left = Math.Max(bbox.MinX, _envelope.MinX);
                double top = Math.Min(bbox.MaxY, _envelope.MaxY);
                double right = Math.Min(bbox.MaxX, _envelope.MaxX);
                double bottom = Math.Max(bbox.MinY, _envelope.MinY);

                double x1 = Math.Abs(_geoTransform.PixelX(left));
                double y1 = Math.Abs(_geoTransform.PixelY(top));
                double imgPixWidth = _geoTransform.PixelXwidth(right - left);
                double imgPixHeight = _geoTransform.PixelYwidth(bottom - top);

                //get screen pixels image should fill 
                double dblBBoxW = bbox.Width;
                double dblBBoxtoImgPixX = imgPixWidth / dblBBoxW;
                dblImginMapW = size.Width * dblBBoxtoImgPixX * _geoTransform.HorizontalPixelResolution;


                double dblBBoxH = bbox.Height;
                double dblBBoxtoImgPixY = imgPixHeight / dblBBoxH;
                dblImginMapH = size.Height * dblBBoxtoImgPixY * -_geoTransform.VerticalPixelResolution;

                if ((dblImginMapH == 0) || (dblImginMapW == 0))
                    return;

                // ratios of bounding box to image ground space
                double dblBBoxtoImgX = size.Width / dblBBoxW;
                double dblBBoxtoImgY = size.Height / dblBBoxH;

                // set where to display bitmap in Map
                if (bbox.MinX != left)
                {
                    if (bbox.MaxX != right)
                        dblLocX = (_envelope.MinX - bbox.MinX) * dblBBoxtoImgX;
                    else
                        dblLocX = size.Width - dblImginMapW;
                }
                if (bbox.MaxY != top)
                {
                    if (bbox.MinY != bottom)
                        dblLocY = (bbox.MaxY - _envelope.MaxY) * dblBBoxtoImgY;
                    else
                        dblLocY = size.Height - dblImginMapH;
                }

                // scale
                if (_bitDepth == 12)
                    bitScalar = 16.0;
                else if (_bitDepth == 16)
                    bitScalar = 256.0;
                else if (_bitDepth == 32)
                    bitScalar = 16777216.0;

                try
                {
                    bitmap = new Bitmap((int)Math.Round(dblImginMapW), (int)Math.Round(dblImginMapH),
                                        PixelFormat.Format24bppRgb);
                    bitmapData =
                        bitmap.LockBits(
                            new Rectangle(0, 0, (int)Math.Round(dblImginMapW), (int)Math.Round(dblImginMapH)),
                            ImageLockMode.ReadWrite, bitmap.PixelFormat);

                    byte cr = _noDataInitColor.R;
                    byte cg = _noDataInitColor.G;
                    byte cb = _noDataInitColor.B;

                    //
                    Double[] noDataValues = new Double[Bands];
                    Double[] scales = new Double[Bands];

                    ColorTable colorTable = null;
                    unsafe
                    {
                        double[][] buffer = new double[Bands][];
                        Band[] band = new Band[Bands];
                        int[] ch = new int[Bands];
                        // get data from image
                        for (int i = 0; i < Bands; i++)
                        {
                            buffer[i] = new double[(int)Math.Round(dblImginMapW) * (int)Math.Round(dblImginMapH)];
                            band[i] = dataset.GetRasterBand(i + 1);

                            //get nodata value if present
                            Int32 hasVal = 0;
                            band[i].GetNoDataValue(out noDataValues[i], out hasVal);
                            if (hasVal == 0) noDataValues[i] = Double.NaN;
                            band[i].GetScale(out scales[i], out hasVal);
                            if (hasVal == 0) scales[i] = 1.0;

                            band[i].ReadRaster((int)Math.Round(x1), (int)Math.Round(y1), (int)Math.Round(imgPixWidth),
                                               (int)Math.Round(imgPixHeight),
                                               buffer[i], (int)Math.Round(dblImginMapW), (int)Math.Round(dblImginMapH),
                                               0, 0);

                            if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_BlueBand) ch[i] = 0;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GreenBand) ch[i] = 1;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_RedBand) ch[i] = 2;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_Undefined)
                            {
                                if (Bands > 1)
                                    ch[i] = 3; // infrared
                                else
                                {
                                    ch[i] = 4;
                                    if (_colorBlend == null)
                                    {
                                        Double dblMin, dblMax;
                                        band[i].GetMinimum(out dblMin, out hasVal);
                                        if (hasVal == 0) dblMin = Double.NaN;
                                        band[i].GetMaximum(out dblMax, out hasVal);
                                        if (hasVal == 0) dblMax = double.NaN;
                                        if (Double.IsNaN(dblMin) || Double.IsNaN(dblMax))
                                        {
                                            double dblMean, dblStdDev;
                                            band[i].GetStatistics(0, 1, out dblMin, out dblMax, out dblMean, out dblStdDev);
                                            //double dblRange = dblMax - dblMin;
                                            //dblMin -= 0.1*dblRange;
                                            //dblMax += 0.1*dblRange;
                                        }
                                        Single[] minmax = new float[] { Convert.ToSingle(dblMin), 0.5f * Convert.ToSingle(dblMin + dblMax), Convert.ToSingle(dblMax) };
                                        Color[] colors = new Color[] { Color.Blue, Color.Yellow, Color.Red };
                                        _colorBlend = new ColorBlend(colors, minmax);
                                    }
                                    intVal = new Double[3];
                                }
                            }
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) ch[i] = 0;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
                            {
                                colorTable = band[i].GetRasterColorTable();
                                ch[i] = 5;
                                intVal = new Double[3];
                            }
                            else ch[i] = -1;
                        }

                        if (_bitDepth == 32)
                            ch = new[] { 0, 1, 2 };

                        p_indx = 0;
                        for (int y = 0; y < Math.Round(dblImginMapH); y++)
                        {
                            byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
                            for (int x = 0; x < Math.Round(dblImginMapW); x++, p_indx++)
                            {
                                for (int i = 0; i < Bands; i++)
                                {
                                    intVal[i] = buffer[i][p_indx]/bitScalar;
                                    Double imageVal = intVal[i] = intVal[i]/bitScalar;
                                    if (ch[i] == 4)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            Color color = _colorBlend.GetColor(Convert.ToSingle(imageVal));
                                            intVal[0] = color.B;
                                            intVal[1] = color.G;
                                            intVal[2] = color.R;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }

                                    else if (ch[i] == 5 && colorTable != null)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            ColorEntry ce = colorTable.GetColorEntry(Convert.ToInt32(imageVal));
                                            intVal[0] = ce.c3;
                                            intVal[1] = ce.c2;
                                            intVal[2] = ce.c1;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }
                                    else
                                    {
                                        if (_colorCorrect)
                                        {
                                            intVal[i] = ApplyColorCorrection(intVal[i], 0, ch[i], 0, 0);

                                            if (_lbands >= 3)
                                                _histogram[_lbands][
                                                    (int) (intVal[2]*0.2126 + intVal[1]*0.7152 + intVal[0]*0.0722)]++;
                                        }
                                    }

                                    if (intVal[i] > 255)
                                        intVal[i] = 255;
                                }

                                WritePixel(x, intVal, iPixelSize, ch, row);
                            }
                        }
                    }
                }
                catch
                {
                    return;
                }
                finally
                {
                    if (bitmapData != null)
                        bitmap.UnlockBits(bitmapData);
                }
            }
            if (_transparentColor != Color.Empty)
                bitmap.MakeTransparent(_transparentColor);
            g.DrawImage(bitmap, new Point((int)Math.Round(dblLocX), (int)Math.Round(dblLocY)));
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Gets the features in view.
 /// </summary>
 /// <param name="bbox">The bbox.</param>
 /// <param name="ds">The ds.</param>
 public void GetFeaturesInView(BoundingBox bbox, FeatureDataSet ds)
 {
     ExecuteIntersectionQuery(bbox, ds);
 }
Ejemplo n.º 52
0
        protected virtual void GetPreview(Dataset dataset, Size size, Graphics g,
                                          BoundingBox displayBbox, ProjectionInfo mapProjection, Map map)
#endif
        {
            double[] geoTrans = new double[6];
            _gdalDataset.GetGeoTransform(geoTrans);

            // not rotated, use faster display method
            if ((!_useRotation ||
                 (geoTrans[1] == 1 && geoTrans[2] == 0 && geoTrans[4] == 0 && Math.Abs(geoTrans[5]) == 1))
                && !_haveSpot && _transform == null)
            {
                GetNonRotatedPreview(dataset, size, g, displayBbox, mapProjection);
                return;
            }
            // not rotated, but has spot...need default rotation
            else if ((geoTrans[0] == 0 && geoTrans[3] == 0) && _haveSpot)
                geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 };

            _geoTransform = new GeoTransform(geoTrans);
            double DsWidth = _imagesize.Width;
            double DsHeight = _imagesize.Height;
            double left, top, right, bottom;
            double GndX = 0, GndY = 0, ImgX = 0, ImgY = 0, PixX, PixY;
            double[] intVal = new double[Bands];
            double imageVal = 0, SpotVal = 0;
            double bitScalar = 1.0;
            Bitmap bitmap = null;
            Point bitmapTL = new Point(), bitmapBR = new Point();
            GeoPoint imageTL = new GeoPoint(), imageBR = new GeoPoint();
            BoundingBox shownImageBbox, trueImageBbox;
            int bitmapLength, bitmapHeight;
            int displayImageLength, displayImageHeight;

            int iPixelSize = 3; //Format24bppRgb = byte[b,g,r] 

            if (dataset != null)
            {
                //check if image is in bounding box
                if ((displayBbox.MinX > _envelope.MaxX) || (displayBbox.MaxX < _envelope.MinX)
                    || (displayBbox.MaxY < _envelope.MinY) || (displayBbox.MinY > _envelope.MaxY))
                    return;

                // init histo
                _histogram = new List<int[]>();
                for (int i = 0; i < _lbands + 1; i++)
                    _histogram.Add(new int[256]);

                // bounds of section of image to be displayed
                left = Math.Max(displayBbox.MinX, _envelope.MinX);
                top = Math.Min(displayBbox.MaxY, _envelope.MaxY);
                right = Math.Min(displayBbox.MaxX, _envelope.MaxX);
                bottom = Math.Max(displayBbox.MinY, _envelope.MinY);

                trueImageBbox = new BoundingBox(left, right, bottom, top);

                // put display bounds into current projection
                if (_transform != null)
                {
#if !DotSpatialProjections
                    _transform.MathTransform.Invert();
                    shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.MathTransform);
                    _transform.MathTransform.Invert();
#else
                    shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.Source, _transform.Target);
#endif
                }
                else
                    shownImageBbox = trueImageBbox;

                // find min/max x and y pixels needed from image
                imageBR.X =
                    (int)
                    (Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).X,
                              Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopRight()).X,
                                       Math.Max(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).X,
                                                _geoTransform.GroundToImage(shownImageBbox.BottomRight()).X))) + 1);
                imageBR.Y =
                    (int)
                    (Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).Y,
                              Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopRight()).Y,
                                       Math.Max(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).Y,
                                                _geoTransform.GroundToImage(shownImageBbox.BottomRight()).Y))) + 1);
                imageTL.X =
                    (int)
                    Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).X,
                             Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopRight()).X,
                                      Math.Min(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).X,
                                               _geoTransform.GroundToImage(shownImageBbox.BottomRight()).X)));
                imageTL.Y =
                    (int)
                    Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopLeft()).Y,
                             Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopRight()).Y,
                                      Math.Min(_geoTransform.GroundToImage(shownImageBbox.BottomLeft()).Y,
                                               _geoTransform.GroundToImage(shownImageBbox.BottomRight()).Y)));

                // stay within image
                if (imageBR.X > _imagesize.Width)
                    imageBR.X = _imagesize.Width;
                if (imageBR.Y > _imagesize.Height)
                    imageBR.Y = _imagesize.Height;
                if (imageTL.Y < 0)
                    imageTL.Y = 0;
                if (imageTL.X < 0)
                    imageTL.X = 0;

                displayImageLength = (int)(imageBR.X - imageTL.X);
                displayImageHeight = (int)(imageBR.Y - imageTL.Y);

                // find ground coordinates of image pixels
                var groundBR = _geoTransform.ImageToGround(imageBR);
                var groundTL = _geoTransform.ImageToGround(imageTL);

                // convert ground coordinates to map coordinates to figure out where to place the bitmap
                bitmapBR = new Point((int)map.WorldToImage(trueImageBbox.BottomRight()).X + 1,
                                     (int)map.WorldToImage(trueImageBbox.BottomRight()).Y + 1);
                bitmapTL = new Point((int)map.WorldToImage(trueImageBbox.TopLeft()).X,
                                     (int)map.WorldToImage(trueImageBbox.TopLeft()).Y);

                bitmapLength = bitmapBR.X - bitmapTL.X;
                bitmapHeight = bitmapBR.Y - bitmapTL.Y;

                // check to see if image is on its side
                if (bitmapLength > bitmapHeight && displayImageLength < displayImageHeight)
                {
                    displayImageLength = bitmapHeight;
                    displayImageHeight = bitmapLength;
                }
                else
                {
                    displayImageLength = bitmapLength;
                    displayImageHeight = bitmapHeight;
                }

                // scale
                if (_bitDepth == 12)
                    bitScalar = 16.0;
                else if (_bitDepth == 16)
                    bitScalar = 256.0;
                else if (_bitDepth == 32)
                    bitScalar = 16777216.0;

                // 0 pixels in length or height, nothing to display
                if (bitmapLength < 1 || bitmapHeight < 1)
                    return;

                //initialize bitmap
                bitmap = new Bitmap(bitmapLength, bitmapHeight, PixelFormat.Format24bppRgb);
                BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmapLength, bitmapHeight),
                                                        ImageLockMode.ReadWrite, bitmap.PixelFormat);

                try
                {
                    unsafe
                    {
                        // turn everything to _noDataInitColor, so we can make fill transparent
                        byte cr = _noDataInitColor.R;
                        byte cg = _noDataInitColor.G;
                        byte cb = _noDataInitColor.B;

                        for (int y = 0; y < bitmapHeight; y++)
                        {
                            byte* brow = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
                            for (int x = 0; x < bitmapLength; x++)
                            {
                                Int32 offsetX = x * 3;
                                brow[offsetX++] = cb;
                                brow[offsetX++] = cg;
                                brow[offsetX] = cr;
                            }
                        }

                        // create 3 dimensional buffer [band][x pixel][y pixel]
                        double[][] tempBuffer = new double[Bands][];
                        double[][][] buffer = new double[Bands][][];
                        for (int i = 0; i < Bands; i++)
                        {
                            buffer[i] = new double[displayImageLength][];
                            for (int j = 0; j < displayImageLength; j++)
                                buffer[i][j] = new double[displayImageHeight];
                        }

                        Band[] band = new Band[Bands];
                        int[] ch = new int[Bands];

                        //
                        Double[] noDataValues = new Double[Bands];
                        Double[] scales = new Double[Bands];
                        ColorTable colorTable = null;


                        // get data from image
                        for (int i = 0; i < Bands; i++)
                        {
                            tempBuffer[i] = new double[displayImageLength * displayImageHeight];
                            band[i] = dataset.GetRasterBand(i + 1);

                            //get nodata value if present
                            Int32 hasVal = 0;
                            band[i].GetNoDataValue(out noDataValues[i], out hasVal);
                            if (hasVal == 0) noDataValues[i] = Double.NaN;
                            band[i].GetScale(out scales[i], out hasVal);
                            if (hasVal == 0) scales[i] = 1.0;

                            band[i].ReadRaster(
                                (int)imageTL.X,
                                (int)imageTL.Y,
                                (int)(imageBR.X - imageTL.X),
                                (int)(imageBR.Y - imageTL.Y),
                                tempBuffer[i], displayImageLength, displayImageHeight, 0, 0);

                            // parse temp buffer into the image x y value buffer
                            long pos = 0;
                            for (int y = 0; y < displayImageHeight; y++)
                            {
                                for (int x = 0; x < displayImageLength; x++, pos++)
                                    buffer[i][x][y] = tempBuffer[i][pos];
                            }

                            if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_BlueBand) ch[i] = 0;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GreenBand) ch[i] = 1;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_RedBand) ch[i] = 2;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_Undefined)
                            {
                                if (Bands > 1)
                                    ch[i] = 3; // infrared
                                else
                                {
                                    ch[i] = 4;
                                    if (_colorBlend == null)
                                    {
                                        Double dblMin, dblMax;
                                        band[i].GetMinimum(out dblMin, out hasVal);
                                        if (hasVal == 0) dblMin = Double.NaN;
                                        band[i].GetMaximum(out dblMax, out hasVal);
                                        if (hasVal == 0) dblMax = double.NaN;
                                        if (Double.IsNaN(dblMin) || Double.IsNaN(dblMax))
                                        {
                                            double dblMean, dblStdDev;
                                            band[i].GetStatistics(0, 1, out dblMin, out dblMax, out dblMean, out dblStdDev);
                                            //double dblRange = dblMax - dblMin;
                                            //dblMin -= 0.1*dblRange;
                                            //dblMax += 0.1*dblRange;
                                        }
                                        Single[] minmax = new float[] { Convert.ToSingle(dblMin), 0.5f * Convert.ToSingle(dblMin + dblMax), Convert.ToSingle(dblMax) };
                                        Color[] colors = new Color[] { Color.Blue, Color.Yellow, Color.Red };
                                        _colorBlend = new ColorBlend(colors, minmax);
                                    }
                                    intVal = new Double[3];
                                }
                            }
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) ch[i] = 0;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
                            {
                                colorTable = band[i].GetRasterColorTable();
                                ch[i] = 5;
                                intVal = new Double[3];
                            }
                            else ch[i] = -1;
                        }

                        // store these values to keep from having to make slow method calls
                        int bitmapTLX = bitmapTL.X;
                        int bitmapTLY = bitmapTL.Y;
                        double imageTop = imageTL.Y;
                        double imageLeft = imageTL.X;
                        double dblMapPixelWidth = map.PixelWidth;
                        double dblMapPixelHeight = map.PixelHeight;
                        double dblMapMinX = map.Envelope.MinX;
                        double dblMapMaxY = map.Envelope.MaxY;
                        double geoTop, geoLeft, geoHorzPixRes, geoVertPixRes, geoXRot, geoYRot;

                        // get inverse values
                        geoTop = _geoTransform.Inverse[3];
                        geoLeft = _geoTransform.Inverse[0];
                        geoHorzPixRes = _geoTransform.Inverse[1];
                        geoVertPixRes = _geoTransform.Inverse[5];
                        geoXRot = _geoTransform.Inverse[2];
                        geoYRot = _geoTransform.Inverse[4];

                        double dblXScale = (imageBR.X - imageTL.X) / (displayImageLength - 1);
                        double dblYScale = (imageBR.Y - imageTL.Y) / (displayImageHeight - 1);
                        double[] dblPoint;

                        // get inverse transform  
                        // NOTE: calling transform.MathTransform.Inverse() once and storing it
                        // is much faster than having to call every time it is needed
#if !DotSpatialProjections
                        IMathTransform inverseTransform = null;
                        if (_transform != null)
                            inverseTransform = _transform.MathTransform.Inverse();
#endif

                        for (PixY = 0; PixY < bitmapBR.Y - bitmapTL.Y; PixY++)
                        {
                            byte* row = (byte*)bitmapData.Scan0 + ((int)Math.Round(PixY) * bitmapData.Stride);

                            for (PixX = 0; PixX < bitmapBR.X - bitmapTL.X; PixX++)
                            {
                                // same as Map.ImageToGround(), but much faster using stored values...rather than called each time
                                GndX = dblMapMinX + (PixX + bitmapTLX) * dblMapPixelWidth;
                                GndY = dblMapMaxY - (PixY + bitmapTLY) * dblMapPixelHeight;

                                // transform ground point if needed
                                if (_transform != null)
                                {
#if !DotSpatialProjections
                                    dblPoint = inverseTransform.Transform(new[] { GndX, GndY });
#else
                                    dblPoint = new double[] { GndX, GndY };
                                    Reproject.ReprojectPoints(dblPoint, null, _transform.Source, _transform.Target, 0, 1);
#endif
                                    GndX = dblPoint[0];
                                    GndY = dblPoint[1];
                                }

                                // same as GeoTransform.GroundToImage(), but much faster using stored values...
                                ImgX = (geoLeft + geoHorzPixRes * GndX + geoXRot * GndY);
                                ImgY = (geoTop + geoYRot * GndX + geoVertPixRes * GndY);

                                if (ImgX < imageTL.X || ImgX > imageBR.X || ImgY < imageTL.Y || ImgY > imageBR.Y)
                                    continue;

                                // color correction
                                for (int i = 0; i < Bands; i++)
                                {
                                    intVal[i] =
                                        buffer[i][(int)((ImgX - imageLeft) / dblXScale)][
                                            (int)((ImgY - imageTop) / dblYScale)];

                                    imageVal = SpotVal = intVal[i] = intVal[i] / bitScalar;
                                    if (ch[i] == 4)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            Color color = _colorBlend.GetColor(Convert.ToSingle(imageVal));
                                            intVal[0] = color.B;
                                            intVal[1] = color.G;
                                            intVal[2] = color.R;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }

                                    else if (ch[i] == 5 && colorTable != null)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            ColorEntry ce = colorTable.GetColorEntry(Convert.ToInt32(imageVal));
                                            intVal[0] = ce.c3;
                                            intVal[1] = ce.c2;
                                            intVal[2] = ce.c1;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }

                                    else
                                    {

                                        if (_colorCorrect)
                                        {
                                            intVal[i] = ApplyColorCorrection(imageVal, SpotVal, ch[i], GndX, GndY);

                                            // if pixel is within ground boundary, add its value to the histogram
                                            if (ch[i] != -1 && intVal[i] > 0 && (_histoBounds.Bottom >= (int)GndY) &&
                                                _histoBounds.Top <= (int)GndY &&
                                                _histoBounds.Left <= (int)GndX && _histoBounds.Right >= (int)GndX)
                                            {
                                                _histogram[ch[i]][(int)intVal[i]]++;
                                            }
                                        }

                                        if (intVal[i] > 255)
                                            intVal[i] = 255;
                                    }
                                }

                                // luminosity
                                if (_lbands >= 3)
                                    _histogram[_lbands][(int)(intVal[2] * 0.2126 + intVal[1] * 0.7152 + intVal[0] * 0.0722)]
                                        ++;

                                WritePixel(PixX, intVal, iPixelSize, ch, row);
                            }
                        }
                    }
                }

                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }
            }
            bitmap.MakeTransparent(_noDataInitColor);
            if (_transparentColor != Color.Empty)
                bitmap.MakeTransparent(_transparentColor);
            g.DrawImage(bitmap, new Point(bitmapTL.X, bitmapTL.Y));
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Computes the full extents of the data source as a 
        /// <see cref="BoundingBox"/>.
        /// </summary>
        /// <returns>
        /// A BoundingBox instance which minimally bounds all the features
        /// available in this data source.
        /// </returns>
        public override BoundingBox GetExtents()
        {
            if (Table.Rows.Count == 0)
            {
                return null;
            }

            BoundingBox box;

            double minX = Double.PositiveInfinity,
                   minY = Double.PositiveInfinity,
                   maxX = Double.NegativeInfinity,
                   maxY = Double.NegativeInfinity;

            foreach (DataRowView dr in Table.DefaultView)
            {
                if (minX > (double) dr[XColumn]) minX = (double) dr[XColumn];
                if (maxX < (double) dr[XColumn]) maxX = (double) dr[XColumn];
                if (minY > (double) dr[YColumn]) minY = (double) dr[YColumn];
                if (maxY < (double) dr[YColumn]) maxY = (double) dr[YColumn];
            }

            box = new BoundingBox(minX, maxX, minY, maxY);

            return box;
        }