1

I have a map, which is displayed or hidden depending on a button click. I init the map while it is hidden, add layer, add markers, and call fitBounds() for the markers.

My problem is that when the map is hidden, fitBounds doesn't work. After switching to visible, the map is shown but fully zoomed out. When I call fitBounds again, the map is shown correctly.

How do I know when the map is ready? I tried mapReady, but it is also called when the map is hidden.

Is there another way?

Thanks!

Eric
  • 25
  • 5

2 Answers2

2

How do I know when the map is ready?

FWIW, it is indeed when the map.whenReady(callback) executes your callback.

Your issue is probably not about the map not being ready (as you figured out, the map is ready even when hidden), but in the fact that it is originally hidden, hence it (the map container) does not have its final size. It needs that size (height and width) as it impacts your map.fitBounds().

You probably just need to call map.invalidateSize() and re-perform your fitBounds once you show your map.

See also: Data-toggle tab does not download Leaflet map

Community
  • 1
  • 1
ghybs
  • 47,565
  • 6
  • 74
  • 99
  • Thanks, I have still to try it. Will give feedback later. – Eric Aug 30 '16 at 12:21
  • 'map.invalidateSize()' alone doesn't help. Now it seems to be more a Angular2 issue, when to call it in the lifecycle hook. – Eric Sep 28 '16 at 07:20
0

You might easily create valid div with width & height. Also you need to setup it as absolute. Then, add this div to relative one, which is displayed. That is all.

<div style="display: block; position: relative; overflow: hidden;">
   <div style="display: absolute; width: 100px; height: 100px; left: -1000px; top: -1000px;" id="map"></div>
</div>

That might be enough