Skip to content

Commit

Permalink
Added checking support for a pair of lat/lng numbers with slight touc…
Browse files Browse the repository at this point in the history
…h on the README.
  • Loading branch information
Jay Chae committed Feb 23, 2013
1 parent f1ed6ca commit edddcbb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
21 changes: 21 additions & 0 deletions README.md
@@ -0,0 +1,21 @@
Google-Maps-Point-in-Polygon
------------------------

A Javascript Google Maps v3 extension for the Polygon class to detect whether or not a point resides within it.

Usage:
------------------------
- Check if a LatLng object resides within the polygon.
```
var coordinate = new google.maps.LatLng(40, -90);
var polygon = new google.maps.Polygon([], "#000000", 1, 1, "#336699", 0.3);
var isWithinPolygon = polygon.containsLatLng(coordinate);
```

- Or, check if a pair of lat,lng resides within the polygon without creating a Marker object

```
var polygon = new google.maps.Polygon([], "#000000", 1, 1, "#336699", 0.3);
var isWithinPolygon = polygon.containsLatLng(40, -90);
```

25 changes: 20 additions & 5 deletions maps.google.polygon.containsLatLng.js
Expand Up @@ -20,10 +20,25 @@ if (!google.maps.Polygon.prototype.getBounds) {
// Polygon containsLatLng - method to determine if a latLng is within a polygon
google.maps.Polygon.prototype.containsLatLng = function(latLng) {
// Exclude points outside of bounds as there is no way they are in the poly
var bounds = this.getBounds();

var lat, lng;

if(bounds != null && !bounds.contains(latLng)) {
return false;
//arguments are a pair of lat, lng variables
if(arguments.length == 2) {
if(typeof arguments[0]=="number" && typeof arguments[1]=="number") {
lat = arguments[0];
lng = arguments[1];
}
} else if (arguments.length == 1) {
var bounds = this.getBounds();

if(bounds != null && !bounds.contains(latLng)) {
return false;
}
lat = latLng.lat();
lng = latLng.lng();
} else {
console.log("Wrong number of inputs in google.maps.Polygon.prototype.contains.LatLng");
}

// Raycast point in polygon method
Expand All @@ -39,8 +54,8 @@ google.maps.Polygon.prototype.containsLatLng = function(latLng) {
var vertex1 = path.getAt(i);
var vertex2 = path.getAt(j);

if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) {
if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) {
if (vertex1.lng() < lng && vertex2.lng() >= lng || vertex2.lng() < lng && vertex1.lng() >= lng) {
if (vertex1.lat() + (lng - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < lat) {
inPoly = !inPoly;
}
}
Expand Down

0 comments on commit edddcbb

Please sign in to comment.