I would like to use client-side JavaScript to find the centroid of a set of latitudes + longitudes (actually Google LatLng objects), using a simple mean calculation.
I see that similar questions has been asked many times before on Stack Overflow, but I can’t find a straightforward answer for JavaScript. (This may just be a fail of my Googling, apologies if this is a duplicate.)
I have something like this, but it doesn’t work for the case where you’re averaging, say, latitudes of 179 and -179, and so the centroid should be 180 rather than 0.
var avg_lat, avg_lng;
for (var i = 0; i < google_latlngs.length; i++) {
avg_lat += google_latlngs[0].lat();
avg_lng += google_latlngs[1].lng();
}
avg_lat = avg_lat / google_latlngs.length;
avg_lng = avg_lng / google_latlngs.length;
I need to do this efficiently in client-side JavaScript, and my points are unlikely to be more than a few km apart, so great-circle distance or anything fancy really isn’t necessary in this case.
Thanks for your help.
UPDATE: OK, any method for finding a centroid in JavaScript will do.
If you are dealing with 2 points only, make sure the difference between your two latitude points is less than or equal to 180 before applying your function. You can do this by adding or subtracting by 360, which would change -179 to 181 (or 179 to -181). When you get your final result, add/subtract by 360 until the final value is within your desired range.
Update
If you want this to work with more than two points, we’ll have to do some geometry. We treat each latitude point as a point on a unit circle with a certain distance
xandyfrom the origin and certain anglea(the latitude):We must average all the
x‘s andy‘s and then take the angle of the resulting point to get our final latitude for the centroid. Here is the JavaScript: