Example #1
3
 public static IGeometry Project(IGeometry geometry, ProjectionInfo pStart, ProjectionInfo pEnd)
 {
     var featureSet = new FeatureSet();
     featureSet.AddFeature(geometry.ToDotSpatial());
     featureSet.Projection = pStart;
     featureSet.Reproject(pEnd);
     return
         GeometryConverter.ToGeoAPI(
             ((featureSet.Features[0].BasicGeometry as DotSpatial.Topology.IGeometry)));
 }
Example #2
0
        /// <summary>
        /// This function creates the HDR of Gridfile
        /// </summary>
        /// <param name="inExtents"> Extension of grid</param>
        /// <param name="cellSize">Size cell of the grid</param>
        /// <param name="projection">Projection (the same that shapefile)</param>
        /// <param name="noDataValue">No value definition</param>
        /// <param name="outGridPath">Path of the output</param>
        /// <param name="outGrid">Name of the output grid</param>
        public static void CreateGridFromExtents(
            Extent inExtents, double cellSize, ProjectionInfo projection, double noDataValue, string outGridPath, out IRaster outGrid)
        {

            double height = Math.Abs(inExtents.MaxY - inExtents.MinY);
            double width = Math.Abs(inExtents.MaxX - inExtents.MinX);
            int numberRows = Convert.ToInt32(Math.Ceiling(height / cellSize)) + 1;
            int numberCols = Convert.ToInt32(Math.Ceiling(width / cellSize)) + 1;

            // outGrid = Raster.CreateRaster(@outGridPath, null, demRaster.NumColumns, demRaster.NumRows, 1, demRaster.DataType, rasterOptions);
            outGrid = Raster.CreateRaster(@outGridPath, null, numberCols, numberRows, 1, typeof(float), new String[] { });
            outGrid.NoDataValue = noDataValue;
            outGrid.Projection = projection;
            outGrid.CellHeight = cellSize;
            outGrid.CellWidth = cellSize;
            //if (inExtents.MinX < 0)
            //    outGrid.Xllcenter = inExtents.MinX + (cellSize / 2.0);
            //else
            outGrid.Xllcenter = inExtents.MinX;// -(cellSize / 2.0);

            //if (inExtents.MinY < 0)
            //    outGrid.Yllcenter = inExtents.MinY + (cellSize / 2.0);
            //else
            outGrid.Yllcenter = inExtents.MinY;// -(cellSize / 2.0);
        }
		private static double[] ReprojectPoint(double[] sourcePoint, double z, ProjectionInfo sourceProj, ProjectionInfo destProj)
		{
			// Calls the reproject function that will transform the input location to the output locaiton
			Reproject.ReprojectPoints(sourcePoint, new double[] { z }, sourceProj, destProj, 0, 1);

			return sourcePoint;
		}
 public static Coordinate Reproject(this Coordinate c, ProjectionInfo source, ProjectionInfo target)
 {
     var ordinates = new[] { c.X, c.Y };
     var z = new[] {double.IsNaN(c.Z) ? 0 : c.Z};
     Projections.Reproject.ReprojectPoints(ordinates, z, source, target, 0, 1);
     return new Coordinate(ordinates);
 }
Example #5
0
        /// <summary>
        /// This method reprojects the affine transform coefficients.  This is used for projection on the fly,
        /// where image transforms can take advantage of an affine projection, but does not have the power of
        /// a full projective transform and gets less and less accurate as the image covers larger and larger
        /// areas.  Since most image layers represent small rectangular areas, this should not be a problem in
        /// most cases.  the affine array should be ordered as follows:
        /// X' = [0] + [1] * Column + [2] * Row
        /// Y' = [3] + [4] * Column + [5] * Row
        /// </summary>
        /// <param name="affine">The array of double affine coefficients.</param>
        /// <param name="numRows">The number of rows to use for the lower bounds.  Value of 0 or less will be set to 1.</param>
        /// <param name="numCols">The number of columns to use to get the right bounds.  Values of 0 or less will be set to 1.</param>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <returns>The transformed coefficients</returns>
        public static double[] ReprojectAffine(double[] affine, double numRows, double numCols, ProjectionInfo source, ProjectionInfo dest)
        {
            if (numRows <= 0) numRows = 1;
            if (numCols <= 0) numCols = 1;

            double[] vertices = new double[6];
            // Top left
            vertices[0] = affine[0];
            vertices[1] = affine[3];
            // Top right
            vertices[2] = affine[0] + affine[1] * numCols;
            vertices[3] = affine[3] + affine[4] * numCols;
            // Bottom Left
            vertices[4] = affine[0] + affine[2] * numRows;
            vertices[5] = affine[3] + affine[5] * numRows;
            double[] z = new double[3];
            ReprojectPoints(vertices, z, source, dest, 0, 3);
            double[] affineResult = new double[6];

            affineResult[0] = vertices[0];
            affineResult[1] = (vertices[2] - vertices[0]) / numCols;
            affineResult[2] = (vertices[4] - vertices[0]) / numRows;

            affineResult[3] = vertices[1];
            affineResult[4] = (vertices[3] - vertices[1]) / numCols;
            affineResult[5] = (vertices[5] - vertices[1]) / numRows;

            return affineResult;
        }
 public ReprojectSqlServer(ProjectionInfo source, int sourceSRID, ProjectionInfo target, int targetSRID)
 {
     _proj_source = source;
     _proj_target = target;
     _srid_source = sourceSRID;
     _srid_target = targetSRID;
 }
        /// <summary>
        /// Creates an instance of this class
        /// </summary>
        public DotSpatialSpatialReference(ProjectionInfo projectionInfo)
        {
            _oid = projectionInfo.ToProj4String();
            Definition = projectionInfo.ToProj4String();
            ProjectionInfo = projectionInfo;

        }
    public static SqlChars EPSG2193_Centroid_to_Longitude(string Geometry_String)
    {
        string Destination_Coordinate_System_String = EPSG4126;
        String Geometry_Type = Geometry_String.Substring(0, Geometry_String.IndexOf(" "));

        switch (Geometry_Type)
        {
        case "POINT":
            Geometry_Type = "Point";
            break;

        default:
            Geometry_Type = "not_supported";
            return(null);
        }

        Geometry_String = Geometry_String.Remove(0, Geometry_String.IndexOf('('));
        Geometry_String = Geometry_String.Replace("(", "");
        Geometry_String = Geometry_String.Replace(")", "");

        double[] xy = Array.ConvertAll(Geometry_String.Split(' '), double.Parse);
        double[] z  = new double[1];
        z[0] = 0;

        DotSpatial.Projections.ProjectionInfo src = DotSpatial.Projections.ProjectionInfo.FromProj4String(EPSG2193);
        DotSpatial.Projections.ProjectionInfo trg = DotSpatial.Projections.ProjectionInfo.FromProj4String(EPSG4126);
        DotSpatial.Projections.Reproject.ReprojectPoints(xy, z, src, trg, 0, 1);

        return(new SqlChars(xy[0].ToString()));
    }
