I have a “place” object from Google Maps which has a set of coordinates that represent a bounding box for a given location, say London. Each set of coordinates has a latitude and longitude.
I have written the below code to find the centerpoint, but I am not sure if it does actually produce the centerpoint. What if the polygon has 5 points instead of 4? Also, can this be done in a more efficient way, with less operations?
JavaScript
x
32
32
1
function average(array) {
2
// Add together and then divide by the length
3
return _.reduce(array, function (sum, num) {
4
return sum + num;
5
}, 0) / array.length;
6
}
7
8
// I have a two-dimensional array that I want to get the average of
9
10
var coords = [
11
[ -1.2, 5.1 ],
12
[ -1.3, 5.2 ],
13
[ -1.8, 5.9 ],
14
[ -1.9, 5.8 ]
15
]
16
17
// So I get the first column
18
19
var lats = coords.map(function (coord) {
20
return coord[0];
21
})
22
23
// Then the second
24
25
var longs = coords.map(function (coord) {
26
return coord[1];
27
})
28
29
// And average each column out
30
31
console.log([average(lats), average(longs)])
32
Advertisement
Answer
This should get the centroid of the area of any polygon
JavaScript
1
67
67
1
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
2
/*global console */
3
4
(function () {
5
"use strict";
6
7
function Point(x, y) {
8
this.x = x;
9
this.y = y;
10
}
11
12
function Region(points) {
13
this.points = points || [];
14
this.length = points.length;
15
}
16
17
Region.prototype.area = function () {
18
var area = 0,
19
i,
20
j,
21
point1,
22
point2;
23
24
for (i = 0, j = this.length - 1; i < this.length; j=i,i++) {
25
point1 = this.points[i];
26
point2 = this.points[j];
27
area += point1.x * point2.y;
28
area -= point1.y * point2.x;
29
}
30
area /= 2;
31
32
return area;
33
};
34
35
Region.prototype.centroid = function () {
36
var x = 0,
37
y = 0,
38
i,
39
j,
40
f,
41
point1,
42
point2;
43
44
for (i = 0, j = this.length - 1; i < this.length; j=i,i++) {
45
point1 = this.points[i];
46
point2 = this.points[j];
47
f = point1.x * point2.y - point2.x * point1.y;
48
x += (point1.x + point2.x) * f;
49
y += (point1.y + point2.y) * f;
50
}
51
52
f = this.area() * 6;
53
54
return new Point(x / f, y / f);
55
};
56
57
var polygon = [
58
{"x": -1.2, "y": 5.1},
59
{"x": -1.3, "y": 5.2},
60
{"x": -1.8, "y": 5.9},
61
{"x": -1.9, "y": 5.8}
62
],
63
region = new Region(polygon);
64
65
console.log(region.centroid());
66
}());
67
On jsfiddle