Serge's World

Blogging about software development, astronomy, genealogy and more.

Finding the Midpoint Between Two GPS Coordinates

Previously I showed how to find the distance between coordinates and the bearing, but what if you want to find the midpoint of two coordinates.

The code in C# is rather straightforward – that is, if you know a little bit of trigonometry.

namespace Geodesy
{
    public class Geodesy
    {
        public static double RadToDeg(double radians)
        {
            return radians * (180 / Math.PI);
        }

        public static double DegToRad(double degrees)
        {
            return degrees * (Math.PI / 180);
        }

        public static void MidpointCoords(double lat1, double long1, double lat2, double long2, ref double midpointLat, ref double midpointLong)
        {
            //Convert input values to radians

            lat1 = Geodesy.DegToRad(lat1);
            long1 = Geodesy.DegToRad(long1);
            lat2 = Geodesy.DegToRad(lat2);
            long2 = Geodesy.DegToRad(long2);
            double deltaLat = lat2 - lat1;
            double deltaLong = long2 - long1;

            double Bx = Math.Cos(lat2) * Math.Cos(deltaLong);
            double By = Math.Cos(lat2) * Math.Sin(deltaLong);
            midpointLat = Geodesy.RadToDeg(Math.Atan2(Math.Sin(lat1) + Math.Sin(lat2),
               Math.Sqrt((Math.Cos(lat1) + Bx) * (Math.Cos(lat1) + Bx) + By * By)));
            midpointLong = Geodesy.RadToDeg(long1 + Math.Atan2(By, Math.Cos(lat1) + Bx));

        }

    }
}

Originally posted on my old blog, Smoky Cogs, on 8 Oct 2009

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)