views:

75

answers:

1

Hello,

I would like to detect that a google.maps.LatLng is inside a google.maps.Polygon.

How can I do that ?

Cheers,

+1  A: 

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;
Natim