Giving the getCentroid method on geometry collections a 'weighted' argument. If true, the centroid will be calculated based on the weighted average of all component centroids. Thanks for the great patch dzwarg. r=me (closes #2469)
git-svn-id: http://svn.openlayers.org/trunk/openlayers@10652 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf
This commit is contained in:
@@ -261,22 +261,67 @@ OpenLayers.Geometry.Collection = OpenLayers.Class(OpenLayers.Geometry, {
|
||||
/**
|
||||
* APIMethod: getCentroid
|
||||
*
|
||||
* Compute the centroid for this geometry collection.
|
||||
*
|
||||
* Parameters:
|
||||
* weighted - {Boolean} Perform the getCentroid computation recursively,
|
||||
* returning an area weighted average of all geometries in this collection.
|
||||
*
|
||||
* Returns:
|
||||
* {<OpenLayers.Geometry.Point>} The centroid of the collection
|
||||
*/
|
||||
getCentroid: function() {
|
||||
return this.components.length && this.components[0].getCentroid();
|
||||
/*
|
||||
var centroid;
|
||||
for (var i=0, len=this.components.length; i<len; i++) {
|
||||
if (!centroid) {
|
||||
centroid = this.components[i].getCentroid();
|
||||
} else {
|
||||
centroid.resize(this.components[i].getCentroid(), 0.5);
|
||||
}
|
||||
getCentroid: function(weighted) {
|
||||
if (!weighted) {
|
||||
return this.components.length && this.components[0].getCentroid();
|
||||
}
|
||||
return centroid;
|
||||
*/
|
||||
var len = this.components.length;
|
||||
if (!len) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var areas = [];
|
||||
var centroids = [];
|
||||
var areaSum = 0;
|
||||
var minArea = Number.MAX_VALUE;
|
||||
var component;
|
||||
for (var i=0; i<len; ++i) {
|
||||
component = this.components[i];
|
||||
var area = component.getArea();
|
||||
var centroid = component.getCentroid(true);
|
||||
if (isNaN(area) || isNaN(centroid.x) || isNaN(centroid.y)) {
|
||||
continue;
|
||||
}
|
||||
areas.push(area);
|
||||
areaSum += area;
|
||||
minArea = (area < minArea && area > 0) ? area : minArea;
|
||||
centroids.push(centroid);
|
||||
}
|
||||
len = areas.length;
|
||||
if (areaSum === 0) {
|
||||
// all the components in this collection have 0 area
|
||||
// probably a collection of points -- weight all the points the same
|
||||
for (var i=0; i<len; ++i) {
|
||||
areas[i] = 1;
|
||||
}
|
||||
areaSum = areas.length;
|
||||
} else {
|
||||
// normalize all the areas where the smallest area will get
|
||||
// a value of 1
|
||||
for (var i=0; i<len; ++i) {
|
||||
areas[i] /= minArea;
|
||||
}
|
||||
areaSum /= minArea;
|
||||
}
|
||||
|
||||
var xSum = 0, ySum = 0, centroid, area;
|
||||
for (var i=0; i<len; ++i) {
|
||||
centroid = centroids[i];
|
||||
area = areas[i];
|
||||
xSum += centroid.x * area;
|
||||
ySum += centroid.y * area;
|
||||
}
|
||||
|
||||
return new OpenLayers.Geometry.Point(xSum/areaSum, ySum/areaSum);
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user