-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathmaps.google.polygon.containsLatLng.js
86 lines (74 loc) · 2.18 KB
/
maps.google.polygon.containsLatLng.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Polygon getBounds extension - google-maps-extensions
// https://github.com/tparkin/Google-Maps-Point-in-Polygon
// http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds = function(latLng) {
var bounds = new google.maps.LatLngBounds(),
paths = this.getPaths(),
path,
p, i;
for (p = 0; p < paths.getLength(); p++) {
path = paths.getAt(p);
for (i = 0; i < path.getLength(); i++) {
bounds.extend(path.getAt(i));
}
}
return bounds;
};
}
// 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 inPoly = false,
bounds, lat, lng,
numPaths, p, path, numPoints,
i, j, vertex1, vertex2;
// 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) {
bounds = this.getBounds();
if (!bounds && !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
numPaths = this.getPaths().getLength();
for (p = 0; p < numPaths; p++) {
path = this.getPaths().getAt(p);
numPoints = path.getLength();
j = numPoints - 1;
for (i = 0; i < numPoints; i++) {
vertex1 = path.getAt(i);
vertex2 = path.getAt(j);
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;
}
}
j = i;
}
}
return inPoly;
};