Vector data · Angular, React and OpenLayers

The world's time zones from KML

Style world time-zone polygons from KML in OpenLayers by proximity to local solar noon using silent feature property updates and hover labels.

The world's time zones over a light gray map, brightest yellow in the zone at noon and fading towards midnight, with the tooltip UTC+01:00 over Kraków.
A screenshot of the example. Time zones: Natural Earth. Base map: Esri World Light Gray (Esri, HERE, Garmin, OpenStreetMap contributors and the GIS user community).

What this example shows

Across a global light-grey map centred on Europe, all 119 world time zones (121 polygons, since two offsets hold a MultiGeometry) from a KML dataset glow in warm yellow whose opacity peaks at 0.75 in whichever zone is currently experiencing local noon and fades smoothly to transparent toward local midnight, paired with a live UTC-offset tooltip under the pointer.

When you need it

Global operations centres, distributed-team directories, follow-the-sun support dashboards and aviation schedulers benefit from visualising active daytime and business hours dynamically across time-zone polygons.

Computing fill opacity dynamically inside a style function turns a static boundary file into a live global clock without modifying server data.

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.

kml-timezones.ts
import { afterNextRender, ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import type { FeatureLike } from 'ol/Feature';
import KML from 'ol/format/KML';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import type { VectorSourceEvent } from 'ol/source/Vector';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import {
  ContentComponent,
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  LayerTileComponent,
  LayerVectorComponent,
  MapComponent,
  OverlayComponent,
  SourceImageTileComponent,
  SourceVectorComponent,
  ViewComponent,
} from 'cc-openlayers';

/*
 * Compute the style of the feature.  Here we want the opacity of polygons to
 * be based on the offset from local noon.  For example, a timezone where it is
 * currently noon would have an opacity of 0.75.  And a timezone where it is
 * currently midnight would have an opacity of 0.  This doesn't account for
 * daylight savings, so don't use it to plan your vacation.
 */
const styleFunction = function (feature: FeatureLike) {
  const tzOffset = feature.get('tz-offset');
  const local = new Date();
  local.setTime(local.getTime() + (local.getTimezoneOffset() + (tzOffset || 0)) * 60000);
  // offset from local noon (in hours)
  let delta = Math.abs(12 - (local.getHours() + local.getMinutes() / 60));
  if (delta > 12) {
    delta = 24 - delta;
  }
  const opacity = 0.75 * (1 - delta / 12);
  return new Style({
    fill: new Fill({
      color: [0xff, 0xff, 0x33, opacity],
    }),
    stroke: new Stroke({
      color: '#ffffff',
    }),
  });
};

/**
 * @param name e.g. UTC-08:30
 * @return The offset from UTC in minutes
 */
function parseOffsetFromUtc(name: string): number | null {
  const match = name.match(/([+-]?)(\d{2}):(\d{2})$/);
  if (!match) {
    return null;
  }
  const sign = match[1] === '-' ? -1 : 1;
  const hours = Number(match[2]);
  const minutes = Number(match[3]);
  return sign * (60 * hours + minutes);
}

/**
 * The world's time zones read from a KML file and filled yellow, the more opaque the nearer the zone is to local noon,
 * seen from Kraków in the middle of its own zone. A tooltip at the pointer names the zone under it.
 */
@Component({
  selector: 'app-kml-timezones',
  imports: [
    ContentComponent,
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    LayerTileComponent,
    LayerVectorComponent,
    MapComponent,
    OverlayComponent,
    SourceImageTileComponent,
    SourceVectorComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="move($event)" (olClick)="displayFeatureInfo($event)" (pointerleave)="hide()">
      <aol-interaction-default />
      <aol-control-defaults />
      <aol-view [zoom]="3">
        <aol-coordinate [x]="19.9373" [y]="50.0617" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile>
        <aol-source-imagetile
          url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
          [maxZoom]="16"
          attributions="Tiles © Esri — Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community"
        />
      </aol-layer-tile>
      <aol-layer-vector [style]="style">
        <aol-source-vector
          url="assets/world/time-zones.kml"
          [format]="format"
          attributions="Time zones: Natural Earth"
        />
      </aol-layer-vector>
      <aol-overlay positioning="bottom-center" [offset]="[0, -5]" [stopEvent]="false">
        <aol-coordinate [x]="position()[0]" [y]="position()[1]" />
        <aol-content>
          @if (info(); as name) {
            <span class="example-label">{{ name }}</span>
          }
        </aol-content>
      </aol-overlay>
    </aol-map>
  `,
})
export class KmlTimezones {
  /** The name of the zone under the pointer, shown in the tooltip. */
  readonly info = signal('');
  readonly position = signal<Coordinate>([0, 0]);
  protected readonly style = styleFunction;
  protected readonly format = new KML({
    extractStyles: false,
  });
  private readonly map = viewChild.required(MapComponent);
  private readonly source = viewChild.required(SourceVectorComponent);

  constructor() {
    afterNextRender(() =>
      this.source().instance.on('featuresloadend', function (evt: VectorSourceEvent) {
        evt.features?.forEach(function (feature) {
          const tzOffset = parseOffsetFromUtc(feature.get('name'));
          feature.set('tz-offset', tzOffset, true);
        });
      })
    );
  }

  protected move(event: MapBrowserEvent): void {
    if (event.dragging) {
      this.hide();
      return;
    }
    this.displayFeatureInfo(event);
  }

  protected displayFeatureInfo(event: MapBrowserEvent): void {
    const target = event.originalEvent.target as Element | null;
    const feature = target?.closest('.ol-control')
      ? undefined
      : this.map().instance.forEachFeatureAtPixel(event.pixel, function (feature) {
          return feature;
        });
    if (!feature) {
      this.hide();
      return;
    }
    this.position.set(event.coordinate);
    this.info.set(feature.get('name'));
  }

  protected hide(): void {
    this.info.set('');
  }
}

Architecture and OpenLayers mechanics

Once featuresloadend signals that KML parsing has finished, the handler extracts each polygon’s standard UTC offset (such as UTC+01:00) from its name and stores it as tz-offset via feature.set('tz-offset', tzOffset, true)—passing true for the silent flag so setting properties across 119 polygons does not fire 119 redundant source-change redraws.

During rendering, the layer’s style function combines current UTC clock time with tz-offset to map noon to 0.75 opacity and midnight to 0, while a control-aware pointer overlay displays the hovered zone.

How it works

  • featuresloadend parses each polygon’s UTC offset once on load and stores it under tz-offset.
  • feature.set('tz-offset', tzOffset, true) writes the computed attribute silently without triggering 119 intermediate redraw events.
  • The style function derives local hour per zone from the current clock, scaling yellow fill opacity between 0.75 at noon and 0 at midnight.
  • A pointer-tracking overlay names the time zone under the cursor while ignoring map control buttons.

Pitfalls

  • Standard KML time-zone offsets represent winter standard time without regional Daylight Saving Time rules—during summer CEST, central Europe’s geographic UTC+01:00 band peaks one hour offset from civil summer clocks.
  • Because style functions run when the canvas paints, a stationary tab left untouched for hours keeps the shading from its last render unless a periodic timer triggers layer.changed().

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.