From a7fb35663c6868409790b2ccc2fb643c0bffe899 Mon Sep 17 00:00:00 2001 From: John Firebaugh Date: Mon, 13 Oct 2014 16:46:32 -0700 Subject: [PATCH] Optimize Way#area --- js/id/core/way.js | 10 +++++----- test/spec/core/way.js | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/js/id/core/way.js b/js/id/core/way.js index 608cf7abf..44893ea87 100644 --- a/js/id/core/way.js +++ b/js/id/core/way.js @@ -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); } diff --git a/test/spec/core/way.js b/test/spec/core/way.js index 799b6a224..a551db1ce 100644 --- a/test/spec/core/way.js +++ b/test/spec/core/way.js @@ -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]}),