Exemplo n.º 1
1
        public PolygonFeatureGeoData GetFieldGeo()
        {
            var result = new PolygonFeatureGeoData();
            //"geom"
            var data = Value.GetGeometryRef();
            SpatialReference spatialReference = new SpatialReference(Constants.Epsg3035Wkt);

            data.TransformTo(spatialReference);

            result.Area = data.GetArea();
            var geomJsonString    = data.ExportToJson(new string[0]);
            var geoData           = JsonConvert.DeserializeObject <GeometryData>(geomJsonString);
            var listOfCoordinates = new List <XY>();

            foreach (var coordinate in geoData.Coordinates)
            {
                // for polygon type.
                foreach (var innerCoordinate in coordinate)
                {
                    var xy = new XY {
                        X = innerCoordinate.First(), Y = innerCoordinate.Last()
                    };
                    listOfCoordinates.Add(xy);
                }
            }

            result.Coordinates = listOfCoordinates;

            return(result);
        }
Exemplo n.º 2
0
        public static bool Transform(this DMesh3 dMesh, SpatialReference to)
        {
            string crs = dMesh.FindMetadata("CRS") as string;

            if (crs != null && crs != "")
            {
                SpatialReference from = new SpatialReference(null);
                if (crs.Contains("+proj"))
                {
                    from.ImportFromProj4(crs);
                }
                else if (crs.StartsWith("epsg") || crs.StartsWith("EPSG"))
                {
                    int epsg = int.Parse(crs.Split(':')[1]);
                    from.ImportFromEPSG(epsg);
                }
                else
                {
                    from.ImportFromWkt(ref crs);
                };
                try {
                    CoordinateTransformation trans = new CoordinateTransformation(from, to);
                    for (int i = 0; i < dMesh.VertexCount; i++)
                    {
                        if (dMesh.IsVertex(i))
                        {
                            Vector3d vertex = dMesh.GetVertex(i);
                            double[] dV     = new double[3] {
                                vertex.x, vertex.y, vertex.z
                            };
                            trans.TransformPoint(dV);
                            AppState.instance.mapTrans.TransformPoint(dV);
                            dMesh.SetVertex(i, new Vector3d(dV));
                        }
                    }
                    ;
                    return(true);
                } catch {
                    return(false);
                }
            }
            try {
                for (int i = 0; i < dMesh.VertexCount; i++)
                {
                    if (dMesh.IsVertex(i))
                    {
                        Vector3d vertex = dMesh.GetVertex(i);
                        double[] dV     = new double[3] {
                            vertex.x, vertex.y, vertex.z
                        };
                        AppState.instance.mapTrans.TransformPoint(dV);
                        dMesh.SetVertex(i, new Vector3d(dV));
                    }
                }
                ;
                return(true);
            } catch {
                return(false);
            }
        }
