Optimize Way#area

This commit is contained in:
John Firebaugh
2014-10-13 16:46:32 -07:00
parent 69af20e44d
commit a7fb35663c
2 changed files with 21 additions and 5 deletions

View File

@@ -218,20 +218,20 @@ _.extend(iD.Way.prototype, {
return resolver.transient(this, 'area', function() {
var nodes = resolver.childNodes(this);
if (!this.isClosed() && nodes.length) {
nodes = nodes.concat([nodes[0]]);
}
var json = {
type: 'Polygon',
coordinates: [_.pluck(nodes, 'loc')]
};
if (!this.isClosed() && nodes.length) {
json.coordinates[0].push(nodes[0].loc);
}
var area = d3.geo.area(json);
// Heuristic for detecting counterclockwise winding order. Assumes
// that OpenStreetMap polygons are not hemisphere-spanning.
if (d3.geo.area(json) > 2 * Math.PI) {
if (area > 2 * Math.PI) {
json.coordinates[0] = json.coordinates[0].reverse();
area = d3.geo.area(json);
}

View File

@@ -469,6 +469,22 @@ describe('iD.Way', function() {
expect(s).to.be.lt(l);
});
it("treats unclosed areas as if they were closed", function () {
var graph = iD.Graph([
iD.Node({id: 'a', loc: [-0.0002, 0.0001]}),
iD.Node({id: 'b', loc: [ 0.0002, 0.0001]}),
iD.Node({id: 'c', loc: [ 0.0002, -0.0001]}),
iD.Node({id: 'd', loc: [-0.0002, -0.0001]}),
iD.Way({id: 's', tags: {area: 'yes'}, nodes: ['a', 'b', 'c', 'd', 'a']}),
iD.Way({id: 'l', tags: {area: 'yes'}, nodes: ['a', 'b', 'c', 'd']})
]);
var s = graph.entity('s').area(graph),
l = graph.entity('l').area(graph);
expect(s).to.equal(l);
});
it("returns 0 for degenerate areas", function () {
var graph = iD.Graph([
iD.Node({id: 'a', loc: [-0.0002, 0.0001]}),