Search code examples
javascriptopenlayers

With two different js both generating an openlayers map each does not replace the other in the same div


Having a simple div with id='map'

and an JS:

var MapPlayOL = {
    myinfo: "MapObjectOL",

    simpleMap : function() {
        var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([12.82, 50.41]),
          zoom: 7
        })
        });
    },

    mainMap : function() {
        var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([37.41, 8.82]),
          zoom: 4
        })
            });
    },

    clearMap : function() {
        $( "#map" ).html("");
    }

Executing MapPlayOL.simpleMap() fills the map. Afterwards executing MapPlayOL.mainMap() does not replace the content of the div: no new map appears. Same happens vice versa. Only executing MapPlayOL.clearMap() inbetween allows the second call to replace the content of the div.

Why?


Solution

  • It does add the map, but it does not superimpose them. If you set the map div height to 100% you will see the second map, you need to scroll down to see it below the first.

    To superimpose maps you would need 2 divs inside a container

    <div id="container" class="container">
      <div id="map1" class="map"></div>
      <div id="map2" class="map"></div>
    </div>
    

    and position them in the css

      .map {
        position: absolute;
      }