StuLondon
StuLondon

Reputation: 343

Openlayer Map - Only shows after page refresh

Just about to launch a new hobby website. All working well apart from the maps! When a page containing a map first loads, the map typically doesn't show, instead it just shows a blank space and then a number of white rows/narrow bars. If I refresh the page, it works OK. Any ideas?

Thank you!

    <div style="text-align:center">
        <div id="search_map" class="map img-responsive" style="height: 30rem;width:100%;max-width:500px;text-align:center;margin: 0 auto;"></div>

           <div id="popupmap" class="ol-popup" style="background-color: white;box-shadow: 0 1px 4px rgba(0,0,0,0.2);
               border-width: 10px;padding: 8px;border-radius: 10px;border: 1px solid #cccccc;font-size: 8px;text-align:center" >
               <div id="popup-contentmap"></div>
           </div>  
    </div>


    <script type="text/javascript">

  var map = new ol.Map({
    target: 'search_map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
        view: new ol.View({
          center: ol.proj.fromLonLat([<%= @record.long %>,<%= @record.lat %>]),
          zoom: 15
        })
  });
  

  
          {
        var container1 = document.getElementById('popupmap');
        var content1 = document.getElementById('popup-contentmap');
      
        var overlay1 = new ol.Overlay({
           element: container1
        });
        
        map.addOverlay(overlay1);
        content1.innerHTML = '<p class="normaltext" style="padding:0px;margin:0px;font-size:8px;"><%= image_tag("photo.jpg", :size => "20x20", :crop => :fill, :style => "") %>&nbsp;&nbsp;<a href="link" class="normaltextlink"><%= @record.eateryname %>' + '</a></p>';

        overlay1.setPosition(ol.proj.fromLonLat([<%= @record.long %>,<%= @record.lat %>]));
        }

      
        var layer = new ol.layer.Vector({
         source: new ol.source.Vector({
             features: [
                 new ol.Feature({
                     geometry: new ol.geom.Point(ol.proj.fromLonLat([<%= @record.long %>,<%= @record.lat %>]))
                 })
             ]
         })
        });
        map.addLayer(layer);
      

    map.updateSize();

</script>

Upvotes: 0

Views: 383

Answers (1)

Enis
Enis

Reputation: 306

You can try wrapping the map initialization code in a function and calling that function after the DOM has finished loading.

window.onload = function() {
  var map = new ol.Map({
    target: 'search_map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
        view: new ol.View({
          center: ol.proj.fromLonLat([<%= @record.long %>,<%= @record.lat %>]),
          zoom: 15
        })
  });
};

Upvotes: 0

Related Questions