Skip to content

Don't throw when toggling a popup or tooltip of a layer that isn't on the map - #10551

Merged
mourner merged 1 commit into
Leaflet:mainfrom
Enesuygurs:fix/toggle-popup-off-map
Nov 9, 2026
Merged

mourner merged 1 commit into
Leaflet:mainfrom
Enesuygurs:fix/toggle-popup-off-map

Conversation

@Enesuygurs

Copy link
Copy Markdown
Contributor

layer.togglePopup() and layer.toggleTooltip() throw when the layer isn't on a map, while openPopup() and openTooltip() on the same layer simply do nothing:

const marker = new Marker([0, 0]).bindPopup('Hi');
marker.openPopup();   // no-op
marker.togglePopup(); // TypeError: Cannot read properties of undefined (reading 'hasLayer')

DivOverlay.toggle() calls _prepareOpen() and then opens the overlay on the source layer's map without checking the result. _prepareOpen() returns false when the layer has no map or no overlay source, and Layer.openPopup()/openTooltip() already check that return value before calling openOn(). Without the check, toggle() passes an empty map to openOn(), which throws. For a FeatureGroup with no layers, which is on the map but has no source to anchor the popup to, the popup is still added to the map.

toggle() now only opens the overlay when _prepareOpen() succeeds, the same way openPopup() and openTooltip() do.

Testing

I added specs for toggling a popup on a layer that was removed from the map, toggling a popup bound to an empty FeatureGroup, and toggling a tooltip on a layer that was never added. All three fail on main and pass with this change.

npm test (Chromium) passes with 1396 tests, and npm run lint and npm run typecheck pass.

@mourner
mourner merged commit 6b123fc into Leaflet:main Nov 9, 2026
10 checks passed
simon04 pushed a commit to maplair/maplair that referenced this pull request Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants