UNPKG

leaflet

Version:

JavaScript library for mobile-friendly interactive maps

157 lines (127 loc) 3.17 kB
/* * Adds popup-related methods to all layers. */ L.Layer.include({ bindPopup: function (content, options) { if (content instanceof L.Popup) { L.setOptions(content, options); this._popup = content; content._source = this; } else { if (!this._popup || options) { this._popup = new L.Popup(options, this); } this._popup.setContent(content); } if (!this._popupHandlersAdded) { this.on({ click: this._openPopup, remove: this.closePopup, move: this._movePopup }); this._popupHandlersAdded = true; } // save the originally passed offset this._originalPopupOffset = this._popup.options.offset; return this; }, unbindPopup: function () { if (this._popup) { this.off({ click: this._openPopup, remove: this.closePopup, move: this._movePopup }); this._popupHandlersAdded = false; this._popup = null; } return this; }, openPopup: function (layer, latlng) { if (!(layer instanceof L.Layer)) { latlng = layer; layer = this; } if (layer instanceof L.FeatureGroup) { for (var id in this._layers) { layer = this._layers[id]; break; } } if (!latlng) { latlng = layer.getCenter ? layer.getCenter() : layer.getLatLng(); } if (this._popup && this._map) { // set the popup offset for this layer this._popup.options.offset = this._popupAnchor(layer); // set popup source to this layer this._popup._source = layer; // update the popup (content, layout, ect...) this._popup.update(); // open the popup on the map this._map.openPopup(this._popup, latlng); } return this; }, closePopup: function () { if (this._popup) { this._popup._close(); } return this; }, togglePopup: function (target) { if (this._popup) { if (this._popup._map) { this.closePopup(); } else { this.openPopup(target); } } return this; }, isPopupOpen: function () { return this._popup.isOpen(); }, setPopupContent: function (content) { if (this._popup) { this._popup.setContent(content); } return this; }, getPopup: function () { return this._popup; }, _openPopup: function (e) { var layer = e.layer || e.target; if (!this._popup) { return; } if (!this._map) { return; } // if this inherits from Path its a vector and we can just // open the popup at the new location if (layer instanceof L.Path) { this.openPopup(e.layer || e.target, e.latlng); return; } // otherwise treat it like a marker and figure out // if we should toggle it open/closed if (this._map.hasLayer(this._popup) && this._popup._source === layer) { this.closePopup(); } else { this.openPopup(layer, e.latlng); } }, _popupAnchor: function (layer) { // where shold we anchor the popup on this layer? var anchor = layer._getPopupAnchor ? layer._getPopupAnchor() : [0, 0]; // add the users passed offset to that var offsetToAdd = this._originalPopupOffset || L.Popup.prototype.options.offset; // return the final point to anchor the popup return L.point(anchor).add(offsetToAdd); }, _movePopup: function (e) { this._popup.setLatLng(e.latlng); } });