Search code examples
gpsgeojson

Check if point is within a polygon


Given a GEO-JSON polygon, such as the below:

[
    [15.520376, 38.231155],
    [15.160243, 37.444046],
    [15.309898, 37.134219],
    [15.099988, 36.619987],
    [14.335229, 36.996631],
    [13.826733, 37.104531],
    [12.431004, 37.61295],
    [12.570944, 38.126381],
    [13.741156, 38.034966],
    [14.761249, 38.143874],
    [15.520376, 38.231155]
]

How can I check if a GPS location is within the polygon region?

For example, if the user is at Lat 37.387617, Long 14.458008, how would I go about searching the array?

I don't need someone to necessarily write the code for me, I just don't understand the logic of how I can check. If you have any example (any language) please point me.


Solution

  • I've found an article about the Ray-casting algorithm. It's explained pretty well here, the jist of it is (in pseudo code):

    count ← 0
     foreach side in polygon:
       if ray_intersects_segment(P,side) then
         count ← count + 1
     if is_odd(count) then
       return inside
     else
       return outside