Last active
July 21, 2022 21:52
-
-
Save bertt/885f8c4d5475b44a1553bd22bd47b885 to your computer and use it in GitHub Desktop.
convert latitude/longitude (4326) to cartesian/ecef (4978)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Two methods to get from 4326 (longitude, latitude) to 4978 (cartesian - ecef). TLDR; use DotSpatial.Positioning when possible (because much faster). | |
1] using DotSpatial.Positioning (fast): | |
``` | |
private static System.Numerics.Vector3 ToCartesian(double lat, double lon, double alt) | |
{ | |
var pos3d = new Position3D(new Distance(alt, DistanceUnit.Meters), new Latitude(lat), new Longitude(lon)); | |
var res1 = pos3d.ToCartesianPoint(); | |
return new System.Numerics.Vector3((float)res1.X.Value, (float)res1.Y.Value, (float)res1.Z.Value); | |
} | |
``` | |
and back ... | |
``` | |
static (double x, double y, double z) FromVector3(Vector3 vec) | |
{ | |
var cartesianPoint = new CartesianPoint(new Distance(vec.X, DistanceUnit.Meters), new Distance(vec.Y, DistanceUnit.Meters), new Distance(vec.Z, DistanceUnit.Meters)); | |
var pos3 = cartesianPoint.ToPosition3D(); | |
return ((double)pos3.Longitude, (double)pos3.Latitude, pos3.Altitude.Value); | |
} | |
``` | |
2] using gdal (slow): | |
call using GetCartesian(p, 4326, 4978) | |
``` | |
public static System.Numerics.Vector3 GetCartesian (point, int from, int to) | |
{ | |
var src = new SpatialReference(""); | |
src.ImportFromEPSG(from); | |
var dst = new SpatialReference(""); | |
dst.ImportFromEPSG(to); | |
var ct = new CoordinateTransformation(src, dst); | |
double[] p = new double[3]; | |
p[0] = point.Coordinates.Longitude; | |
p[1] = point.Coordinates.Latitude; | |
p[2] = (double)point.Coordinates.Altitude; | |
ct.TransformPoint(p); | |
return new System.Numerics.Vector3((float)p[0], (float)p[1], (float)p[2]); | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment