openlayers

How can I show just a single world when zoomed out using OpenLayers & EPSG:3857?


I asked a similar question and the answer remains valid for EPSG:4326, but I need to know how to get the same result using EPSG:3857.

I thought I would only need to use ol.proj.transformExtent to transform the two extents from 4326 to 3857, but that didn't quite work. The map does work, but the result is not what I want.

How can I get only a single world to show when the zoom level is 0 and I am using EPSG:3857? What code do I need to change?

const sourceEPSG = "EPSG:4326";
const epsg = 'EPSG:3857';
const osmExtent = [-180, -85, 180, 85];
const wholeExtent = [-180, -90, 180, 90];

epsgOSMExtent = ol.proj.transformExtent( osmExtent, sourceEPSG, epsg )
epsgWholeExtent = ol.proj.transformExtent( wholeExtent, sourceEPSG, epsg )

ol.proj.get(epsg).setExtent(epsgOSMExtent);

const osm = new ol.source.OSM();

osm.setTileGridForProjection(
  epsg,
  ol.tilegrid.createXYZ({ extent: wholeExtent })
);

const tileLayer = new ol.layer.Tile({ source: osm });

const map = new ol.Map({
  target: "map",
  layers: [tileLayer],
  view: new ol.View({
    projection: epsg,
    center: [0, 0],
    zoom: 3
  }),
  controls: ol.control.defaults.defaults({ attribution: false, zoom: false })
});
#map {
  width: 1024px;
  aspect-ratio: 360/170;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/10.2.1/ol.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/10.2.1/dist/ol.min.js"></script>

<div style="background-color: red;" id="map"></div>


Solution

  • OSM at zoom level 0 uses a single 256 x 256 pixel tile, so you will need a map div the same size:

    const osm = new ol.source.OSM();
    
    const tileLayer = new ol.layer.Tile({ source: osm });
    
    const map = new ol.Map({
      target: "map",
      layers: [tileLayer],
      view: new ol.View({
        center: [0, 0],
        zoom: 0
      }),
      controls: ol.control.defaults.defaults({ attribution: false, zoom: false })
    });
    #map {
      width: 256px;
      aspect-ratio: 1;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/10.2.1/ol.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/10.2.1/dist/ol.min.js"></script>
    
    <div style="background-color: red;" id="map"></div>