Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Created June 17, 2010 02:28
Show Gist options
  • Select an option

  • Save joshuaclayton/441599 to your computer and use it in GitHub Desktop.

Select an option

Save joshuaclayton/441599 to your computer and use it in GitHub Desktop.
var polygonIncludes = function(points) {
return function() {
var point = [this.grid_lat, this.grid_lng];
var sides = points.length;
var map = function( elems, callback, arg ) {
var ret = [], value;
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
return ret.concat.apply( [], ret );
}
var polyXs = map(points, function(p, i) { return p[0]; }),
polyYs = map(points, function(p, i) { return p[1]; }),
x = point[0],
y = point[1];
var max = function(arr) { return Math.max.apply({}, arr); },
min = function(arr) { return Math.min.apply({}, arr); };
if(max(polyXs) < x || min(polyXs) > x || max(polyYs) < y || min(polyYs) > y) {
return false;
}
var result = false,
j = sides - 1;
for(var i = 0; i < sides; i++) {
if((polyYs[i] < y && polyYs[j] >= y) || (polyYs[j] < y && polyYs[i] >= y)) {
if((polyXs[i] + (y - polyYs[i])/(polyYs[j] - polyYs[i])*(polyXs[j] - polyXs[i])) < x) {
result = !result;
}
}
j = i;
}
return result;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment