0

I want to run code in a Template.foo.rendered only once. I have a Leaflet map and a locate-control plugin integrated. It works quite good so far but it seems the rendered template is rerun frequently. So my marker for locating the user on the map is reset every few seconds. I just want to initialize it once.

  var map, mapInit;
  map = void 0;

  mapInit = function (element){

      map = L.mapbox.map(element, 'examples.map-20v6611k').setView(new L.LatLng(52.02312,13.02627), 11);
      L.control.locate({drawCircle: true, position: 'topright'}).addTo(map);

  }

  Template.map.rendered = function () {
    $(window).resize(function () {
      var h = $(window).height(); 
      $mc = $('#map');
      $mc.css('height', h);
    }).resize();

    if (!this.rendered) {
      mapInit('map');
      this.rendered = true;
    }
  }
Chromos
  • 1,801
  • 6
  • 20
  • 26

1 Answers1

1

You may want to save the map's DOM elements to a global or app variable (here, Map), and reinsert them in the DOM later:

var Map;

...

var mapDomElement = $('#map');
if (Map.domElements) {
  mapDomElement.replaceWith(Map.domElements);
} else {
  Map.mapObject = L.mapbox.map(...) // instantiate map here
  Map.domElements = mapDomElement;
}

Note re. the height recomputation: you don't need to do that. Use the CSS flex box model to maximize map height:

<div style="display: flex; flex-flow: column; min-height: 100%">

  <div id="map" style="flex: 1"></div>

  <div>
    ... map controls here
  </div>
</div>

See this answer on the flex model. The "stuff goes here" div is your map.

Community
  • 1
  • 1
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404