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.

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.tsimport { 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);
}
} The React version uses the library's React adapter, cc-openlayers/react: each component creates the OpenLayers object it names when it mounts, updates it from its props and disposes of it when it unmounts.
center.react.tsximport { useRef, type CSSProperties } from 'react';
import type OLMap from 'ol/Map.js';
import type OLView from 'ol/View.js';
import type OLVectorSource from 'ol/source/Vector.js';
import type Point from 'ol/geom/Point.js';
import type SimpleGeometry from 'ol/geom/SimpleGeometry.js';
import {
CircleStyle,
Coordinate,
DefaultControls,
DefaultInteractions,
Feature,
Fill,
GeoJSONSource,
Map,
OSMSource,
PointGeometry,
Stroke,
Style,
TileLayer,
VectorLayer,
VectorSource,
View,
} from 'cc-openlayers/react';
const padding = [120, 50, 30, 150];
/** The padding as the sizes of the bands that stand for content over the map's edges. */
const edges = {
'--top': `${padding[0]}px`,
'--right': `${padding[1]}px`,
'--bottom': `${padding[2]}px`,
'--left': `${padding[3]}px`,
} as CSSProperties;
const polandStyle = {
'stroke-color': '#319FD3',
'stroke-width': 1,
'fill-color': 'rgba(255, 255, 255, 0.6)',
};
/**
* 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.
*/
export function Center() {
const map = useRef<OLMap>(null);
const view = useRef<OLView>(null);
const poland = useRef<OLVectorSource>(null);
const point = useRef<Point>(null);
const zoomToPoland = () => {
const geometry = poland.current?.getFeatures()[0]?.getGeometry() as SimpleGeometry | undefined;
if (geometry) view.current?.fit(geometry, { padding });
};
const zoomToKrakow = () => {
view.current?.fit(point.current as Point, { padding, minResolution: 50 });
};
/** Puts Kraków in the middle of the area the padding leaves free. */
const centerOnKrakow = () => {
const size = map.current?.getSize() ?? [0, 0];
const position = [
padding[3] + (size[0] - padding[1] - padding[3]) / 2,
padding[0] + (size[1] - padding[0] - padding[2]) / 2,
];
view.current?.centerOn((point.current as Point).getCoordinates(), size, position);
};
return (
<>
<div className="padded-map" style={edges}>
<Map ref={map} height="480px">
<DefaultInteractions />
<DefaultControls />
<View ref={view} zoom={6}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<OSMSource />
</TileLayer>
<VectorLayer style={polandStyle}>
<GeoJSONSource ref={poland} url="assets/poland/poland.geojson" featureProjection="EPSG:3857" />
</VectorLayer>
<VectorLayer>
<VectorSource>
<Feature>
<PointGeometry ref={point}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</PointGeometry>
<Style>
<CircleStyle radius={5}>
<Stroke color="#319FD3" width={1} />
<Fill color="rgba(255, 255, 255, 0.6)" />
</CircleStyle>
</Style>
</Feature>
</VectorSource>
</VectorLayer>
</Map>
<div className="padding-band top"></div>
<div className="padding-band right"></div>
<div className="padding-band bottom"></div>
<div className="padding-band left"></div>
<div className="padding-target"></div>
</div>
<div className="example-controls">
<button type="button" onClick={zoomToPoland}>
Zoom to Poland
</button>
<button type="button" onClick={zoomToKrakow}>
Zoom to Kraków
</button>
<button type="button" onClick={centerOnKrakow}>
Center on Kraków
</button>
<p className="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>
</>
);
}How the React version works
Buttons fit the view to Poland's outline or to the point of Kraków and put Kraków in the middle of the area clear of the bands at the edges. The view itself has no padding: only fit and centerOn take it into account.
What both versions share
OpenLayers renders the map and handles the interactions; the cc-openlayers/core layer gives both adapters the same view binding (MapViewBinding) and the same conversion of coordinates from EPSG:4326 to the map's projection. A GeoJSON source reads Poland's outline; the padding bands and their styles (padded-map, padding-band) are global gallery classes both versions use.
From Angular to React
| Angular | React |
|---|---|
viewChild of the map, view, source and geometry with .instance | four useRef calls passed as ref to Map, View, GeoJSONSource and PointGeometry |
[style]="edges" from the class field edges | the module constant edges with CSS variables passed as style |
(click)="zoomToPoland()" | onClick={zoomToPoland} |
Who creates, updates and disposes
Map creates the ol/Map in useLayoutEffect and disposes of it on unmount; each layer, source and interaction component adds its object to the parent it gets from context and removes it in its effect's cleanup, as ngOnDestroy does in Angular. The buttons read the OpenLayers objects from the refs when clicked; until the outline has loaded, “Zoom to Poland” changes nothing.
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: 50stops the zoom at 50 metres per pixel instead of zooming in to maximum scale. centerOnplaces a coordinate at an exact viewport pixel;centerOnKrakow()derives the midpoint of the uncovered window from the map size andpadding.- CSS custom properties driven from the same
paddingvalues 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.
Related examples
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.