Example #9
0
 public static ShapeFileModel OpenFile(string file, ProjectionInfo projection)
 {
     var res = new ShapeFileModel();
     res.File = file;
     res.Shape = Shapefile.OpenFile(file);
     if (projection != null) res.Shape.Reproject(projection);
     return res;
 }
        /// <summary>
        /// Transforms a <see cref="SharpMap.Geometries.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.Left, box.Bottom, box.Left, box.Top, box.Right, box.Top, box.Right, box.Bottom };
            Reproject.ReprojectPoints(corners, null, from, to, 0, 4);

            return new BoundingBox(corners[0], corners[1], corners[4], corners[5]).Join(
                   new BoundingBox(corners[2], corners[3], corners[6], corners[7]));
        }
Example #11
0
 /// <summary>
 /// Creates a new instance of a Projection Param with the specified name
 /// and the specified projection as the default projection that will
 /// appear if no changes are made.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="defaultProjection"></param>
 public ProjectionParam(string name, ProjectionInfo defaultProjection)
 {
     Name = name;
     Value = defaultProjection;
     ParamVisible = ShowParamInModel.No;
     ParamType = "DotSpatial String Param";
     DefaultSpecified = true;
 }
Example #12
0
static Extent Reproject(Extent extent, ProjectionInfo source, ProjectionInfo target, int depth = 0)
{
    var xy = ToSequence(extent);
    DotSpatial.Projections.Reproject.ReprojectPoints(xy, null, source, target, 0, xy.Length / 2);
    var res = ToExtent(xy);

    return res;
}
 /// <summary>
 /// use the mapFrame with this dialog
 /// </summary>
 /// <param name="mapFrame"></param>
 public MapFrameProjectionDialog(IMapFrame mapFrame)
 {
     InitializeComponent();
     _mapFrame = mapFrame;
     _projection = new ProjectionInfo();
     _projection.CopyProperties(_mapFrame.Projection);
     UpdateProjectionStrings();
 }
Example #14
0
 public static string ToGeoJson(System.Data.Entity.Spatial.DbGeometry location, ProjectionInfo pStart,
     ProjectionInfo pEnd)
 {
     var wktReader = new WKTReader();
     var geometry = wktReader.Read(location.WellKnownValue.WellKnownText);
     geometry = Project(geometry, pStart, pEnd);
     var geoJsonWriter = new GeoJsonWriter();
     return geoJsonWriter.Write(geometry);
 }
Example #15
0
 public void SetAreaRectangle(Extent extent, ProjectionInfo rectangleProjection)
 {
     var xMin = extent.MinX;
     var yMin = extent.MinY;
     var xMax = extent.MaxX;
     var yMax = extent.MaxY;
     var box = new Box(xMin, xMax, yMin, yMax);
     SetAreaRectangle(box, rectangleProjection);
 }
        /// <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;
        }
        /// <summary>
        /// Transforms a <see cref="GeoAPI.Geometries.Coordinate"/>.
        /// </summary>
        /// <param name="c">Point to transform</param>
        /// <param name="from">Source Projection</param>
        /// <param name="to">Target Projection</param>
        /// <returns>Transformed coordinate</returns>
        public static Coordinate TransformCoordinate(Coordinate c, ProjectionInfo from, ProjectionInfo to)
        {
            var xy = c.ToDoubleArray();
            double[] z = !Double.IsNaN(c.Z) ? new double[1] : null;

            Reproject.ReprojectPoints(xy, z, from, to, 0, 1);
            return new Coordinate(xy[0], xy[1]) {Z = z != null ? z[0] : Coordinate.NullOrdinate};

        }
Example #18
0
        /// <summary>Creates a new instance of the <see cref="CoordinateSystem" /> class.</summary>
        /// <param name="projection">The original system to encapsulate.</param>
        internal CoordinateSystem(DsProjections.ProjectionInfo projection)
        {
            Debug.Assert(projection != null);
            if (projection == null)
            {
                throw new ArgumentNullException("projection");
            }

            _Projection = projection;
        }
Example #19
0
        public static Proj4Crs Wrap(ProjectionInfo projectionInfo)
        {
            if (projectionInfo == null) throw new ArgumentNullException("projectionInfo");
            Contract.EndContractBlock();

            if (projectionInfo.Transform == null || projectionInfo.IsLatLon) {
                return new Proj4CrsGeographic(projectionInfo.GeographicInfo);
            }

            return new Proj4CrsProjected(projectionInfo);
        }
Example #20
0
        private static DotSpatial.Projections.ICoordinateTransformation GetCoordinateTransformation()
        {
            var epsg4326 = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            var epsg3785 = new DotSpatial.Projections.ProjectionInfo();

            epsg3785.ReadEsriString("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3785\"]]");
            return(new DotSpatial.Projections.CoordinateTransformation()
            {
                Source = epsg4326, Target = epsg3785
            });
#endif
        }
Example #21
0
 public WmsInfo(string serverUrl, WmsCapabilities wmsCapabilities, Layer layer, Dictionary<string, string> customParameters,
     string crs, ProjectionInfo projectionInfo, string style, NetworkCredential credentials)
 {
     Credentials = credentials;
     CustomParameters = customParameters;
     CRS = crs;
     CrsProjectionInfo = projectionInfo;
     Style = style;
     Layer = layer;
     WmsCapabilities = wmsCapabilities;
     ServerUrl = serverUrl;
 }
 /// <summary>
 /// Transforms a <see cref="SharpMap.Geometries.Point"/>.
 /// </summary>
 /// <param name="p">Point to transform</param>
 /// <param name="from">Source Projection</param>
 /// <param name="to">Target Projection</param>
 /// <returns>Transformed Point</returns>
 public static Point TransformPoint(Point p, ProjectionInfo from, ProjectionInfo to)
 {
     try
     {
         double[] coords = p.ToDoubleArray();
         Reproject.ReprojectPoints(coords, null, from, to, 0, 1);
         return new Point(coords);
     }
     catch
     {
         return null;
     }
 }
        public static IPolygon Reproject(this IPolygon polygon, ProjectionInfo source, ProjectionInfo target)
        {
            var shell = Reproject(polygon.Shell, source, target);
            ILinearRing[] holes = null;
            if (polygon.NumHoles > 0)
            {
                holes = new ILinearRing[polygon.NumHoles];
                var i = 0;
                foreach (var hole in polygon.Holes)
                    holes[i++] = Reproject(hole, source, target);
            }

            return polygon.Factory.CreatePolygon(shell, holes);
        }
