Ben Mayo
Ben Mayo

Reputation: 1315

Leaflet - refreshing the map

I understand that this question has been asked, and answered before, but I haven't been able to successfully implement those examples.

I'm trying to load the map via zoomedIn() (works fine), then on the button press load the map with zoomedOut()

In zoomedOut() however, I'm throwing Map container is already initialized after var map = new L.Map('map');

I had thought that the previous line if (map != undefined) { map.remove(); } would have taken care of that.

What's going on - how can I redraw the map?

<body onLoad="javascript:zoomedIn();">
<form method = "post">
<button type="button" onclick="return zoomedOut()">Zoom Out</button>
<div id="map"</div>
</form>

<script language="javascript">
  function zoomedIn() {
     var map = new L.Map('map');
    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        id: 'mapbox.streets'
    }).addTo(map);
         var devon = new L.LatLng(50.900958,-3.370846);
         map.setView(devon, 7);
      }
</script>

<script language="javascript">
  function zoomedOut() {
    if (map != undefined) { map.remove(); }
    var map = new L.Map('map');
    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        id: 'mapbox.streets'
    }).addTo(map);
         var devon = new L.LatLng(50.900958,-3.370846);
         map.setView(devon, 1);
      }

Upvotes: 0

Views: 8384

Answers (1)

Symeon Mattes
Symeon Mattes

Reputation: 1268

You can use

map.invalidateSize()

It worked for me

Upvotes: 5

Related Questions