Vector data · Angular, React and OpenLayers

Drop GPX, GeoJSON, IGC, KML and TopoJSON files

Drop local GPX, GeoJSON, IGC, KML or TopoJSON files directly onto an OpenLayers map to create styled vector layers client-side in the browser.

The orthophoto of Kraków with two dropped KML districts outlined in red with green fills, fitted to the map, and the district under the pointer named below it.
A screenshot of the example. Orthophotomap © GUGiK. Map data © OpenStreetMap contributors.

What this example shows

Over GUGiK’s aerial orthophotomap of Kraków, dragging any local .gpx, .geojson, .igc, .kml or .topojson file from your desktop onto the map parses its geometries entirely in browser memory, mounts a fresh vector layer, and zooms smoothly to frame the imported data with 40 pixels of margin.

Sample download buttons let you test immediately, a checkbox toggles whether dropped KML files keep their embedded styles or use layer defaults, and hovering lists feature names below.

When you need it

Surveyors, planners and GIS analysts constantly want to overlay an ad-hoc boundary .geojson, handheld GPS .gpx walk or Google Earth .kml export over your basemap without uploading sensitive files to a backend server.

Browser-native DragAndDrop parsing delivers zero-latency previewing while keeping user files 100% private on the client device.

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.

drag-and-drop.ts
import { ChangeDetectionStrategy, Component, signal, viewChild } from '@angular/core';
import type Feature from 'ol/Feature';
import type MapBrowserEvent from 'ol/MapBrowserEvent';
import { getTopLeft, getWidth } from 'ol/extent';
import GeoJSON from 'ol/format/GeoJSON';
import GPX from 'ol/format/GPX';
import IGC from 'ol/format/IGC';
import KML from 'ol/format/KML';
import TopoJSON from 'ol/format/TopoJSON';
import type { DragAndDropEvent } from 'ol/interaction/DragAndDrop';
import VectorLayer from 'ol/layer/Vector';
import { EXTENT } from 'ol/proj/epsg3857';
import VectorSource from 'ol/source/Vector';
import {
  CoordinateComponent,
  DefaultControlComponent,
  DefaultInteractionComponent,
  type DragAndDropFormat,
  DragAndDropInteractionComponent,
  LayerTileComponent,
  MapComponent,
  SourceTileWMTSComponent,
  TileGridWMTSComponent,
  ViewComponent,
} from 'cc-openlayers';

const size = getWidth(EXTENT) / 256;

/** The sample files offered for download: a button label and the file under `assets/drag-and-drop/`. */
const SAMPLES = [
  { label: 'GPX', file: 'vistula-route.gpx' },
  { label: 'GeoJSON', file: 'krakow-landmarks.geojson' },
  { label: 'IGC', file: 'flight.igc' },
  { label: 'KML', file: 'districts.kml' },
  { label: 'TopoJSON', file: 'districts.topojson' },
];