Example #24
0
 /// <summary>
 /// Creates an instance of this class
 /// </summary>
 /// <param name="tileSource">The tile source to use</param>
 /// <param name="tileCache">The tile cache to use</param>
 public BruTileLayer(ITileSource tileSource, ITileCache<byte[]> tileCache)
 {
     TileSource = tileSource;
     TileCache = tileCache;
     int epsgCode;
     if (int.TryParse(TileSource.Schema.Srs.Substring(5), out epsgCode))
     {
         _projection = new ProjectionInfo();
         _projection = ProjectionInfo.FromEpsgCode(epsgCode);
     }
     else
         _projection = KnownCoordinateSystems.Projected.World.WebMercator;
     LegendItemVisible = true;
 }
Example #25
0
 public static string ToGeoJson(IEnumerable<System.Data.Entity.Spatial.DbGeometry> dbGeometrys,
     ProjectionInfo pStart)
 {
     var pEnd = Definitions.WorldProjection;
     var enumerable = dbGeometrys as IList<System.Data.Entity.Spatial.DbGeometry> ?? dbGeometrys.ToList();
     var reader = new WKTReader();
     var geometryCollection =
         new GeometryCollection(
             enumerable.Select(x => GeometryHelper.Project(x.MakeValid(), pStart, pEnd))
                 .Select(dbGeometry => reader.Read(dbGeometry.WellKnownValue.WellKnownText))
                 .ToArray());
     var geoJsonWriter = new GeoJsonWriter();
     return geoJsonWriter.Write(geometryCollection);
 }
        /// <summary>
        /// Enumerates through location code boundary features in a shapefile.
        /// </summary>
        /// <param name="shapePath">The path to a shapefile.</param>
        /// <param name="targetProjection">Optional. Provide to reproject from 2927.</param>
        /// <returns>Returns an <see cref="IEnumerable&lt;T&gt;"/> of <see cref="Feature"/> objects.</returns>
        public static IEnumerable<IFeature> EnumerateLocationCodeBoundaries(string shapePath, ProjectionInfo targetProjection = null)
        {
            using (var fs = FeatureSet.Open(shapePath))
            {
                if (targetProjection != null)
                {
                    fs.Reproject(targetProjection);
                }
                for (int i = 0, l = fs.NumRows(); i < l; i++)
                {
                    var feature = fs.GetFeature(i) as IFeature;
                    yield return feature;
                }
            }

        }
Example #27
0
 public static System.Data.Entity.Spatial.DbGeometry Project(System.Data.Entity.Spatial.DbGeometry source,
     ProjectionInfo pStart, ProjectionInfo pEnd)
 {
     var wkt = source.WellKnownValue.WellKnownText;
     var wktReader = new WKTReader();
     var geometry = wktReader.Read(wkt);
     var featureSet = new FeatureSet();
     featureSet.Features.Add(geometry.ToDotSpatial());
     featureSet.Projection = pStart;
     featureSet.Reproject(pEnd);
     var projected =
         (featureSet.Features.First().BasicGeometry as IGeometry).ToGeoAPI();
     var wktWriter = new WKTWriter();
     var projectedWkt = wktWriter.Write(projected);
     return System.Data.Entity.Spatial.DbGeometry.FromText(projectedWkt);
 }
		public static SqlGeometry ReprojectTo(this SqlGeometry geom, ProjectionInfo destination)
		{
			Func<double[], double[]> reprojectionFunc = SqlGeometryReprojection.Identity;

			// Defines the starting coordiante system
			ProjectionInfo pStart = ProjectionInfo.FromEpsgCode(geom.STSrid.Value);
			// Defines the starting coordiante system
			ProjectionInfo pEnd = destination;

			reprojectionFunc = pts => SqlGeometryReprojection.ReprojectPoint(pts, 0, pStart, pEnd);

			GeometryToGeometrySink sink = new GeometryToGeometrySink(destination.AuthorityCode, pts => reprojectionFunc(pts));
			geom.Populate(sink);

			return sink.ConstructedGeometry;
		}
Example #29
0
        public void Wgs84ToKrovak_KnownCoordSys()
        {
            double[] myOut = new double[2];
            myOut[0] = 12.8069888666667;
            myOut[1] = 49.4522626972222;
            double[] myZ = new double[1];
            myZ[0] = 0;

            ProjectionInfo source = KnownCoordinateSystems.Geographic.World.WGS1984;

            DotSpatial.Projections.ProjectionInfo myJTSKPI = KnownCoordinateSystems.Projected.NationalGrids.SJTSKKrovakEastNorth;

            DotSpatial.Projections.Reproject.ReprojectPoints(myOut, myZ, source, myJTSKPI, 0, myZ.Length);

            Assert.AreEqual(myOut[0], -868208.52, 1.0);
            Assert.AreEqual(myOut[1], -1095793.96, 1.0);
        }
Example #30
0
        public void Wgs84ToKrovakWithTransform()
        {
            double[] myOut = new double[2];
            myOut[0] = 12.8069888666667;
            myOut[1] = 49.4522626972222;
            double[] myZ = new double[1];
            myZ[0] = 0;

            ProjectionInfo source    = KnownCoordinateSystems.Geographic.World.WGS1984;
            string         projJTSK2 = "+proj=krovak +lat_0=49.5 +lon_0=24.83333333333333 +alpha=0 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +units=m +no_defs";

            DotSpatial.Projections.ProjectionInfo myJTSKPI = DotSpatial.Projections.ProjectionInfo.FromProj4String(projJTSK2);

            DotSpatial.Projections.Reproject.ReprojectPoints(myOut, myZ, source, myJTSKPI, 0, myZ.Length);

            Assert.AreEqual(myOut[0], -868208.52, 1.0);
            Assert.AreEqual(myOut[1], -1095793.96, 1.0);
        }
Example #31
0
        private void Reproject(DotSpatial.Projections.ProjectionInfo proj)
        {
            LogManager.DefaultLogManager.LogMessage(string.Format("Reprojecting from '{0}' to '{1};'", map.Projection.Name, proj.Name), DialogResult.OK);

            var extents       = map.ViewExtents;
            var oldProjection = map.Projection;

            map.Projection = proj;
            var newExtents = Reproject(extents, oldProjection, map.Projection);

            foreach (var layer in map.Layers)
            {
                layer.Reproject(map.Projection);
            }

            map.ViewExtents = newExtents;
            map.Invalidate();
        }
Example #32
0
        public void KrovakToWgs84_KnownCoordSys()
        {
            double[] myOut = new double[2];
            myOut[0] = -868208.52;
            myOut[1] = -1095793.96;
            double[] myZ = new double[1];
            myZ[0] = 0;

            ProjectionInfo projWGS84 = KnownCoordinateSystems.Geographic.World.WGS1984;
            string         projJTSK2 = "+proj=krovak +lat_0=49.5 +lon_0=24.83333333333333 +alpha=0 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +towgs84=570.8,85.7,462.8,4.998,1.587,5.261,3.56 +units=m +no_defs";

            DotSpatial.Projections.ProjectionInfo myJTSKPI = DotSpatial.Projections.KnownCoordinateSystems.Projected.NationalGrids.SJTSKKrovakEastNorth;

            DotSpatial.Projections.Reproject.ReprojectPoints(myOut, myZ, myJTSKPI, projWGS84, 0, myZ.Length);

            Assert.AreEqual(myOut[0], 12.8069888666667, 1.0);
            Assert.AreEqual(myOut[1], 49.4522626972222, 1.0);
        }
