iOS Code Snippet Point inside a polygon (Ray casting algorithm)

Based on this source http://rosettacode.org/wiki/Ray-casting_algorithm
I've adatped the code to B4i (should be identical for B4J and B4A too) and I want to share it in this so helpful forum.

You need to call the sub with a Point(LatLng) and a list(LatLng) that contains the sequence of vertex of the polygon (in CW or CCW order). The polygon must be closed of course, so the last point is equal to the first one.

Happy coding.

B4X:
Sub PointInsidePolygon(point As LatLng, LatLngList As List) As Boolean                  
    Dim pa, pb, ptemp As LatLng
    Dim i As Int
    Dim Inside As Boolean=False
    For j=0 To LatLngList.Size-1           
        pa=LatLngList.Get(j)
        i=j+1
        If i=LatLngList.Size Then i=0
        pb=LatLngList.Get(i)
        If pb.Latitude<pa.Latitude Then       
            ptemp=pa
            pa=pb
            pb=ptemp  
        End If
        If RayIntersect(point.Latitude, pa.Latitude, pb.Latitude, point.Longitude, pa.Longitude, pb.Longitude) Then Inside=Not(Inside)
    Next
    Return Inside
End Sub
Sub RayIntersect(Py As Float, Ay As Float, By As Float, Px As Float, Ax As Float, Bx As Float) As Boolean
    Dim RedIsInfinity, BlueIsInfinity As Boolean
    Dim mred, mblue As Float
    If Py=Ay Or Py=By Then Py=Py+0.00001
    If Py<Ay Or Py>By Then
        Return False
    else if Px>Max(Ax,Bx) Then
        Return False
    Else
        If Px<Min(Ax,Bx) Then
            Return True
        Else  
            If Ax<>Bx Then
                mred=(By-Ay)/(Bx-Ax)
            Else
                RedIsInfinity=True          
            End If
            If Ax<>Px Then
                mblue=(Py-Ay)/(Px-Ax)
            Else
                BlueIsInfinity=True
            End If
            If BlueIsInfinity Then
                Return True
            else if RedIsInfinity Then
                Return False
            Else if mblue>=mred Then
                Return True
            Else
                Return False
            End If
        End If  
    End If
End Sub
 
Last edited:
Top