Reputation: 6122
I have to generate random point/marker in the map which should not outside of specific country.
For canvas, I found following example
var markerPositions = [[225,175], [75,275], [150,225], [400,125], [300,300]];
var svgNS = "http://www.w3.org/2000/svg";
var xlinkNS = "http://www.w3.org/1999/xlink";
for (var i=0; i<markerPositions.length; i++) {
// Create an SVG <use> element
var use = document.createElementNS(svgNS, "use");
// Point it at our pin marker (the circle)
use.setAttributeNS(xlinkNS, "href", "#pin");
// Set it's x and y
use.setAttribute("x", markerPositions[i][0]);
use.setAttribute("y", markerPositions[i][1]);
// Add it to the "markers" group
document.getElementById("markers").appendChild(use);
}
It adds marker but I have to generate random marker and check it should not be outside of the shape/region.
Is there any way to detect whether the random point is outside? As the above sample has simple shapes but map will have different corners/polygons?
Upvotes: 1
Views: 1717
Reputation: 82186
First, you calculate the bounding box rectangle.
Then you generate random points within that rectangle.
x ==> rand(x_min,x_max)
y ==> rand (y_min, y_max)
Then you check if the point is in the polygon, and if yes add.
While not numMatchingPoints < numPointsMustHave ==> repeat
You can check if a point is in a non-overlapping n-Vertex-Polygon like this (C-Code):
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
This is called a ray-casting algorithm.
This algorithm ray-casts to the right.
In each iteration, it tests the test point against one of the polygon's edges.
The first if-statement succeeds if the point's y-coord is within the edge's scope.
The second condition checks whether the test point is to the left of the line
If both are true, then the line drawn rightwards from the test point crosses that edge.
By repeatedly inverting the value of c, the algorithm counts how many times the rightward line crosses the polygon.
If it crosses an odd number of times, then the point is inside the polygon;
if it crosses an even number of times, the point is outside the polygon.
See also: http://en.wikipedia.org/wiki/Point_in_polygon
Upvotes: 1