Example #33
0
        public void KrovakToWgs84_EsriString()
        {
            double[] myOut = new double[2];
            myOut[0] = -868208.52;
            myOut[1] = -1095793.96;
            double[] myZ = new double[1];
            myZ[0] = 0;

            string jtskEsriString = @"PROJCS[""S-JTSK_Krovak_East_North"",GEOGCS[""GCS_S_JTSK"",DATUM[""D_S_JTSK"",SPHEROID[""Bessel_1841"",6377397.155,299.1528128]],PRIMEM[""Greenwich"",0.0],UNIT[""Degree"",0.0174532925199433]],PROJECTION[""Krovak""],PARAMETER[""False_Easting"",0.0],PARAMETER[""False_Northing"",0.0],PARAMETER[""Pseudo_Standard_Parallel_1"",78.5],PARAMETER[""Scale_Factor"",0.9999],PARAMETER[""Azimuth"",30.28813975277778],PARAMETER[""Longitude_Of_Center"",24.83333333333333],PARAMETER[""Latitude_Of_Center"",49.5],PARAMETER[""X_Scale"",-1.0],PARAMETER[""Y_Scale"",1.0],PARAMETER[""XY_Plane_Rotation"",90.0],UNIT[""Meter"",1.0]]";

            ProjectionInfo projWGS84 = KnownCoordinateSystems.Geographic.World.WGS1984;

            DotSpatial.Projections.ProjectionInfo myJTSKPI = DotSpatial.Projections.ProjectionInfo.FromEsriString(jtskEsriString);

            DotSpatial.Projections.Reproject.ReprojectPoints(myOut, myZ, myJTSKPI, projWGS84, 0, myZ.Length);

            Assert.AreEqual(myOut[0], 12.8069888666667, 1.0);
            Assert.AreEqual(myOut[1], 49.4522626972222, 1.0);
        }
        /// <summary>
        /// Enumerates through location code boundary features.
        /// </summary>
        /// <param name="quarterYear">A quarter year.</param>
        /// <param name="targetProjection">Optional. Provide to reproject from 2927.</param>
        /// <returns>Returns an <see cref="IEnumerable&lt;T&gt;"/> of <see cref="Feature"/> objects.</returns>
        public static IEnumerable<IFeature> EnumerateLocationCodeBoundaries(QuarterYear quarterYear, ProjectionInfo targetProjection = null)
        {
            var uri = new Uri(string.Format(_locCodeBoundariesShpUrlPattern, quarterYear.GetDateRange()[0], quarterYear.Quarter));
            // Get the path to the TEMP directory.
            string tempDirPath = Path.GetTempPath();
            string dir = Path.Combine(tempDirPath, Path.GetRandomFileName());
            DirectoryInfo dirInfo = Directory.CreateDirectory(dir);
            string shp_name = null;

            try
            {
                var client = new HttpClient();
                client.GetStreamAsync(uri).ContinueWith(st =>
                {
                    // Write the shapefile to a temporary location.
                    using (var zipArchive = new ZipArchive(st.Result, ZipArchiveMode.Read))
                    {
                        foreach (var entry in zipArchive.Entries)
                        {
                            using (var outfile = File.Create(Path.Combine(dir, entry.Name)))
                            using (var sourcefile = entry.Open())
                            {
                                sourcefile.CopyToAsync(outfile).Wait();
                            }
                            if (entry.Name.EndsWith(".shp", StringComparison.InvariantCultureIgnoreCase))
                            {
                                shp_name = Path.Combine(dir, entry.Name);
                            }
                        }
                    }
                }).Wait();

                foreach (var kvp in EnumerateLocationCodeBoundaries(shp_name, targetProjection))
                {
                    yield return kvp;
                }

            }
            finally
            {
                dirInfo.Delete(true);
            }
        }
Example #35
0
 public static List<IGeometry> Project(List<IGeometry> toList, ProjectionInfo pStart, ProjectionInfo pEnd)
 {
     var geometryCollection = new GeometryCollection(toList.ToArray());
     var collection = geometryCollection.ToDotSpatial();
     var featureSet = new FeatureSet();
     foreach (var geo in collection.Geometries)
     {
         featureSet.Features.Add(geo);
     }
     featureSet.Projection = pStart;
     featureSet.Reproject(pEnd);
     var dotSpatialProjectedGeos =
         featureSet.Features.Select(x => x.BasicGeometry as DotSpatial.Topology.IGeometry).ToList();
     var result =
         dotSpatialProjectedGeos.Select(
             dotSpatialProjectedGeo => GeometryConverter.ToGeoAPI((dotSpatialProjectedGeo)))
             .ToList();
     return result;
 }
 /// <summary>
 /// Transforms a <see cref="GeoAPI.Geometries.IGeometry"/>.
 /// </summary>
 /// <param name="g">Geometry to transform</param>
 /// <param name="from">Source Projection</param>
 /// <param name="to">Target Projection</param>
 /// <param name="toFactory">The factory to create the transformed geometry</param>
 /// <returns>Transformed Geometry</returns>
 public static IGeometry TransformGeometry(IGeometry g, ProjectionInfo from, ProjectionInfo to, IGeometryFactory toFactory)
 {
     if (g == null)
         return null;
     if (g is IPoint)
         return TransformPoint(g as IPoint, from, to, toFactory);
     if (g is ILineString)
         return TransformLineString(g as ILineString, from, to, toFactory);
     if (g is IPolygon)
         return TransformPolygon(g as IPolygon, from, to, toFactory);
     if (g is IMultiPoint)
         return TransformMultiPoint(g as IMultiPoint, from, to, toFactory);
     if (g is IMultiLineString)
         return TransformMultiLineString(g as IMultiLineString, from, to, toFactory);
     if (g is IMultiPolygon)
         return TransformMultiPolygon(g as IMultiPolygon, from, to, toFactory);
     if (g is IGeometryCollection)
         return TransformGeometryCollection(g as IGeometryCollection, from, to, toFactory);
     throw new ArgumentException("Could not transform geometry type '" + g.GetType() + "'");
 }
 /// <summary>
 /// Transforms a <see cref="SharpMap.Geometries.Geometry"/>.
 /// </summary>
 /// <param name="g">Geometry to transform</param>
 /// <param name="from">Source Projection</param>
 /// <param name="to">Target Projection</param>
 /// <returns>Transformed Geometry</returns>
 public static Geometry TransformGeometry(Geometry g, ProjectionInfo from, ProjectionInfo to)
 {
     if (g == null)
         return null;
     if (g is Point)
         return TransformPoint(g as Point, from, to);
     if (g is LineString)
         return TransformLineString(g as LineString, from, to);
     if (g is Polygon)
         return TransformPolygon(g as Polygon, from, to);
     if (g is MultiPoint)
         return TransformMultiPoint(g as MultiPoint, from, to);
     if (g is MultiLineString)
         return TransformMultiLineString(g as MultiLineString, from, to);
     if (g is MultiPolygon)
         return TransformMultiPolygon(g as MultiPolygon, from, to);
     if (g is GeometryCollection)
         return TransformGeometryCollection(g as GeometryCollection, from, to);
     throw new ArgumentException("Could not transform geometry type '" + g.GetType() + "'");
 }
Example #38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainForm"/> class.
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            
            if (DesignMode) return;
            
            LogManager.DefaultLogManager.AddLogger(new TestLogger(consoleControl1));

            _shell = this;
            appManager.Map = map;

            appManager.DockManager = new SpatialDockManager();
            var hc = new MenuBarHeaderControl();
            hc.Initialize(new ToolStripPanel(), msTest);
            appManager.HeaderControl = hc;
            var sss = new SpatialStatusStrip();
                        
            appManager.ProgressHandler = sss;
            appManager.ShowExtensionsDialogMode = ShowExtensionsDialogMode.Default;

            try
            {
                appManager.LoadExtensions();
            }
            finally
            {
                map.FunctionMode = FunctionMode.Pan;
                _infos = new ProjectionInfo[]
                {
                    KnownCoordinateSystems.Projected.World.WebMercator,
                    KnownCoordinateSystems.Projected.Europe.EuropeLambertConformalConic,
                    KnownCoordinateSystems.Projected.World.Sinusoidalworld,
                    KnownCoordinateSystems.Projected.World.Polyconicworld,
                    ProjectionInfo.FromEpsgCode(28992)
                };
                map.Projection = _infos[0];
                map.MouseClick += map_MouseClick;
            }
        }
Example #39
0
 public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, ProjectionInfo dest, int startIndex, int numPoints)
 {
     ReprojectPoints(xy, z, source, 1.0, dest, 1.0, null, startIndex, numPoints);
 }
Example #40
0
        /// <summary>
        /// This method reprojects the affine transform coefficients.  This is used for projection on the fly,
        /// where image transforms can take advantage of an affine projection, but does not have the power of
        /// a full projective transform and gets less and less accurate as the image covers larger and larger
        /// areas.  Since most image layers represent small rectangular areas, this should not be a problem in
        /// most cases.  the affine array should be ordered as follows:
        /// X' = [0] + [1] * Column + [2] * Row
        /// Y' = [3] + [4] * Column + [5] * Row
        /// </summary>
        /// <param name="affine">The array of double affine coefficients.</param>
        /// <param name="numRows">The number of rows to use for the lower bounds.  Value of 0 or less will be set to 1.</param>
        /// <param name="numCols">The number of columns to use to get the right bounds.  Values of 0 or less will be set to 1.</param>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <returns>The transformed coefficients</returns>
        public static double[] ReprojectAffine(double[] affine, double numRows, double numCols, ProjectionInfo source, ProjectionInfo dest)
        {
            if (numRows <= 0)
            {
                numRows = 1;
            }
            if (numCols <= 0)
            {
                numCols = 1;
            }

            double[] vertices = new double[6];
            // Top left
            vertices[0] = affine[0];
            vertices[1] = affine[3];
            // Top right
            vertices[2] = affine[0] + affine[1] * numCols;
            vertices[3] = affine[3] + affine[4] * numCols;
            // Bottom Left
            vertices[4] = affine[0] + affine[2] * numRows;
            vertices[5] = affine[3] + affine[5] * numRows;
            double[] z = new double[3];
            ReprojectPoints(vertices, z, source, dest, 0, 3);
            double[] affineResult = new double[6];

            affineResult[0] = vertices[0];
            affineResult[1] = (vertices[2] - vertices[0]) / numCols;
            affineResult[2] = (vertices[4] - vertices[0]) / numRows;

            affineResult[3] = vertices[1];
            affineResult[4] = (vertices[3] - vertices[1]) / numCols;
            affineResult[5] = (vertices[5] - vertices[1]) / numRows;

            return(affineResult);
        }
Example #41
0
        private static void DatumTransform(ProjectionInfo source, ProjectionInfo dest, double[] xy, double[] z, int startIndex, int numPoints)
        {
            Spheroid wgs84  = new Spheroid(Proj4Ellipsoid.WGS_1984);
            Datum    sDatum = source.GeographicInfo.Datum;
            Datum    dDatum = dest.GeographicInfo.Datum;

            /* -------------------------------------------------------------------- */
            /*      We cannot do any meaningful datum transformation if either      */
            /*      the source or destination are of an unknown datum type          */
            /*      (ie. only a +ellps declaration, no +datum).  This is new        */
            /*      behavior for PROJ 4.6.0.                                        */
            /* -------------------------------------------------------------------- */
            if (sDatum.DatumType == DatumType.Unknown ||
                dDatum.DatumType == DatumType.Unknown)
            {
                return;
            }

            /* -------------------------------------------------------------------- */
            /*      Short cut if the datums are identical.                          */
            /* -------------------------------------------------------------------- */

            if (sDatum.Matches(dDatum))
            {
                return;
            }

            // proj4 actually allows some tollerance here
            if (sDatum.DatumType == dDatum.DatumType)
            {
                if (sDatum.Spheroid.EquatorialRadius == dDatum.Spheroid.EquatorialRadius)
                {
                    if (Math.Abs(sDatum.Spheroid.EccentricitySquared() - dDatum.Spheroid.EccentricitySquared()) < 0.000000000050)
                    {
                        // The tolerence is to allow GRS80 and WGS84 to escape without being transformed at all.
                        return;
                    }
                }
            }

            double srcA  = sDatum.Spheroid.EquatorialRadius;
            double srcEs = sDatum.Spheroid.EccentricitySquared();

            double dstA  = dDatum.Spheroid.EquatorialRadius;
            double dstEs = dDatum.Spheroid.EccentricitySquared();

            /* -------------------------------------------------------------------- */
            /*      Create a temporary Z value if one is not provided.              */
            /* -------------------------------------------------------------------- */
            if (z == null)
            {
                z = new double[xy.Length / 2];
            }

            /* -------------------------------------------------------------------- */
            /*	If this datum requires grid shifts, then apply it to geodetic   */
            /*      coordinates.                                                    */
            /* -------------------------------------------------------------------- */
            if (sDatum.DatumType == DatumType.GridShift)
            {
                //        pj_apply_gridshift(pj_param(srcdefn->params,"snadgrids").s, 0,
                //                            point_count, point_offset, x, y, z );

                GridShift.Apply(source.GeographicInfo.Datum.NadGrids, false, xy, startIndex, numPoints);

                srcA  = wgs84.EquatorialRadius;
                srcEs = wgs84.EccentricitySquared();
            }

            if (dDatum.DatumType == DatumType.GridShift)
            {
                dstA  = wgs84.EquatorialRadius;
                dstEs = wgs84.EccentricitySquared();
            }

            /* ==================================================================== */
            /*      Do we need to go through geocentric coordinates?                */
            /* ==================================================================== */

            if (srcEs != dstEs || srcA != dstA ||
                sDatum.DatumType == DatumType.Param3 ||
                sDatum.DatumType == DatumType.Param7 ||
                dDatum.DatumType == DatumType.Param3 ||
                dDatum.DatumType == DatumType.Param7)
            {
                /* -------------------------------------------------------------------- */
                /*      Convert to geocentric coordinates.                              */
                /* -------------------------------------------------------------------- */

                GeocentricGeodetic gc = new GeocentricGeodetic(sDatum.Spheroid);
                gc.GeodeticToGeocentric(xy, z, startIndex, numPoints);

                /* -------------------------------------------------------------------- */
                /*      Convert between datums.                                         */
                /* -------------------------------------------------------------------- */

                if (sDatum.DatumType == DatumType.Param3 || sDatum.DatumType == DatumType.Param7)
                {
                    PjGeocentricToWgs84(source, xy, z, startIndex, numPoints);
                }

                if (dDatum.DatumType == DatumType.Param3 || dDatum.DatumType == DatumType.Param7)
                {
                    PjGeocentricFromWgs84(dest, xy, z, startIndex, numPoints);
                }

                /* -------------------------------------------------------------------- */
                /*      Convert back to geodetic coordinates.                           */
                /* -------------------------------------------------------------------- */

                gc = new GeocentricGeodetic(dDatum.Spheroid);
                gc.GeocentricToGeodetic(xy, z, startIndex, numPoints);
            }

            /* -------------------------------------------------------------------- */
            /*      Apply grid shift to destination if required.                    */
            /* -------------------------------------------------------------------- */
            if (dDatum.DatumType == DatumType.GridShift)
            {
                //        pj_apply_gridshift(pj_param(dstdefn->params,"snadgrids").s, 1,
                //                            point_count, point_offset, x, y, z );
                GridShift.Apply(dest.GeographicInfo.Datum.NadGrids, true, xy, startIndex, numPoints);
            }
        }
