Esempio n. 1
0
        /// <summary>
        /// 得到数据空间参考的wkt字符串
        /// </summary>
        /// <returns></returns>
        public string GetSridWkt()
        {
            string wkt = String.Empty;

            OSGeo.OSR.SpatialReference pSpatialReference = _ogrLayer.GetSpatialRef();
            if (pSpatialReference != null)
            {
                pSpatialReference.ExportToWkt(out wkt);
            }
            return(wkt);
        }
Esempio n. 2
0
        public static ESRI.ArcGIS.Geometry.ISpatialReference get_spatialReference(OSGeo.OSR.SpatialReference ogrSR)
        {
            ogrSR.MorphToESRI();

            string wkt;

            ogrSR.ExportToWkt(out wkt);

            ISpatialReferenceFactory4 spatialReferenceFactory = new ESRI.ArcGIS.Geometry.SpatialReferenceEnvironmentClass();
            ISpatialReference         sr;

            int bytesRead;

            spatialReferenceFactory.CreateESRISpatialReference(wkt, out sr, out bytesRead);

            return(sr);
        }
Esempio n. 3
0
        //矢量转栅格
        private void RasterizeLayer(Layer layer, string outRaster, string field, float resolution, int xSize, int ySize)
        {
            const double noDataValue      = -9999;          // NoData值
            string       outputRasterFile = outRaster;
            Envelope     envelope         = new Envelope(); //原图层外接矩形

            layer.GetExtent(envelope, 0);
            //新建栅格图层
            OSGeo.GDAL.Driver outputDriver  = Gdal.GetDriverByName("GTiff");
            Dataset           outputDataset = outputDriver.Create(outputRasterFile, xSize, ySize, 1, DataType.GDT_Int32, null);//DataType.GDT_Float64
            //获取原矢量图层坐标系
            string inputShapeSrs;

            OSGeo.OSR.SpatialReference spatialRefrence = layer.GetSpatialRef();
            spatialRefrence.ExportToWkt(out inputShapeSrs);
            outputDataset.SetProjection(inputShapeSrs);

            double[] argin = new double[] { envelope.MinX, resolution, 0, envelope.MaxY, 0, -resolution };
            outputDataset.SetGeoTransform(argin);

            Band band = outputDataset.GetRasterBand(1);

            band.SetNoDataValue(noDataValue);

            outputDataset.FlushCache();
            outputDataset.Dispose();
            //矢量转栅格
            int[]    bandlist   = new int[] { 1 };
            double[] burnValues = new double[] { 10.0 };
            Dataset  myDataset  = Gdal.Open(outputRasterFile, Access.GA_Update);

            string[] rasterizeOptions;
            rasterizeOptions = new string[] { "ATTRIBUTE=" + field, "ALL_TOUCHED=TRUE" };
            int tets = Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");

            myDataset.FlushCache();
            myDataset.Dispose();
        }
Esempio n. 4
0
        // public method to set envelope and transform to new projection
        /// <summary>
        /// Method to set <see cref="Envelope"/> and <see cref="Layer.CoordinateTransformation"/> to the projection of the map
        /// </summary>
        /// <param name="map">The map</param>
        public void ReprojectToMap(Map map)
        {
            ICoordinateSystem cs = null;
            if (map.SRID > 0)
            {
                using (var p = new OSGeo.OSR.SpatialReference(null))
                {
                    string wkt;
                    p.ImportFromEPSG(map.SRID);
                    p.ExportToWkt(out wkt);
#if !DotSpatialProjections
                    cs = new CoordinateSystemFactory().CreateFromWkt(wkt);
#else
                    cs = ProjectionInfo.FromEsriString(wkt);
#endif
                }
            }
            ReprojectToCoordinateSystem(cs);
        }
Esempio n. 5
0
        private void _load(bool leaveopen = false)
        {
            Open();

            // Populate some important metadata
            Layer mLayer = _ds.GetLayerByIndex(0);

            FIDColumn = mLayer.GetFIDColumn();
            LayerName = mLayer.GetName();

            _geometryType = new GDalGeometryType(mLayer.GetGeomType());

            // Get our FEATURE definitions
            Feature mFeat = mLayer.GetNextFeature();

            while (mFeat != null)
            {
                Geometry geo = mFeat.GetGeometryRef();
                if (geo == null)
                {
                    Debug.WriteLine(String.Format("Warning: Null Geometry Detected: FID:{0}", mFeat.GetFID()));
                }
                else
                {
                    int count = geo.GetGeometryCount();
                    if (count > 1)
                    {
                        if (_geometryType.SimpleType == SimpleTypes.Point || _geometryType.SimpleType == SimpleTypes.LineString)
                        {
                            Exception ex = new Exception("Multi-part geometries are detected in this file. This is not allowed.");
                            ex.Data["File Path"] = GISFileInfo.FullName;
                            ex.Data["Solution"]  = "Remove all multipart features from this ShapeFile.";
                            throw ex;
                        }
                        else
                        {
                            Debug.WriteLine(String.Format("Warning: Multipart feature detected: FID:{0}", mFeat.GetFID()));
                        }
                    }
                }

                Features.Add(mFeat.GetFID(), new VectorFeature(mFeat));

                mFeat = mLayer.GetNextFeature();
            }

            // Now get our FIELD definitions
            FeatureDefn mFeatDfn = mLayer.GetLayerDefn();
            int         iFldCnt  = mFeatDfn.GetFieldCount();

            for (int fldId = 0; fldId < iFldCnt; fldId++)
            {
                FieldDefn mFldDef = mFeatDfn.GetFieldDefn(fldId);
                Fields.Add(mFldDef.GetName(), new VectorField(mFldDef, fldId));
            }

            // Spatial is way harder than it needs to be:
            OSGeo.OSR.SpatialReference sRef = mLayer.GetSpatialRef();
            if (sRef == null)
            {
                Exception ex = new Exception("Feature class is missing spatial reference");
                ex.Data["Path"] = GISFileInfo.FullName;
                throw ex;
            }

            string sRefstring = "";

            sRef.ExportToWkt(out sRefstring);
            _Init(sRefstring);

            if (!leaveopen)
            {
                UnloadDS();
            }
        }
Esempio n. 6
0
        // export map as raster-image
        private void renderButton_Click(object sender, EventArgs e)
        {
            toolBuilder.addHeader("Export to GeoTiff", false);
            // textbox for increase in resolution
            var zoom = toolBuilder.addTextboxWithCaption("Zoom factor:", "1");
            // textbox and button for new file name input
            var file = toolBuilder.addTextboxWithCaption("Filename:", "");
            var browsebutton = toolBuilder.addButton("Browse...");
            browsebutton.Click += (o, w) =>
            {
                 SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                 saveFileDialog1.Filter = "bmp files (*.bmp)|*.bmp"  ;
                 if(saveFileDialog1.ShowDialog() == DialogResult.OK)
                     file.Text = saveFileDialog1.FileName;
            };
            // label for errors
            var error = toolBuilder.addErrorLabel();

            // button for performing rasterization
            Button button = toolBuilder.addButton("Export", (Layer selectedLayer) =>
            {
                // no filename is given
                if (file.Text == "")
                {
                    toolBuilder.setError("Please provide filename");
                    return;
                }
                // æøå not accepted in filename, not supported by GDAL
                if (file.Text.ToLower().IndexOfAny("æøå".ToCharArray()) > -1)
                {
                    toolBuilder.setError("No æøå in filename");
                    return;
                }
                double zoomfactor = 1;
                if (!double.TryParse(zoom.Text, out zoomfactor))
                {
                    // zoom factor must be a number
                    toolBuilder.setError("Zoom factor not a number");
                    return;
                }

                // calulate image resolution and new real world coordinates
                var oldWindowRect = ScreenManager.WindowsRect.Clone();
                ScreenManager.WindowsRect = new ScreenManager.SGISEnvelope(0, oldWindowRect.MaxX * zoomfactor, 0, oldWindowRect.MaxY * zoomfactor);
                ScreenManager.Calculate();
                Bitmap mapTemp = new Bitmap((int)ScreenManager.WindowsRect.Width,
                                            (int)ScreenManager.WindowsRect.Height);
                var mapRectTemp = ScreenManager.MapScreenToReal(ScreenManager.WindowsRect);
                OgcCompliantGeometryFactory fact = new OgcCompliantGeometryFactory();
                var boundingGeometry = fact.ToGeometry(mapRectTemp);
                Render render = new Render(ScreenManager.Scale, ScreenManager.Offset);
                ScreenManager.WindowsRect.Set(oldWindowRect);
                ScreenManager.Calculate();

                // background worker for performing rasterisation in another thread
                BackgroundWorker bwRender = new BackgroundWorker();
                bwRender.DoWork += (obj, args) =>
                {
                    var mapGraphics = Graphics.FromImage(mapTemp);

                    // draw background maps
                    foreach (Photo p in photos)
                    {
                        // only if visible
                        if (p.Geometry.Intersects(boundingGeometry))
                            render.Draw(p, mapGraphics);
                    }
                    // draw layers
                    foreach (Layer l in Layers.Reverse())
                    {
                        // only if visible
                        if (!l.Visible)
                            continue;
                        // draw only visible features
                        var visibleFeatures = l.getWithin(boundingGeometry);
                        lock (l) // lock layer to prevent multithreaded access to style when drawing
                        {
                            // render feature
                            foreach (Feature s in visibleFeatures)
                            {
                                render.Draw(s.Geometry, mapGraphics, l.Style);
                            }
                        }
                    }
                };
                // georeference drawn bitmap
                bwRender.RunWorkerCompleted += (obj, args) =>
                {
                    // remove .bmp ending if present
                    if (file.Text.EndsWith(".bmp"))
                        file.Text = file.Text.Substring(0, file.Text.Length-4);
                    // save render
                    mapTemp.Save(file.Text+".bmp");

                   // init GDAL and copy image
                   OSGeo.GDAL.Gdal.AllRegister();
                   OSGeo.GDAL.Driver srcDrv = OSGeo.GDAL.Gdal.GetDriverByName("GTiff");
                   OSGeo.GDAL.Dataset srcDs = OSGeo.GDAL.Gdal.Open(file.Text+".bmp", OSGeo.GDAL.Access.GA_ReadOnly);
                   OSGeo.GDAL.Dataset dstDs = srcDrv.CreateCopy(file.Text+".tiff", srcDs, 0, null, null, null);

                   //Set the map projection
                    {
                        OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference("");
                        oSRS.ImportFromProj4( SRS.ToString() );
                        string wkt;
                        // convert projection to wkt
                        oSRS.ExportToWkt(out wkt);
                        dstDs.SetProjection(wkt);
                   }

                   //Set the map coordinates
                   double mapWidth = mapRectTemp.Width;
                   double mapHeight = mapRectTemp.Height;
                   double[] geoTransfo = new double[] { mapRectTemp.MinX, mapWidth / mapTemp.Width, 0, mapRectTemp.MaxY, 0, -mapHeight / mapTemp.Height };
                   dstDs.SetGeoTransform(geoTransfo);

                   dstDs.FlushCache();
                   dstDs.Dispose();
                   srcDs.Dispose();
                   srcDrv.Dispose();

                    /////////////////////////
                };
                bwRender.RunWorkerAsync();
            });
        }