The Google Maps API does not yet provide a method for checking points in polygons. After doing some research, I came across a Ray-casting algorithm that will determine if the XY coordinate is inside the constructed shape. This will lead to latitude and longitude. The following extends google.maps.polygon.prototype to use this algorithm. Just include this code at a point in the code after loading google.maps:
google.maps.Polygon.prototype.Contains = function(point) { var crossings = 0, path = this.getPath(); // for each edge for (var i=0; i < path.getLength(); i++) { var a = path.getAt(i), j = i + 1; if (j >= path.getLength()) { j = 0; } var b = path.getAt(j); if (rayCrossesSegment(point, a, b)) { crossings++; } } // odd number of crossings? return (crossings % 2 == 1); function rayCrossesSegment(point, a, b) { var px = point.lng(), py = point.lat(), ax = a.lng(), ay = a.lat(), bx = b.lng(), by = b.lat(); if (ay > by) { ax = b.lng(); ay = b.lat(); bx = a.lng(); by = a.lat(); } // alter longitude to cater for 180 degree crossings if (px < 0) { px += 360 }; if (ax < 0) { ax += 360 }; if (bx < 0) { bx += 360 }; if (py == ay || py == by) py += 0.00000001; if ((py > by || py < ay) || (px > Math.max(ax, bx))) return false; if (px < Math.min(ax, bx)) return true; var red = (ax != bx) ? ((by - ay) / (bx - ax)) : Infinity; var blue = (ax != px) ? ((py - ay) / (px - ax)) : Infinity; return (blue >= red); } };
Here we have expanded the functionality of google.maps.Polygon by specifying a function called โContainsโ, which can be used to determine whether the latitude longitude is in the function parameter inside the polygon or not. Here we use the Ray-casting algorithm and have developed a function using the same. After completing this large amount of exercise, we can check the point as follows:
var point = new google.maps.LatLng (52.05249047600099, -0.6097412109375); var polygon = new google.maps.Polygon ({path: [INSERT_PATH_ARRAY_HERE]}); if (polygon.Contains (point)) {// point inside the polygon}
For a complete code and demo, go to: http://counsellingbyabhi.blogspot.in/2013/01/google-map-check-whether-point-latlong.html
source share