Example #42
0
        public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, double srcZtoMeter, ProjectionInfo dest, double dstZtoMeter, IDatumTransform idt, int startIndex, int numPoints)
        {
            if (xy == null || source?.Equals(dest) == true || numPoints <= 0)
            {
                return;
            }
            double toMeter = source.Unit.Meters;

            // Geocentric coordinates are centered at the core of the earth.  Z is up toward the north pole.
            // The X axis goes from the center of the earth through Greenwich.
            // The Y axis passes through 90E.
            // This section converts from geocentric coordinates to geodetic ones if necessary.
            if (source.IsGeocentric)
            {
                if (z == null)
                {
                    throw new ProjectionException(45);
                }
                for (int i = startIndex; i < numPoints; i++)
                {
                    if (toMeter != 1)
                    {
                        xy[i * 2]     *= toMeter;
                        xy[i * 2 + 1] *= toMeter;
                    }
                }
                GeocentricGeodetic g = new GeocentricGeodetic(source.GeographicInfo.Datum.Spheroid);
                g.GeocentricToGeodetic(xy, z, startIndex, numPoints);
            }

            // Transform source points to lam/phi if they are not already
            ConvertToLatLon(source, xy, z, srcZtoMeter, startIndex, numPoints);

            double fromGreenwich = source.GeographicInfo.Meridian.Longitude * source.GeographicInfo.Unit.Radians;

            if (fromGreenwich != 0)
            {
                for (int i = startIndex; i < numPoints; i++)
                {
                    if (xy[2 * i] != double.PositiveInfinity)
                    {
                        xy[2 * i] += fromGreenwich;
                    }
                }
            }
            // DATUM TRANSFORM IF NEEDED
            if (idt == null)
            {
                if (!source.GeographicInfo.Datum.Matches(dest.GeographicInfo.Datum))
                {
                    DatumTransform(source, dest, xy, z, startIndex, numPoints);
                }
            }
            else
            {
                idt.Transform(source, dest, xy, z, startIndex, numPoints);
            }

            // Adjust to new prime meridian if there is one in the destination cs
            fromGreenwich = dest.GeographicInfo.Meridian.Longitude * dest.GeographicInfo.Unit.Radians;
            if (fromGreenwich != 0)
            {
                for (int i = startIndex; i < numPoints; i++)
                {
                    if (xy[i * 2] != double.PositiveInfinity)
                    {
                        xy[i * 2] -= fromGreenwich;
                    }
                }
            }

            if (dest.IsGeocentric)
            {
                if (z == null)
                {
                    throw new ProjectionException(45);
                }
                GeocentricGeodetic g = new GeocentricGeodetic(dest.GeographicInfo.Datum.Spheroid);
                g.GeodeticToGeocentric(xy, z, startIndex, numPoints);
                double frmMeter = 1 / dest.Unit.Meters;
                if (frmMeter != 1)
                {
                    for (int i = startIndex; i < numPoints; i++)
                    {
                        if (xy[i * 2] != double.PositiveInfinity)
                        {
                            xy[i * 2]     *= frmMeter;
                            xy[i * 2 + 1] *= frmMeter;
                        }
                    }
                }
            }
            else
            {
                ConvertToProjected(dest, xy, z, dstZtoMeter, startIndex, numPoints);
            }
        }
    public static string Convert_To_GeoJSON(string Geometry_String, String Source_Coordinate_System_String)
    {
        string Destination_Coordinate_System_String = EPSG4126;
        String Geometry_Type = Geometry_String.Substring(0, Geometry_String.IndexOf(" "));

        switch (Geometry_Type)
        {
        case "MULTIPOLYGON":
            Geometry_Type = "MultiPolygon";
            break;

        case "MULTILINESTRING":
            Geometry_Type = "MultiLineString";
            break;

        case "MULTIPOINT":
            Geometry_Type = "MultiPoint";
            break;

        case "POLYGON":
            Geometry_Type = "Polygon";
            break;

        case "LINESTRING":
            Geometry_Type = "LineString";
            break;

        case "POINT":
            Geometry_Type = "Point";
            break;

        default:
            Geometry_Type = "not_supported";
            return(null);
        }

        Geometry_String = Geometry_String.Replace(",", " , ");
        Geometry_String = Geometry_String.Remove(0, Geometry_String.IndexOf('('));
        Geometry_String = Geometry_String.Replace("(", "[ ");
        Geometry_String = Geometry_String.Replace(")", " ]");

        string[] splitbycomma = Geometry_String.Split(',');

        foreach (var itembycomma in splitbycomma)
        {
            string tmpitem = itembycomma;
            tmpitem = tmpitem.Replace('[', ' ');
            tmpitem = tmpitem.Replace(']', ' ');
            tmpitem = tmpitem.Trim();
            string[] splitbyspace = tmpitem.Split(' ');
            for (int ibs = 0; ibs < splitbyspace.Length - 1; ibs++)
            {
                double[] x = { double.Parse(splitbyspace[ibs]) };
                double[] y = { double.Parse(splitbyspace[ibs + 1]) };
                double[] z = new double[x.Length];
                //rewrite xy array for input into Proj4
                double[] xy  = new double[2 * x.Length];
                int      ixy = 0;
                for (int i = 0; i <= x.Length - 1; i++)
                {
                    xy[ixy]     = x[i];
                    xy[ixy + 1] = y[i];
                    z[i]        = 0;
                    ixy        += 2;
                }
                double[] xy_geometry = new double[xy.Length];
                Array.Copy(xy, xy_geometry, xy.Length);

                DotSpatial.Projections.ProjectionInfo src = DotSpatial.Projections.ProjectionInfo.FromProj4String(Source_Coordinate_System_String);
                DotSpatial.Projections.ProjectionInfo trg = DotSpatial.Projections.ProjectionInfo.FromProj4String(Destination_Coordinate_System_String);
                DotSpatial.Projections.Reproject.ReprojectPoints(xy, z, src, trg, 0, x.Length);

                ixy = 0;
                for (int i = 0; i <= x.Length - 1; i++)
                {
                    Geometry_String = Geometry_String.Replace(splitbyspace[ixy] + " ", "[" + xy[ixy].ToString("G17") + " , ");
                    Geometry_String = Geometry_String.Replace(splitbyspace[ixy + 1] + " ", xy[ixy + 1].ToString("G17") + " ] ");
                    Geometry_String = Geometry_String.Replace("- ", "-");
                    ixy            += 2;
                }
            }
        }

        Geometry_String = Geometry_String.Replace("  ", " ");
        Geometry_String = Geometry_String.Replace(" [ ", "[");
        Geometry_String = Geometry_String.Replace(" ] ", "]");
        Geometry_String = Geometry_String.Replace(" , ", ",");
        Geometry_String = Geometry_String.Replace("[ [", "[[");
        if (Geometry_Type == "Point")
        {
            Geometry_String = Geometry_String.Replace("[[", "[").Replace("]]", "]");
        }
        Geometry_String = "{\"type\": \"" + Geometry_Type + "\", \"coordinates\": " + Geometry_String + "}";

        return(Geometry_String);
    }
