Toggle the display of a marker s popup on click

This commit is contained in:
Paul Bonaud 2013-06-16 22:13:31 +02:00
parent 6d33627f66
commit 1af9769ed0
3 changed files with 40 additions and 2 deletions

View File

@ -46,6 +46,30 @@ describe('Popup', function() {
expect(map.hasLayer(popup)).to.be(true);
});
it("toggles its visibility when marker is clicked", function() {
var marker = new L.Marker(new L.LatLng(55.8, 37.6));
map.addLayer(marker);
marker.bindPopup('Popup1').openPopup();
map.options.closePopupOnClick = true;
happen.click(c);
// toggle open popup
sinon.spy(marker, "openPopup");
marker.fire('click');
expect(marker.openPopup.calledOnce).to.be(true);
expect(map.hasLayer(marker._popup)).to.be(true);
marker.openPopup.restore();
// toggle close popup
sinon.spy(marker, "closePopup");
marker.fire('click');
expect(marker.closePopup.calledOnce).to.be(true);
expect(map.hasLayer(marker._popup)).to.be(false);
marker.closePopup.restore();
});
it("should trigger popupopen on marker when popup opens", function() {
var marker1 = new L.Marker(new L.LatLng(55.8, 37.6));
var marker2 = new L.Marker(new L.LatLng(57.123076977278, 44.861962891635));

View File

@ -27,6 +27,7 @@ L.Popup = L.Class.extend({
this._source = source;
this._animated = L.Browser.any3d && this.options.zoomAnimation;
this._isOpen = false;
},
onAdd: function (map) {
@ -301,6 +302,7 @@ L.Map.include({
.setLatLng(latlng)
.setContent(content);
}
popup._isOpen = true;
this._popup = popup;
return this.addLayer(popup);
@ -313,6 +315,7 @@ L.Map.include({
}
if (popup) {
this.removeLayer(popup);
popup._isOpen = false;
}
return this;
}

View File

@ -19,6 +19,17 @@ L.Marker.include({
return this;
},
togglePopup: function () {
if (this._popup) {
if (this._popup._isOpen) {
this.closePopup();
} else {
this.openPopup();
}
}
return this;
},
bindPopup: function (content, options) {
var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
@ -32,7 +43,7 @@ L.Marker.include({
if (!this._popup) {
this
.on('click', this.openPopup, this)
.on('click', this.togglePopup, this)
.on('remove', this.closePopup, this)
.on('move', this._movePopup, this);
}
@ -59,7 +70,7 @@ L.Marker.include({
if (this._popup) {
this._popup = null;
this
.off('click', this.openPopup)
.off('click', this.togglePopup)
.off('remove', this.closePopup)
.off('move', this._movePopup);
}