Posts Tagged ‘polygon boundary’

Polygon Boundary

Thursday, March 25th, 2010

One of the many fun things about being in charge of advertising implementations is your boss will say things like, “Hey, I need you to do the design and markup for this ad and only show it to users living in a polygonal region of California. Can you get that up in a couple of hours?”

I assumed this would be readily available with a little googling, but had trouble finding a Javascript cut-and-paste example, so I ended up adapting a point-in-polygon algorithm written in C.

function in_polygon(polygon,point)
{
	var X = [],
	    Y = [],
	    j=X.length-1,
	    odd=false,
	    x=point[0],
	    y=point[1];

	for(i=0; i < polygon.length; i++) {
		X[X.length] = polygon[i][0];
		Y[Y.length] = polygon[i][1];
	}

	for (i=0; i < X.length; i++) {
		if(Y[i] < y && Y[j] >= y
		|| Y[j] < y && Y[i] >= y)
			if (X[i]+(y-Y[i])/(Y[j]-Y[i])*(X[j]-X[i]) < x)
				odd=!odd;
		j=i;
	}
	return odd;
}

The original program took two arrays, one of X coordinates and one of Y coordinates, so the first for loop in the function just translates a more human readable set of values into the X and Y arrays used by the algorithm. So you define the inputs like so:

var polygon = [
	[38,-123],
	[38,-121],
	[36,-121],
	[36,-123]
];

var point = [37,-125];

... and feed them into the function to get a boolean answer.

Hope this saves somebody some time.