Monday, April 2, 2012

Transform non lat/long coordinate to lat/long using proj.net

This took me some time. I eventually found something online close and created this method. The inputs are authority and the native point to be transformed. The authority is the string that you would use in a program like cs2cs.exe to make a transform.

private static double[] TransformCoordToLatLong(string authority, double[] fromPoint)
    {
        // The authority type needs to be proj4, and we will be turning the coordinate into lat/long (WGS84)
        string authType = "proj4";
        string WGS84WKT = "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\"]]";

        SpatialReferenceTransformation srt = new SpatialReferenceTransformation();
        SR.AuthorityTransformationResult[] transformations;
        transformations = srt.TransformToKnownAuthorities(authType, authority, null);
        transformations = srt.AddLocalTransformation(transformations);
        
        ICoordinateSystem pcs_New = CoordinateSystemWktReader.Parse(transformations[0].AuthorityText) as ICoordinateSystem;
        ICoordinateSystem pcs_wgs84 = CoordinateSystemWktReader.Parse(WGS84WKT) as ICoordinateSystem;

        CoordinateSystemFactory csFactory = new ProjNet.CoordinateSystems.CoordinateSystemFactory();
        CoordinateTransformationFactory ctFactory = new CoordinateTransformationFactory();
        ICoordinateSystem sourceCS = csFactory.CreateFromWkt(transformations[0].AuthorityText);
        ICoordinateSystem targetCS = csFactory.CreateFromWkt(WGS84WKT);
        ICoordinateTransformation transformer = ctFactory.CreateFromCoordinateSystems(pcs_New, pcs_wgs84);

        double[] toPoint = transformer.MathTransform.Transform(fromPoint);
        return toPoint;
    }

Proj.net

1 comment:

  1. Where does the SpatialReferenceTransformation class object come from? It doesn't appear to be in Proj.Net.

    ReplyDelete