Essentials · Angular, React and OpenLayers

Fit a geometry into the free part of the map

Fit polygons or points into the uncovered area of an OpenLayers map using per-call fit padding, minResolution limits and pixel-accurate centerOn.

Poland fitted into the area that dark translucent bands along the map's edges leave free, with a dot on Kraków, a blue square in the middle of that area and the three buttons below the map.
A screenshot of the example. Administrative boundaries © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Translucent dark bands along the top, right, bottom and left edges of the viewport represent floating UI chrome—such as a search header, side panel and bottom bar—leaving an asymmetric clear window over the map with a blue square marking its exact midpoint. Three buttons below the map fit the outline of Poland into that clear area, zoom to a point in Kraków, or place Kraków directly under the midpoint marker.

Each button frames its target inside the unobstructed region on demand while leaving the view’s default centre unchanged for manual panning and rotation.

When you need it

Real-world map interfaces almost always float sidebars, toolbars or mobile bottom sheets above a full-bleed map canvas.

Without accounting for those overlays, zooming to a selected parcel or city centres it behind an open drawer or hides polygon edges beneath the header. Per-call fit padding and centerOn solve one-off camera framing cleanly when you do not want to permanently shift the view’s pivot for everyday navigation.

The code

The example uses cc-openlayers, my Angular component library for OpenLayers: each aol-… element creates the OpenLayers object it names, updates it from its inputs and disposes of it with the component.

center.ts
import { ChangeDetectionStrategy, Component, viewChild } from '@angular/core';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  FeatureComponent,
  GeometryPointComponent,
  SourceGeoJSONComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  SourceOsmComponent,
  SourceVectorComponent,
  StyleCircleComponent,
  StyleComponent,
  StyleFillComponent,
  StyleStrokeComponent,
  ViewComponent,
} from 'cc-openlayers';
import type SimpleGeometry from 'ol/geom/SimpleGeometry';

const padding = [120, 50, 30, 150];

/**
 * The view fitted to a polygon or a point inside a padded area, and a coordinate moved to a chosen pixel. The view
 * itself has no padding: only `fit` and `centerOn` take the bands into account.
 */
@Component({
  selector: 'app-center',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    FeatureComponent,
    GeometryPointComponent,
    SourceGeoJSONComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    SourceOsmComponent,
    SourceVectorComponent,
    StyleCircleComponent,
    StyleComponent,
    StyleFillComponent,
    StyleStrokeComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="padded-map" [style]="edges">
      <aol-map height="480px">
        <aol-interaction-default />
        <aol-control-defaults />
        <aol-view [zoom]="6">
          <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
        </aol-view>
        <aol-layer-tile><aol-source-osm /></aol-layer-tile>
        <aol-layer-vector [style]="polandStyle">
          <aol-source-geojson url="assets/poland/poland.geojson" featureProjection="EPSG:3857" />
        </aol-layer-vector>
        <aol-layer-vector>
          <aol-source-vector>
            <aol-feature>
              <aol-geometry-point><aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" /></aol-geometry-point>
              <aol-style>
                <aol-style-circle [radius]="5">
                  <aol-style-stroke color="#319FD3" [width]="1" />
                  <aol-style-fill color="rgba(255, 255, 255, 0.6)" />
                </aol-style-circle>
              </aol-style>
            </aol-feature>
          </aol-source-vector>
        </aol-layer-vector>
      </aol-map>
      <div class="padding-band top"></div>
      <div class="padding-band right"></div>
      <div class="padding-band bottom"></div>
      <div class="padding-band left"></div>
      <div class="padding-target"></div>
    </div>
    <div class="example-controls">
      <button type="button" (click)="zoomToPoland()">Zoom to Poland</button>
      <button type="button" (click)="zoomToKrakow()">Zoom to Kraków</button>
      <button type="button" (click)="centerOnKrakow()">Center on Kraków</button>
      <p class="example-hint">
        The bands stand for content over the map's edges. Both zooms fit inside the area they leave free, and centring
        puts Kraków in the box in its middle; the view's own centre stays put, so the zoom buttons still zoom around the
        middle of the whole map.
      </p>
    </div>
  `,
})
export class Center {
  /** The padding as the sizes of the bands that stand for content over the map's edges. */
  protected readonly edges = {
    '--top': `${padding[0]}px`,
    '--right': `${padding[1]}px`,
    '--bottom': `${padding[2]}px`,
    '--left': `${padding[3]}px`,
  };
  protected readonly polandStyle = {
    'stroke-color': '#319FD3',
    'stroke-width': 1,
    'fill-color': 'rgba(255, 255, 255, 0.6)',
  };
  private readonly map = viewChild.required(MapComponent);
  private readonly view = viewChild.required(ViewComponent);
  private readonly poland = viewChild.required(SourceGeoJSONComponent);
  private readonly point = viewChild.required(GeometryPointComponent);

  protected zoomToPoland(): void {
    const geometry = this.poland().instance.getFeatures()[0]?.getGeometry() as SimpleGeometry | undefined;
    if (geometry) this.view().instance.fit(geometry, { padding });
  }

  protected zoomToKrakow(): void {
    this.view().instance.fit(this.point().instance, { padding, minResolution: 50 });
  }

  /** Puts Kraków in the middle of the area the padding leaves free. */
  protected centerOnKrakow(): void {
    const size = this.map().instance.getSize() ?? [0, 0];
    const position = [
      padding[3] + (size[0] - padding[1] - padding[3]) / 2,
      padding[0] + (size[1] - padding[0] - padding[2]) / 2,
    ];
    this.view().instance.centerOn(this.point().instance.getCoordinates(), size, position);
  }
}

Architecture and OpenLayers mechanics

Passing { padding } to fit(geometry, { padding }) insets the target bounding box by [120, 50, 30, 150] pixels (top, right, bottom, left) during that single operation while keeping the underlying view unpadded. Because a single point geometry has zero area and would otherwise zoom in to the deepest tile level, minResolution: 50 caps point fits at 50 metres per pixel.

When you want to reposition a coordinate without altering the current zoom level, centerOn translates a map coordinate so it lands on the exact screen pixel computed by centerOnKrakow() from the live viewport dimensions and padding offsets.

How it works

  • fit(geometry, { padding }) zooms to Poland’s administrative polygon while keeping 120, 50, 30 and 150 pixels clear along the top, right, bottom and left edges.
  • When fitting the Kraków point geometry, minResolution: 50 stops the zoom at 50 metres per pixel instead of zooming in to maximum scale.
  • centerOn places a coordinate at an exact viewport pixel; centerOnKrakow() derives the midpoint of the uncovered window from the map size and padding.
  • CSS custom properties driven from the same padding values size the translucent edge bands and centre square so visual chrome and camera math match.

Pitfalls

  • Because the view itself is not padded here, +/- zoom buttons and Alt+Shift drag rotation still pivot around the centre of the entire map element; use view-level padding when every gesture should share the offset centre.
  • Vector boundaries load asynchronously after map startup: guard fit buttons until the vector source has loaded its feature so early clicks safely no-op.
  • Recompute target pixels from the current map size at click time rather than caching mount dimensions so window resizes stay accurate.

The same feature in the OpenLayers examples .

Background: state and lifecycle of maps in Angular with OpenLayers, which the components of cc-openlayers take care of.