Example #44
0
        private static void ConvertToLatLon(ProjectionInfo source, double[] xy, double[] z, double srcZtoMeter, int startIndex, int numPoints)
        {
            double toMeter = 1.0;

            if (source.Unit != null)
            {
                toMeter = source.Unit.Meters;
            }
            double oneEs = 1 - source.GeographicInfo.Datum.Spheroid.EccentricitySquared();
            double ra    = 1 / source.GeographicInfo.Datum.Spheroid.EquatorialRadius;
            double x0    = 0;

            if (source.FalseEasting != null)
            {
                x0 = source.FalseEasting.Value;
            }
            double y0 = 0;

            if (source.FalseNorthing != null)
            {
                y0 = source.FalseNorthing.Value;
            }
            if (srcZtoMeter == 1.0)
            {
                for (int i = startIndex; i < numPoints; i++)
                {
                    if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
                    {
                        // This might be error worthy, but not sure if we want to throw an exception here
                        continue;
                    }
                    // descale and de-offset
                    xy[i * 2]     = (xy[i * 2] * toMeter - x0) * ra;
                    xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
                }
            }
            else
            {
                for (int i = startIndex; i < numPoints; i++)
                {
                    if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
                    {
                        // This might be error worthy, but not sure if we want to throw an exception here
                        continue;
                    }
                    // descale and de-offset
                    xy[i * 2]     = (xy[i * 2] * toMeter - x0) * ra;
                    xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
                    z[i]         *= srcZtoMeter;
                }
            }

            if (source.Transform != null)
            {
                source.Transform.Inverse(xy, startIndex, numPoints);
            }

            for (int i = startIndex; i < numPoints; i++)
            {
                double lam0 = source.Lam0;
                xy[i * 2] += lam0;
                if (!source.Over)
                {
                    xy[i * 2] = Adjlon(xy[i * 2]);
                }
                if (source.Geoc && Math.Abs(Math.Abs(xy[i * 2 + 1]) - Math.PI / 2) > EPS)
                {
                    xy[i * 2 + 1] = Math.Atan(oneEs * Math.Tan(xy[i * 2 + 1]));
                }
            }
        }
Example #45
0
        private static Map InitializeMapOsmWithXls(float angle)
        {
            Map map = new Map();

            TileLayer tileLayer = new TileLayer(new OsmTileSource(), "TileLayer - OSM with XLS");

            map.Layers.Add(tileLayer);

            //Get data from excel
            var xlsPath = string.Format(XlsConnectionString, System.IO.Directory.GetCurrentDirectory(), "GeoData\\Cities.xls");
            var ds      = new System.Data.DataSet("XLS");

            using (var cn = new System.Data.OleDb.OleDbConnection(xlsPath))
            {
                cn.Open();
                using (var da = new System.Data.OleDb.OleDbDataAdapter(new System.Data.OleDb.OleDbCommand("SELECT * FROM [Cities$]", cn)))
                    da.Fill(ds);
            }

#if !DotSpatialProjections
            //The SRS for this datasource is EPSG:4326, therefore we need to transfrom it to OSM projection
            var ctf      = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();
            var cf       = new ProjNet.CoordinateSystems.CoordinateSystemFactory();
            var epsg4326 = cf.CreateFromWkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.01745329251994328,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]");
            var epsg3785 = cf.CreateFromWkt("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3785\"]]");
            var ct       = ctf.CreateFromCoordinateSystems(epsg4326, epsg3785);
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value)
                {
                    continue;
                }
                double[] coords = new double[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"]) };
                coords   = ct.MathTransform.Transform(coords);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }
#else
            var epsg4326 = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
            var epsg3785 = new DotSpatial.Projections.ProjectionInfo();
            epsg3785.ReadEsriString("PROJCS[\"Popular Visualisation CRS / Mercator\", GEOGCS[\"Popular Visualisation CRS\", DATUM[\"Popular Visualisation Datum\", SPHEROID[\"Popular Visualisation Sphere\", 6378137, 0, AUTHORITY[\"EPSG\",\"7059\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6055\"]],PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\", \"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\", \"9102\"]], AXIS[\"E\", EAST], AXIS[\"N\", NORTH], AUTHORITY[\"EPSG\",\"4055\"]], PROJECTION[\"Mercator\"], PARAMETER[\"False_Easting\", 0], PARAMETER[\"False_Northing\", 0], PARAMETER[\"Central_Meridian\", 0], PARAMETER[\"Latitude_of_origin\", 0], UNIT[\"metre\", 1, AUTHORITY[\"EPSG\", \"9001\"]], AXIS[\"East\", EAST], AXIS[\"North\", NORTH], AUTHORITY[\"EPSG\",\"3785\"]]");
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                if (row["X"] == DBNull.Value || row["Y"] == DBNull.Value)
                {
                    continue;
                }
                double[] coords = new double[] { Convert.ToDouble(row["X"]), Convert.ToDouble(row["Y"]) };
                DotSpatial.Projections.Reproject.ReprojectPoints(coords, null, epsg4326, epsg3785, 0, 1);
                row["X"] = coords[0];
                row["Y"] = coords[1];
            }
#endif
            //Add Rotation Column
            ds.Tables[0].Columns.Add("Rotation", typeof(float));
            foreach (System.Data.DataRow row in ds.Tables[0].Rows)
            {
                row["Rotation"] = -angle;
            }

            //Set up provider
            var xlsProvider = new SharpMap.Data.Providers.DataTablePoint(ds.Tables[0], "OID", "X", "Y");
            var xlsLayer    = new SharpMap.Layers.VectorLayer("XLS", xlsProvider);
            xlsLayer.Style.Symbol = SharpMap.Styles.VectorStyle.DefaultSymbol;

            //Add layer to map
            map.Layers.Add(xlsLayer);
            var xlsLabelLayer = new SharpMap.Layers.LabelLayer("XLSLabel");
            xlsLabelLayer.DataSource               = xlsProvider;
            xlsLabelLayer.LabelColumn              = "Name";
            xlsLabelLayer.PriorityColumn           = "Population";
            xlsLabelLayer.Style.CollisionBuffer    = new System.Drawing.SizeF(2f, 2f);
            xlsLabelLayer.Style.CollisionDetection = true;
            xlsLabelLayer.LabelFilter              = SharpMap.Rendering.LabelCollisionDetection.ThoroughCollisionDetection;
            map.Layers.Add(xlsLabelLayer);

            map.ZoomToBox(tileLayer.Envelope);

            return(map);
        }
        public void ExportGeoJSON()
        {
            //select the objects that want to export as geojson
            List <BaseC3dObject> featureCollection = GetObjects("Export etmek istediğin objeleri seç");

            //defining the variables for coordinate transformation
            string src1 = "+proj=tmerc +lat_0=0 +lon_0=30 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs";

            DotSpatial.Projections.ProjectionInfo info  = ProjectionInfo.FromProj4String(src1);
            DotSpatial.Projections.ProjectionInfo info2 = ProjectionInfo.FromEpsgCode(4326);
            double[]      zet = new double[] { 0, 0 };
            StringBuilder vertexCoordinates = new StringBuilder();
            string        center            = "";

            //seperating the object type of selected objects for specific action
            using (Transaction ts = Dwg.TransactionManager.StartTransaction())
            {
                foreach (BaseC3dObject item in featureCollection)
                {
                    List <double[]> pnts = new List <double[]>();
                    if (item.Name == "LWPOLYLINE")
                    {
                        Autodesk.AutoCAD.DatabaseServices.Polyline lwp = ts.GetObject(item.Id, OpenMode.ForWrite)
                                                                         as Autodesk.AutoCAD.DatabaseServices.Polyline;

                        int      vn        = lwp.NumberOfVertices;
                        double[] fromPoint = new double[vn * 2];
                        int      syc       = 0;
                        for (int i = 0; i < vn; i++)
                        {
                            double east = lwp.GetPoint2dAt(i).X;
                            double nort = lwp.GetPoint2dAt(i).Y;
                            fromPoint[syc]     = east;
                            fromPoint[syc + 1] = nort;
                            syc += 2;
                        }
                        syc = 0;
                        Reproject.ReprojectPoints(fromPoint, zet, info, info2, 0, vn);

                        for (int i = 0; i < vn; i++)
                        {
                            string str = string.Format("[{0},{1}]", fromPoint[syc + 1], fromPoint[syc]);
                            vertexCoordinates.Append(str);
                            syc += 2;
                            if (i != vn - 1)
                            {
                                vertexCoordinates.Append(",");
                            }
                            center = str;
                        }

                        // polyline kapalı ise son kısmına ilk noktayı tekrar atmamız gerekiyor.
                        if (lwp.Closed)
                        {
                            vertexCoordinates.Append(",");
                            string str = string.Format("[{0},{1}]", fromPoint[1], fromPoint[0]);
                            vertexCoordinates.Append(str);
                        }
                    }
                    string geo = GeoObject("LineString", vertexCoordinates.ToString());

                    //WritingToHTML(geo, center);
                }
            }
        }
Example #47
0
        private static void ConvertToProjected(ProjectionInfo dest, double[] xy, double[] z, double dstZtoMeter, int startIndex, int numPoints)
        {
            double frmMeter  = 1 / dest.Unit.Meters;
            double frmZMeter = 1 / dstZtoMeter;
            bool   geoc      = dest.Geoc;
            double lam0      = dest.Lam0;
            double roneEs    = 1 / (1 - dest.GeographicInfo.Datum.Spheroid.EccentricitySquared());
            bool   over      = dest.Over;
            double x0        = 0;
            double y0        = 0;

            if (dest.FalseEasting.HasValue)
            {
                x0 = dest.FalseEasting.Value;
            }
            if (dest.FalseNorthing.HasValue)
            {
                y0 = dest.FalseNorthing.Value;
            }
            double a = dest.GeographicInfo.Datum.Spheroid.EquatorialRadius;

            for (int i = startIndex; i < numPoints; i++)
            {
                double lam = xy[2 * i];
                double phi = xy[2 * i + 1];
                double t   = Math.Abs(phi) - Math.PI / 2;
                if (t > EPS || Math.Abs(lam) > 10)
                {
                    xy[2 * i]     = double.PositiveInfinity;
                    xy[2 * i + 1] = double.PositiveInfinity;
                    continue;
                }
                if (Math.Abs(t) <= EPS)
                {
                    xy[2 * i + 1] = phi < 0 ? -Math.PI / 2 : Math.PI / 2;
                }
                else if (geoc)
                {
                    xy[2 * i + 1] = Math.Atan(roneEs * Math.Tan(phi));
                }
                xy[2 * i] -= lam0;
                if (!over)
                {
                    xy[2 * i] = Adjlon(xy[2 * i]);
                }
            }

            // break this out because we don't want a chatty call to extension transforms
            dest.Transform.Forward(xy, startIndex, numPoints);

            if (dstZtoMeter == 1.0)
            {
                for (int i = startIndex; i < numPoints; i++)
                {
                    xy[2 * i]     = frmMeter * (a * xy[2 * i] + x0);
                    xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
                }
            }
            else
            {
                for (int i = startIndex; i < numPoints; i++)
                {
                    xy[2 * i]     = frmMeter * (a * xy[2 * i] + x0);
                    xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
                    z[i]         *= frmZMeter;
                }
            }
        }