I would like to detect that a google.maps.LatLng
is inside a google.maps.Polygon
.
How can I do that ?
Cheers,
Pick a point outside the polygon check and see if a line from that point to your point intersects an odd number of lines that define the perimeter of the polygon. poly[i]. y should be poly[i][1] at the end of line 3. Also that function checks if the point is inside the polygon not if the point belongs to the polygon.
You can use this in google map V3:-
google.maps.geometry.poly.containsLocation(google.maps.LatLng(latitude, longitude),polygons);
polygons is a object returned by function after polygoncomplete.
var polygons=null;
google.maps.event.addDomListener(drawingManager, "polygoncomplete", function(polygon) {
polygons=polygon;
});
reference by https://developers.google.com/maps/documentation/javascript/reference
I used this algorithm to detect that the point is inside the polygon : http://alienryderflex.com/polygon/
I added a new method contains
to the Polygon :
// Add a function contains(point) to the Google Maps API v.3
google.maps.Polygon.prototype.contains = function(point) {
var j=0;
var oddNodes = false;
var x = point.lng();
var y = point.lat();
var paths = this.getPath();
for (var i=0; i < paths.getLength(); i++) {
j++;
if (j == paths.getLength()) {j = 0;}
if (((paths.getAt(i).lat() < y) && (paths.getAt(j).lat() >= y))
|| ((paths.getAt(j).lat() < y) && (paths.getAt(i).lat() >= y))) {
if ( paths.getAt(i).lng() + (y - paths.getAt(i).lat())
/ (paths.getAt(j).lat()-paths.getAt(i).lat())
* (paths.getAt(j).lng() - paths.getAt(i).lng())<x ) {
oddNodes = !oddNodes
}
}
}
return oddNodes;
}
google.maps.Polyline.prototype.contains = google.maps.Polygon.prototype.contains;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With