Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a latitude/longitude is within a polygon on Earth's surface

I am trying to figure out if a latitude/longitude point is contained within a polygon defined by vertexes that represent points on the earth (also lat/lon's, in clockwise order). This is trivial for polygons that can be mapped to the 2D lat/lon space.

Where this becomes increasingly difficult is circle's (now switching back to 3D) that may go from pole to pole covering half the earth. The translation to lat/lon looks like a sine wave. The 2D point in polygon test no longer applies to this case. Is there an algorithm that exists that solves this problem?

================== Clarifications on comments below: =================== The polygon is defined as (lon, lat) pairs in degrees, i.e., (60, 90), (60, 110), (-30, 110), (-30, 90).

I do have code that implements the ray casting algorithm, and that works. however, certain polygons on the surface of the earth do not translate to closed polygons in the 2D space.

like image 334
BigBrownBear00 Avatar asked Dec 10 '25 18:12

BigBrownBear00


1 Answers

As stated by denniston.t, if you are only interested in circles, and you have a radius, you can simply check if the Great Circle Distance between the center point and the point is less than the radius. To find the great circle distance you typically use the Haversine Formula. The following is my implementation in python:

from math import radians, sin, cos, asin, sqrt

def haversine(point1, point2):
    """Gives the distance between two points on earth.

    The haversine formula, given two sets of latitude and longitude,
    returns the distance along the surface of the earth in miles,
    ignoring potential changes in elevation. The points must be in
    decimal degrees.
    """
    earth_radius_miles = 3956
    lat1, lon1 = (radians(coord) for coord in point1)
    lat2, lon2 = (radians(coord) for coord in point2)
    dlat, dlon = (lat2 - lat1, lon2 - lon1)
    a = sin(dlat/2.0)**2 + cos(lat1) * cos(lat2) * sin(dlon/2.0)**2
    great_circle_distance = 2 * asin(min(1,sqrt(a)))
    d = earth_radius_miles * great_circle_distance
    return d
like image 183
Wilduck Avatar answered Dec 13 '25 10:12

Wilduck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!