Check if point is inside a circle

14,653

Function to calculate the distance between two coordinates (converted to C# from this answer):

double GetDistance(double lat1, double lon1, double lat2, double lon2) 
{
    var R = 6371; // Radius of the earth in km
    var dLat = ToRadians(lat2-lat1);
    var dLon = ToRadians(lon2-lon1); 
    var a = 
        Math.Sin(dLat/2) * Math.Sin(dLat/2) +
        Math.Cos(ToRadians(lat1)) * Math.Cos(ToRadians(lat2)) * 
        Math.Sin(dLon/2) * Math.Sin(dLon/2);

    var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1-a)); 
    var d = R * c; // Distance in km
    return d;
}

double ToRadians(double deg) 
{
    return deg * (Math.PI/180);
}

If the distance between the two points is less than the radius, then it is within the circle.

Share:
14,653

Related videos on Youtube

Lorenzo
Author by

Lorenzo

What should I say here?

Updated on June 04, 2022

Comments

  • Lorenzo
    Lorenzo almost 2 years

    I have a point expressed in lat/long

    Position louvreMuseum = new Position( 48.861622, 2.337474 );
    

    and I have a radius value expressed in meters. I need to check if another point, also expressed in lat/long, is inside the circle.

    If I were on a flat surface I can simply use the formula

    (x - center_x)^2 + (y - center_y)^2 <= radius^2
    

    as deeply explained in these SO answer.

    However as per the latitude/longitude usage I can not use that formula because of the spherical nature of the planet.

    How can I calculate a distance from any given point to the center to be compared with the radius?

    • Jonesopolis
      Jonesopolis over 8 years
      sounds like a math question, not a programming question
    • Lorenzo
      Lorenzo over 8 years
      @Jonesopolis: Right. Is a Math question that shall be correctly coded in a program
    • A.S.H
      A.S.H over 8 years
      I googled distance using earth coordinates and found so many answers
    • A.S.H
      A.S.H over 8 years