/** GPX, GeoJSON, IGC, KML and TopoJSON files dropped on the map become vector layers; the KML styles can be left out. */
@Component({
  selector: 'app-drag-and-drop',
  imports: [
    CoordinateComponent,
    DefaultControlComponent,
    DefaultInteractionComponent,
    DragAndDropInteractionComponent,
    LayerTileComponent,
    MapComponent,
    SourceTileWMTSComponent,
    TileGridWMTSComponent,
    ViewComponent,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <aol-map height="480px" (pointerMove)="describe($event)" (olClick)="describe($event)">
      <aol-interaction-default />
      <!-- OpenLayers reads the formats once, so each choice of the KML styles is its own interaction. -->
      @if (extractStyles()) {
        <aol-interaction-draganddrop [formatConstructors]="withStyles" (addFeatures)="show($event)" />
      } @else {
        <aol-interaction-draganddrop [formatConstructors]="withoutStyles" (addFeatures)="show($event)" />
      }
      <aol-control-defaults />
      <aol-view [zoom]="12">
        <aol-coordinate [x]="19.9368" [y]="50.0614" srid="EPSG:4326" />
      </aol-view>
      <aol-layer-tile>
        <aol-source-tilewmts
          attributions='Tiles © <a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>'
          url="https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution"
          layer="ORTOFOTOMAPA"
          matrixSet="EPSG:3857"
          format="image/jpeg"
          projection="EPSG:3857"
          [style]="'default'"
        >
          <aol-tilegrid-wmts [origin]="origin" [resolutions]="resolutions" [matrixIds]="matrixIds" />
        </aol-source-tilewmts>
      </aol-layer-tile>
    </aol-map>
    <div class="example-controls">
      <label>
        <input type="checkbox" [checked]="extractStyles()" (change)="extractStyles.set(checked($event))" />
        Extract styles from KML
      </label>
      <span>
        Download samples
        @for (sample of samples; track sample.file) {
          <button type="button" (click)="download(sample.file)">{{ sample.label }}</button>
        }
      </span>
      <p class="example-hint">
        Drag and drop GPX, GeoJSON, IGC, KML or TopoJSON files on to the map. The walk, the square and the districts of
        the samples are ©
        <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors.
      </p>
      <output>{{ info() }}</output>
    </div>
  `,
})
export class DragAndDrop {
  readonly extractStyles = signal(true);
  readonly info = signal('');
  protected readonly samples = SAMPLES;
  protected readonly withStyles: DragAndDropFormat[] = [GPX, GeoJSON, IGC, new KML({ extractStyles: true }), TopoJSON];
  protected readonly withoutStyles: DragAndDropFormat[] = [
    GPX,
    GeoJSON,
    IGC,
    new KML({ extractStyles: false }),
    TopoJSON,
  ];
  protected readonly origin = getTopLeft(EXTENT);
  protected readonly resolutions = Array.from({ length: 20 }, (_, z) => size / 2 ** z);
  protected readonly matrixIds = Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`);
  private readonly map = viewChild.required(MapComponent);

  protected checked(event: Event): boolean {
    return (event.target as HTMLInputElement).checked;
  }

  /** The names of the features under the pointer. */
  protected describe(event: MapBrowserEvent): void {
    if (event.dragging) return;
    const names: string[] = [];
    this.map().instance.forEachFeatureAtPixel(event.pixel, (feature) => {
      names.push(feature.get('name'));
    });
    this.info.set(names.join(', '));
  }

  /** Shows the dropped features in a new layer and fits the view to them, 40 pixels inside the map's edges. */
  protected show(event: DragAndDropEvent): void {
    const source = new VectorSource({ features: event.features as Feature[] });
    const map = this.map().instance;
    map.addLayer(new VectorLayer({ source }));
    map.getView().fit(source.getExtent(), { padding: [40, 40, 40, 40] });
  }

  protected async download(file: string): Promise<void> {
    const response = await fetch(`assets/drag-and-drop/${file}`);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(await response.blob());
    link.download = file;
    link.click();
  }
}

Architecture and OpenLayers mechanics

aol-interaction-draganddrop accepts an ordered array of formatConstructors and tests each dropped file sequentially until a parser yields features projected into the active view CRS. Its (addFeatures) output passes the parsed array to show, which wraps them in a new VectorLayer and fits their extent.

Because DragAndDrop instantiates its format parsers once at construction time, toggling KML style extraction swaps cleanly between two @if interaction branches configured with extractStyles: true and extractStyles: false.

How it works

  • aol-interaction-draganddrop tries each parser in formatConstructors in order until one extracts valid features.
  • (addFeatures) delivers features already transformed into the view projection; show mounts a new VectorLayer and fits the view with 40 px padding.
  • Switching @if branches toggles KML parsing cleanly between extractStyles: true and extractStyles: false.
  • Sample file buttons and live pointer hover inspection make testing multi-format drops effortless.

Pitfalls

  • Each file drop appends another VectorLayer to the map—add a Clear / layer-removal UI in production apps so repeated drops do not accumulate unbounded layers in memory.
  • Parser order inside formatConstructors matters: place stricter schemas ahead of overly permissive formats so the right parser claims each file.

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.