Skip to content

Commit

Permalink
Throw error on call to L.Polygon getCenter before map add (#4820)
Browse files Browse the repository at this point in the history
* Throw error on call to L.Polygon getCenter before map add

References #4740

* add polyline handling, tests, and docstring
  • Loading branch information
snkashis authored and IvanSanchez committed Aug 15, 2016
1 parent 1a0b082 commit 92baa9c
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions spec/suites/layer/vector/PolygonSpec.js
Expand Up @@ -162,6 +162,16 @@ describe('Polygon', function () {
expect(layer.getCenter()).to.be.nearLatLng(L.latLng([0, 0]));
});

it('throws error if not yet added to map', function () {
expect(function () {
var latlngs = [
[[0, 0], [10, 0], [10, 10], [0, 10]]
];
var layer = new L.Polygon(latlngs);
var center = layer.getCenter();
}).to.throwException('Must add layer to map before using getCenter()');
});

});

describe("#_defaultShape", function () {
Expand Down
7 changes: 7 additions & 0 deletions spec/suites/layer/vector/PolylineSpec.js
Expand Up @@ -135,6 +135,13 @@ describe('Polyline', function () {
expect(polyline.getCenter()).to.be.nearLatLng(L.latLng([0, 0]), 1e-2);
});

it('throws error if not yet added to map', function () {
expect(function () {
var polyline = new L.Polyline([[0, 0], [0, 0.090]]);
var center = polyline.getCenter();
}).to.throwException('Must add layer to map before using getCenter()');
});

});

describe('#_flat', function () {
Expand Down
5 changes: 5 additions & 0 deletions src/layer/vector/Polygon.js
Expand Up @@ -55,6 +55,11 @@ L.Polygon = L.Polyline.extend({
},

getCenter: function () {
// throws error when not yet added to map as this center calculation requires projected coordinates
if (!this._map) {
throw new Error('Must add layer to map before using getCenter()');
}

var i, j, p1, p2, f, area, x, y, center,
points = this._rings[0],
len = points.length;
Expand Down
5 changes: 5 additions & 0 deletions src/layer/vector/Polyline.js
Expand Up @@ -105,6 +105,11 @@ L.Polyline = L.Path.extend({
// @method getCenter(): LatLng
// Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the polyline.
getCenter: function () {
// throws error when not yet added to map as this center calculation requires projected coordinates
if (!this._map) {
throw new Error('Must add layer to map before using getCenter()');
}

var i, halfDist, segDist, dist, p1, p2, ratio,
points = this._rings[0],
len = points.length;
Expand Down

0 comments on commit 92baa9c

Please sign in to comment.