Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect that a point is inside a Polygon using Google Maps?

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

How can I do that ?

Cheers,

like image 676
Natim Avatar asked Jun 14 '10 10:06

Natim


People also ask

How do you check if a point is inside a polygon Javascript?

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.


2 Answers

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

like image 63
swapnil udare Avatar answered Sep 25 '22 12:09

swapnil udare


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;
like image 31
Natim Avatar answered Sep 22 '22 12:09

Natim