Detect self intersection of a polygon with n sides?
<p>I am using Google Maps SDK to allow a user to draw a polygon on the map by tapping. Everything works perfectly is the user is to draw a polygon following a path and continues on that path without crossing over lines. If that happens, this result is produced: <a href="https://i.stack.imgur.com/1aiaS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1aiaS.png" alt="Done properly Example"></a>. However. if the user is to make an error and cross over or change the direction of their "tapping" path this happens: <a href="https://i.stack.imgur.com/Rw6SP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rw6SP.png" alt="Error Example"></a>
I need to either
 A) alert the user that they have created an invalid polygon, and must undo that action, or 
B) correct the polygon shape to form a complete polygon.</p>

<p>With the research I have done, option <strong>A</strong> seems much more feasible and simple since option B would require rearranging the path of the polygon points. </p>

<p>I have done research and found algorithms and formulas to detect line intersection, but I am yet to find any piece of a solution in Swift to recognize if a polygon self-intersects based off of points (in this case, latitude and longitude). I don't need to know the point, just TRUE or FALSE to the question, "Does this Polygon self-intersect?" The polygon will typically have less than 20 sides.</p>

<p>Perhaps there is a solution built in with the GoogleMaps SDK, but I am yet to find it. Also, I understand that there are already algorithms for problems such as these, I am just having trouble <strong>implementing</strong> them into Swift 2 or 3. Any help is appreciated, thanks!</p>