Detect a point is inside a polygon with google maps
// Ray Cast Point in Polygon extension for Google Maps
// Thanks to App Delegate Inc
// For API V2
GPolygon.prototype.contains = function(latLng) {
var inPolygon = false;
// Exclude points outside of bounds as there is no way they are in the polygon
var bounds = this.getBounds();
if (bounds!=null && bounds.contiansLatLng) {
// Raycast point in polygon method
var numPoints = this.getVertexCount();
var j = numPoints - 1;
var P = latLng;
for (var i = 0; i < numPoints; i++) {
var P1 = this.getVertex(i);
var P2 = this.getVertex(j);
if (P1.lng()<P.lng() && P.lng()<=P2.lng()) {
if ( (P2.lng()-P1.lng())*(P.lat()-P1.lat()) < (P.lng()-P1.lng())*(P2.lat()-P1.lat()) ) {
inPolygon = !inPolygon;
}
}
j = i;
}
}
return inPolygon;
}
// For API V3
google.maps.Polygon.prototype.contains = function(latLng) {
var inPolygon = false;
var path = this.getPath();
if (path) {
// Raycast point in polygon method
var numPoints = path.getLength();
var j = numPoints - 1;
var P = latLng;
for (var i = 0; i < numPoints; i++) {
var P1 = path.getAt(i);
var P2 = path.getAt(j);
if (P1.lng()<P.lng() && P.lng()<=P2.lng()) {
if ( (P2.lng()-P1.lng())*(P.lat()-P1.lat()) < (P.lng()-P1.lng())*(P2.lat()-P1.lat()) ) {
inPolygon = !inPolygon;
}
}
j = i;
}
}
return inPolygon;
}