Exemplo n.º 3
0
        private static void SelectRandomFeatures(string dataSetPath, int sampleSize)
        {
            List <dynamic> result        = new List <dynamic>();
            Driver         fileGdbDriver = Ogr.GetDriverByName("OpenFileGDB");
            DataSource     dataSource    = fileGdbDriver.Open(dataSetPath, 0);

            Layer            layer            = dataSource.GetLayerByIndex(0);
            SpatialReference spatialReference = layer.GetSpatialRef();

            // A list of all the feature indices in the layer from 0 to featureCount-1
            List <int> featureList = Enumerable.Range(0, (int)layer.GetFeatureCount(0)).ToList();
            Random     random      = new Random();

            for (int i = 0; i < sampleSize; i++)
            {
                int index = random.Next(0, featureList.Count);

                // Get the feature at the selected index position
                Feature feature = layer.GetFeature(featureList[index]);
                featureList.RemoveAt(index);

                result.Add(new
                {
                    FeatureId       = feature.GetFID(),
                    Classification  = feature.GetFieldAsString("CODE2012"),
                    FeatureGeometry = Tools.GetSampleItemGeometriesPolygon(feature, spatialReference),
                });
            }

            Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions {
                WriteIndented = true
            }));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Convert Vector3 World Space location to Position taking account of zoom, scale and mapscale
        /// </summary>
        /// <param name="position">Vector3 World Space coordinates</param>
        /// <returns>Position</returns>
        static public IPosition ToPosition(this Vector3 position, ICRSObject crs = null)
        {
            Geometry         geom = position.ToGeometry();
            SpatialReference sr   = new SpatialReference(null);

            if (crs == null)
            {
                sr.SetWellKnownGeogCS("EPSG:4326");
            }
            else
            {
                switch (crs.Type)
                {
                case CRSType.Name:
                    string name = (crs as NamedCRS).Properties["name"] as string;
                    sr.SetProjCS(name);
                    break;

                case CRSType.Link:
                    string url = (crs as LinkedCRS).Properties["href"] as string;
                    sr.ImportFromUrl(url);
                    break;

                case CRSType.Unspecified:
                    sr.SetWellKnownGeogCS("EPSG:4326");
                    break;
                }
            }
            geom.TransformTo(sr);
            double[] argout = new double[3];
            geom.GetPoint(0, argout);
            return(new Position(argout[0], argout[1], argout[2]));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creates ag3.DCurve from a geometry
        /// </summary>
        /// <param name="curve"> this curve</param>
        /// <param name="geom"> the OGR geometry to ue as ths source</param>
        /// <param name="crs"> the crs to u for the DCurve3 DEFAULT map default projections or EPG:4326 if none</param>
        /// <returns></returns>
        public static DCurve3 FromGeometry(this DCurve3 curve, Geometry geom, SpatialReference crs = null)
        {
            if (geom.GetSpatialReference() == null)
            {
                if (crs != null)
                {
                    geom.AssignSpatialReference(crs);
                }
                else
                {
                    geom.AssignSpatialReference(AppState.instance.projectCrs);
                }
            }
            if (geom.TransformTo(AppState.instance.mapProj) != 0)
            {
                throw new NotSupportedException("projection failed");
            }
            if (geom.Transform(AppState.instance.mapTrans) != 0)
            {
                throw new NotSupportedException("axis change failed");
            }
            int n = geom.GetPointCount();

            Vector3d[] ls = new Vector3d[n];
            for (int i = 0; i < n; i++)
            {
                double[] argout = new double[3];
                geom.GetPoint(i, argout);
                ls[i] = new Vector3d(argout);
            }
            curve.ClearVertices();
            curve.SetVertices(ls);
            curve.Closed = geom.IsRing();
            return(curve);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Ogr to DotSpatial at projection level
        /// </summary>
        /// <param name="spatialReference">Ogr SpatialReference</param>
        /// <returns>DotSpatial ProjectionInfo</returns>
        public static DotSpatial.Projections.ProjectionInfo Ogr2DSProjection(OSGeo.OSR.SpatialReference spatialReference)
        {
            string proj4 = string.Empty;
            int    i     = spatialReference.ExportToProj4(out proj4);

            DotSpatial.Projections.ProjectionInfo projectionInfo = DotSpatial.Projections.ProjectionInfo.FromProj4String(proj4);
            return(projectionInfo);
        }
Exemplo n.º 7
0
 public void AssignSpatialReference(OSGeo.OSR.SpatialReference reference)
 {
     OgrPINVOKE.Geometry_AssignSpatialReference(swigCPtr, OSGeo.OSR.SpatialReference.getCPtr(reference));
     if (OgrPINVOKE.SWIGPendingException.Pending)
     {
         throw OgrPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Exemplo n.º 8
0
 public static void CoordTransformToWgs84(this OSGeo.OSR.SpatialReference srcSR, params double[][] inouts)
 {
     using (OSGeo.OSR.SpatialReference destSR = new OSGeo.OSR.SpatialReference(""))
     {
         destSR.SetWellKnownGeogCS("EPSG:4326");
         CoordTransform(srcSR, destSR, inouts);
     }
 }
Exemplo n.º 9
0
 public void SetSpatialRef(OSGeo.OSR.SpatialReference srs)
 {
     OgrPINVOKE.GeomFieldDefn_SetSpatialRef(swigCPtr, OSGeo.OSR.SpatialReference.getCPtr(srs));
     if (OgrPINVOKE.SWIGPendingException.Pending)
     {
         throw OgrPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// DotSpatial to Ogr at projection level
        /// </summary>
        /// <param name="projectionInfo">DotSpatial ProjectionInfo</param>
        /// <returns>Ogr SpatialReference</returns>
        public static OSGeo.OSR.SpatialReference DS2OgrProjection(DotSpatial.Projections.ProjectionInfo projectionInfo)
        {
            string proj4 = projectionInfo.ToProj4String();

            OSGeo.OSR.SpatialReference spatialReference = new OSGeo.OSR.SpatialReference("");
            spatialReference.ImportFromProj4(proj4);
            return(spatialReference);
        }
Exemplo n.º 11
0
        public static void GetSuitableZoom(this Dataset dataset, ref int minZoom, ref int maxZoom)
        {
            string projectionStr = dataset.GetProjection();

            double[] affineParas = new double[6];
            dataset.GetGeoTransform(affineParas);
            double xRes       = affineParas[1];
            double yRes       = -affineParas[5];
            double resolution = Math.Min(xRes, yRes);
            double dWidth     = Math.Max(dataset.RasterXSize * xRes, dataset.RasterYSize * yRes);
            string projcs     = null;
            string geogcs     = null;

            using (OSGeo.OSR.SpatialReference srcSR = new OSGeo.OSR.SpatialReference(projectionStr))
            {
                projcs = srcSR.GetAttrValue("PROJCS", 0);
                if (string.IsNullOrEmpty(projcs))
                {
                    geogcs = srcSR.GetAttrValue("GEOGCS", 0);
                }
            }
            bool isDegree     = projcs == null && geogcs != null;
            bool minZoomSeted = false;
            bool maxZoomSeted = false;

            for (int i = 0; i < 30; i++)
            {
                double tmpResolution = TileMatrix.GetResolution(isDegree, i);
                if (!minZoomSeted)
                {
                    if (dWidth / tmpResolution > 256)
                    {
                        if (i == 0)
                        {
                            minZoom = i;
                        }
                        else
                        {
                            minZoom = i - 1;
                        }
                        minZoomSeted = true;
                    }
                }
                if (!maxZoomSeted)
                {
                    if (resolution >= tmpResolution)
                    {
                        maxZoom      = i;
                        maxZoomSeted = true;
                    }
                }
                if (minZoomSeted && maxZoomSeted)
                {
                    break;
                }
            }
        }
        public static void ReportLayer(Layer layer)
        {
            FeatureDefn def = layer.GetLayerDefn();

            Console.WriteLine("Layer name: " + def.GetName());
            Console.WriteLine("Feature Count: " + layer.GetFeatureCount(1));
            Envelope ext = new Envelope();

            layer.GetExtent(ext, 1);
            Console.WriteLine("Extent: " + ext.MinX + "," + ext.MaxX + "," +
                              ext.MinY + "," + ext.MaxY);

            /* -------------------------------------------------------------------- */
            /*      Reading the spatial reference                                   */
            /* -------------------------------------------------------------------- */
            OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef();
            string srs_wkt;

            if (sr != null)
            {
                sr.ExportToPrettyWkt(out srs_wkt, 1);
            }
            else
            {
                srs_wkt = "(unknown)";
            }


            Console.WriteLine("Layer SRS WKT: " + srs_wkt);

            /* -------------------------------------------------------------------- */
            /*      Reading the fields                                              */
            /* -------------------------------------------------------------------- */
            Console.WriteLine("Field definition:");
            for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
            {
                FieldDefn fdef = def.GetFieldDefn(iAttr);

                Console.WriteLine(fdef.GetNameRef() + ": " +
                                  fdef.GetFieldTypeName(fdef.GetFieldType()) + " (" +
                                  fdef.GetWidth() + "." +
                                  fdef.GetPrecision() + ")");
            }

            /* -------------------------------------------------------------------- */
            /*      Reading the shapes                                              */
            /* -------------------------------------------------------------------- */
            Console.WriteLine("");
            Feature feat;

            while ((feat = layer.GetNextFeature()) != null)
            {
                ReportFeature(feat, def);
                feat.Dispose();
            }
        }
Exemplo n.º 13
0
        public int TransformTo(OSGeo.OSR.SpatialReference reference)
        {
            int ret = OgrPINVOKE.Geometry_TransformTo(swigCPtr, OSGeo.OSR.SpatialReference.getCPtr(reference));

            if (OgrPINVOKE.SWIGPendingException.Pending)
            {
                throw OgrPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Exemplo n.º 14
0
 public static OSGeo.OSR.SpatialReference GetSpatialReference(this Dataset dataset)
 {
     OSGeo.OSR.SpatialReference spatialReference = null;
     if (dataset == null)
     {
         return(spatialReference);
     }
     spatialReference = new OSGeo.OSR.SpatialReference(dataset.GetProjection());
     return(spatialReference);
 }
Exemplo n.º 15
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();

            ///Working with data trees allows us to only call the osr coordinate transformation once, which seems to be expensive
            GH_Structure <GH_Point> sourcePoints = new GH_Structure <GH_Point>();

            DA.GetDataTree(0, out sourcePoints);

            GH_Structure <GH_Point> destPoints = new GH_Structure <GH_Point>();

            string sourceString = string.Empty;

            DA.GetData(1, ref sourceString);
            OSGeo.OSR.SpatialReference sourceSRS = new OSGeo.OSR.SpatialReference("");
            sourceSRS.SetFromUserInput(sourceString);
            if (sourceSRS.Validate() == 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Source SRS.");
                return;
            }

            string destString = string.Empty;

            DA.GetData(2, ref destString);
            OSGeo.OSR.SpatialReference destSRS = new OSGeo.OSR.SpatialReference("");
            destSRS.SetFromUserInput(destString);
            if (destSRS.Validate() == 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Destination SRS.");
                return;
            }

            OSGeo.OSR.CoordinateTransformation trans = new OSGeo.OSR.CoordinateTransformation(sourceSRS, destSRS);

            foreach (var path in sourcePoints.Paths)
            {
                List <GH_Point> branchPts = (List <GH_Point>)sourcePoints.get_Branch(path);
                foreach (var sp in branchPts)
                {
                    OSGeo.OGR.Geometry destOgrPoint = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint);
                    destOgrPoint.AddPoint(sp.Value.X, sp.Value.Y, sp.Value.Z);
                    destOgrPoint.AssignSpatialReference(sourceSRS);

                    destOgrPoint.Transform(trans);
                    Point3d destPoint = new Point3d(destOgrPoint.GetX(0), destOgrPoint.GetY(0), destOgrPoint.GetZ(0));

                    destPoints.Append(new GH_Point(destPoint), path);
                    destOgrPoint.Dispose();
                }
            }

            DA.SetDataTree(0, destPoints);
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
        public int GetSrid()
        {
            int srid = -1;

            OSGeo.OSR.SpatialReference pSpatialReference = _ogrLayer.GetSpatialRef();
            if (pSpatialReference != null)
            {
                srid = pSpatialReference.AutoIdentifyEPSG();
            }
            return(srid);
        }
Exemplo n.º 18
0
 public static void CoordTransformToWgs84(this OSGeo.OSR.SpatialReference srcSR, ref double x, ref double y)
 {
     using (OSGeo.OSR.SpatialReference destSR = new OSGeo.OSR.SpatialReference(""))
     {
         destSR.SetWellKnownGeogCS("EPSG:4326");
         double[] inout = { x, y };
         CoordTransform(srcSR, destSR, inout);
         x = inout[0];
         y = inout[1];
     }
 }
Exemplo n.º 19
0
        public Layer CreateLayer(string name, OSGeo.OSR.SpatialReference srs, wkbGeometryType geom_type, string[] options)
        {
            IntPtr cPtr = OgrPINVOKE.DataSource_CreateLayer(swigCPtr, name, OSGeo.OSR.SpatialReference.getCPtr(srs), (int)geom_type, (options != null)? new OgrPINVOKE.StringListMarshal(options)._ar : null);
            Layer  ret  = (cPtr == IntPtr.Zero) ? null : new Layer(cPtr, false, ThisOwn_false());

            if (OgrPINVOKE.SWIGPendingException.Pending)
            {
                throw OgrPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Exemplo n.º 20
0
        public OSGeo.OSR.SpatialReference GetSpatialRef()
        {
            IntPtr cPtr = OgrPINVOKE.Layer_GetSpatialRef(swigCPtr);

            OSGeo.OSR.SpatialReference ret = (cPtr == IntPtr.Zero) ? null : new OSGeo.OSR.SpatialReference(cPtr, true, ThisOwn_true());
            if (OgrPINVOKE.SWIGPendingException.Pending)
            {
                throw OgrPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Exemplo n.º 21
0
        public static Geometry CreateGeometryFromWkt(ref string val, OSGeo.OSR.SpatialReference reference)
        {
            IntPtr   cPtr = OgrPINVOKE.CreateGeometryFromWkt(ref val, OSGeo.OSR.SpatialReference.getCPtr(reference));
            Geometry ret  = (cPtr == IntPtr.Zero) ? null : new Geometry(cPtr, true, ThisOwn_true());

            if (OgrPINVOKE.SWIGPendingException.Pending)
            {
                throw OgrPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Exemplo n.º 22
0
        public void GetProjString(string file)
        {
            using var dataset = Gdal.Open(file, Access.GA_ReadOnly);

            string wkt = dataset.GetProjection();

            using var spatialReference = new OSGeo.OSR.SpatialReference(wkt);

            spatialReference.ExportToProj4(out string projString);

            Assert.False(string.IsNullOrWhiteSpace(projString));
        }
Exemplo n.º 23
0
        private static void SelectRandomFeatureWeighted(string dataSetPath, int sampleSize)
        {
            ColumnScale <string> columnScale = Program.SpatialIndexAdvanced(dataSetPath);

            List <dynamic> result        = new List <dynamic>();
            Driver         fileGdbDriver = Ogr.GetDriverByName("OpenFileGDB");
            DataSource     dataSource    = fileGdbDriver.Open(dataSetPath, 0);

            Layer            layer            = dataSource.GetLayerByIndex(0);
            SpatialReference spatialReference = layer.GetSpatialRef();

            List <int> featureIds = new List <int>();
            Random     random     = new Random();

            for (int i = 0; i < sampleSize; i++)
            {
                double randomValue = random.NextDouble();
                KeyValuePair <string, ColumnValueScale> columnValueScale = columnScale.ColumnValueScales
                                                                           .Where(x => x.Value.ProbabilityLimit > randomValue)
                                                                           .Where(x => x.Value.Features.Any(y => !featureIds.Contains(y.FeatureId)))
                                                                           .OrderBy(x => x.Value.ProbabilityLimit)
                                                                           .FirstOrDefault();

                if (columnValueScale.Value != null)
                {
                    FeatureScale featureScale;

                    do
                    {
                        randomValue = random.NextDouble();

                        featureScale = columnValueScale.Value.Features.Where(x => x.ProbabilityLimit > randomValue)
                                       .Where(x => !featureIds.Contains(x.FeatureId))
                                       .OrderBy(x => x.ProbabilityLimit)
                                       .FirstOrDefault();
                    }while (featureScale != null && featureIds.Contains(featureScale.FeatureId));

                    Feature feature = layer.GetFeature(featureScale.FeatureId);
                    featureIds.Add(featureScale.FeatureId);

                    result.Add(new
                    {
                        FeatureId       = feature.GetFID(),
                        Classification  = feature.GetFieldAsString("CODE2012"),
                        FeatureGeometry = Tools.GetSampleItemGeometriesPolygon(feature, spatialReference),
                    });
                }
            }

            Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions {
                WriteIndented = true
            }));
        }
Exemplo n.º 24
0
 public static SpatialReference getSR(Layer layer, RecordSet metadata)
 {
     if (metadata.Crs == null || metadata.Crs == "")
     {
         SpatialReference crs = layer.GetSpatialRef();
         if (crs != null)
         {
             return(crs);
         }
         return(AppState.instance.projectCrs);
     }
     return(Convert.TextToSR(metadata.Crs));
 }
Exemplo n.º 25
0
        public Ogr(string filename, string layerName)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 1);
            _ogrLayer      = _ogrDataSource.GetLayerByName(layerName);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();

            if (spatialReference != null)
            {
                _srid = spatialReference.AutoIdentifyEPSG();
            }
        }
Exemplo n.º 26
0
 public static void CoordTransform(this OSGeo.OSR.SpatialReference srcSR, OSGeo.OSR.SpatialReference destSR, params double[][] inouts)
 {
     if (srcSR.IsSame(destSR) <= 0)
     {
         using (OSGeo.OSR.CoordinateTransformation coordinateTransformation = new OSGeo.OSR.CoordinateTransformation(srcSR, destSR))
         {
             foreach (var inout in inouts)
             {
                 coordinateTransformation.TransformPoint(inout);
             }
         }
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// Loads a Ogr datasource with the specified layer
        /// </summary>
        /// <param name="filename">datasource</param>
        /// <param name="layerNum">number of layer</param>
        public Ogr(string filename, int layerNum)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 0);
            _ogrLayer      = _ogrDataSource.GetLayerByIndex(layerNum);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();

            if (spatialReference != null)
            {
                SRID = spatialReference.AutoIdentifyEPSG();
            }
        }
Exemplo n.º 28
0
        public double GetArea()
        {
            var data = Value.GetGeometryRef();

            if (data == null)
            {
                return(0.0);
            }
            SpatialReference spatialReference = new SpatialReference(Constants.Epsg3035Wkt);

            data.TransformTo(spatialReference);

            return(data.GetArea());
        }
Exemplo n.º 29
0
        public static string Amersfoort()
        {
            string proj4 =
                "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs";


            using(var osrs= new SpatialReference("+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs"))
            {
                Ogr.RegisterAll();
                string stringOutput;
                osrs.ExportToProj4(out stringOutput);
                return stringOutput;
            }
        }
Exemplo n.º 30
0
        public static string Amersfoort()
        {
            string proj4 =
                "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs";


            using (var osrs = new SpatialReference("+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +units=m +no_defs"))
            {
                Ogr.RegisterAll();
                string stringOutput;
                osrs.ExportToProj4(out stringOutput);
                return(stringOutput);
            }
        }
Exemplo n.º 31
0
        private LayerWrapper Wgs84Layer(string name, wkbGeometryType wkbGeometryType)
        {
            OSGeo.OGR.Layer  layerSH;
            SpatialReference spatialReference = new SpatialReference(Constants.Epsg4326Wkt);

            layerSH = _dataSource.CreateLayer(name, spatialReference, wkbGeometryType, new string[] { });
            if (layerSH == null)
            {
                Console.WriteLine("Layer creation failed, exiting...");
                return(null);
            }

            Console.WriteLine($"{wkbGeometryType} Layer created");
            return(new LayerWrapper(layerSH));
        }
Exemplo n.º 32
0
        // reads .prj files
        public static IProjection read(string filename)
        {
            // reads all text in file
            string input = File.ReadAllText(filename);
            string proj4 = null;

            OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference("");
            string[] ESRI = {input};
            // converts text to spatial reference
            oSRS.ImportFromESRI(ESRI);
            // converts spatial reference to proj4-representation
            oSRS.ExportToProj4(out proj4);

            // returns proj4 srs object
            return Proj4CSharp.Proj4CSharp.ProjectionFactory(proj4);
        }
Exemplo n.º 33
0
        public static string  EsriToProj4(string esriProjectionPath)
        {
            OSGeo.OSR.SpatialReference oSRS= new SpatialReference("");
           if (oSRS.SetFromUserInput(esriProjectionPath)!=Ogr.OGRERR_NONE)
           {
               throw new ApplicationException(string.Format("Error occured translating {0}",esriProjectionPath));
           }

            string proj4OutputString;
            if( oSRS.ExportToProj4(out proj4OutputString)==Ogr.OGRERR_NONE)
            {
                return proj4OutputString;
            }
            else
            {
                throw new ApplicationException("Export to proj4 failed");
            }

/*
            if (nArgc != 2)
            {
                printf("Usage: wkt2proj4 [srtext def or srtext file]\n");
                exit(1);
            }

            if (oSRS.SetFromUserInput(papszArgv[1]) != OGRERR_NONE)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                        "Error occured translating %s.\n", papszArgv[1]);
            }

            oSRS.morphFromESRI();

            char* pszProj4 = NULL;

            if (oSRS.exportToProj4(&pszProj4) == OGRERR_NONE)
            {
                printf("%s\n", pszProj4);
            }
            else
            {
                fprintf(stderr, "exportToProj4() failed.\n");
            }

*/
        }
Exemplo n.º 34
0
Arquivo: SGIS.cs Projeto: hakbra/SGIS
        // returns wkt-representation of current srs
        public string getSrsName()
        {
            OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference("");
            oSRS.ImportFromProj4(SRS.ToString());

            if (oSRS.IsProjected() == 1)
                return oSRS.GetAttrValue("projcs", 0);
            return oSRS.GetAttrValue("geogcs", 0);
        }
Exemplo n.º 35
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();
            });
        }
Exemplo n.º 36
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);
        }