I am creating a polygon using Google Maps V3 API. It starts off with a 4 sided polygon which is a square.
Problem: Now when a new point is added to the polygon, it is possible for the polygon to overlap itself in a weird shape instead of forming a pentagon. This is because the polygon is drawn in the order the points are added to the array. Is it possible to rearrange the polygon points so no 2 lines overlap each other?
I have successfully implemented Blazemonger’s suggestion above, and it works for me.
Here was his novel suggestion:
To determine if the point is in the polygon, I used the polygon.Contains function from Mike Williams’ updated epoly.js, found here: http://www.geocodezip.com/scripts/v3_epoly.js.
If the point is not in the polygon (see above), we:
1.) Determine if the interior angle of the last two vectors is greater than 180 degrees. To do so we need to implement the below equation to find the angle of last two vectors of the polygon:
angleRadians = Math.acos((vx1 * vx2 + vy1 * vy2) / ( Math.sqrt( vx1*vx1 + vy1*vy1 ) * Math.sqrt( vx2*vx2 + vy2*vy2 ) ));
this is using the Dot product of the vectors.
But that does not take into account the ‘winding direction’, first you must get the cross product and, if the cross product is positive, it was a left turn, if negative–a right turn.
I have included my JS code here, as a gist: https://gist.github.com/3741816.
BTW, I’m a newbie here at StackOverflow — it’s been such a great resource to me thanks thanks to all who have contributed!