0

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);
      }

Ben Mayo
  • 1,285
  • 2
  • 20
  • 37
  • I don't understand what you are trying to achieve. Why would you want the map to be removed and then added again ? – Julien V Jun 25 '17 at 12:22
  • I've got a bunch of markers on the map - I'm trying to redraw those markers. That's not in the code above of course, but as I understand it I need to redraw it. – Ben Mayo Jun 25 '17 at 13:43
  • As here: https://stackoverflow.com/questions/19186428/refresh-leaflet-map-map-container-is-alreay-initialized – Ben Mayo Jun 25 '17 at 13:45
  • If you are trying to redraw some markers, your question should be titled "How to redraw Leaflet markers?" – IvanSanchez Jun 25 '17 at 17:31
  • What I'm trying to do is understand why I'm getting the behaviour I'm getting. I deliberately didn't include my end goal in the question. – Ben Mayo Jun 25 '17 at 17:44
  • First : i verified that the result of the "remove" method call leaves the map object as undefined : it's not. Second : to redraw markers, it's useless to destroy the entire map. You could keep track of the currently displayed markers (in an array for example), remove them and add them again. You could also move them with "setLatLng()" method. Anyway, i can't think about any reason to destroy and create a new map to refresh information on the map... – Julien V Jun 26 '17 at 07:36

1 Answers1

5

You can use

map.invalidateSize()

It worked for me

Symeon Mattes
  • 1,169
  • 16
  • 40