Search code examples
openlayers

How can I pin the top of the map to the top of the containing div?


If I scroll down, the top of the map appears below the edge of the containing div and the blue background appears.

background leak top

The same thing happens if I scroll up. The bottom of the map appears above the edge of the containing div. I would like to pin the bottom of the map to the bottom of the containing div.

background leak bottom

How can I pin the top of the map to the top of the containing div so this blue background does not show up?

const map = new ol.Map({
  target: "map",
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  view: new ol.View({
    projection: "EPSG:4326",
    center: [120, 15],
    zoom: 2
  })
});
#map {
  aspect-ratio: 3 / 1;
  background-color: blue;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/7.3.0/ol.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/7.3.0/dist/ol.min.js"></script>
<div id="map"></div>


Solution

  • OSM does not have any coverage above or below 85 degrees north or south. If you must use OSM in EPSG:4326 set an extent constraint to allow wrapping but not exceed those latitudes:

    const map = new ol.Map({
      target: "map",
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      view: new ol.View({
        projection: "EPSG:4326",
        center: [120, 15],
        zoom: 2,
        extent: [-Infinity, -85, Infinity, 85],
        smoothExtentConstraint: false,
      })
    });
    #map {
      aspect-ratio: 3 / 1;
      background-color: blue;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/7.3.0/ol.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/7.3.0/dist/ol.min.js"></script>
    <div id="map"></div>