两个不同的 js 都生成一个 openlayers 地图,每个都不会替换另一个 div

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

有一个简单的 div with id='map'

和一个 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("");
    }

执行 MapPlayOL.simpleMap() 填充地图。之后执行 MapPlayOL.mainMap() 不会替换 div 的内容:没有新地图出现。 反之亦然。只有在中间执行 MapPlayOL.clearMap() 才允许第二次调用替换 div.

的内容

为什么?

它确实添加了地图,但没有叠加它们。如果您将地图 div 高度设置为 100%,您将看到第二张地图,您需要向下滚动才能在第一张地图下方看到它。

要叠加地图,您需要在容器内放置 2 divs

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

并将它们放在 css

  .map {
    position: absolute;
  }