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.

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.tsimport { 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();
}
} 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.
drag-and-drop.react.tsximport { useRef, useState } from 'react';
import type { Extent } from 'ol/extent.js';
import type Feature from 'ol/Feature.js';
import type OLMap from 'ol/Map.js';
import type MapBrowserEvent from 'ol/MapBrowserEvent.js';
import { getTopLeft, getWidth } from 'ol/extent.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import GPX from 'ol/format/GPX.js';
import IGC from 'ol/format/IGC.js';
import KML from 'ol/format/KML.js';
import TopoJSON from 'ol/format/TopoJSON.js';
import type { DragAndDropEvent } from 'ol/interaction/DragAndDrop.js';
import VectorLayer from 'ol/layer/Vector.js';
import { EXTENT } from 'ol/proj/epsg3857.js';
import VectorSource from 'ol/source/Vector.js';
import {
Coordinate,
DefaultControls,
DefaultInteractions,
DragAndDropInteraction,
Map,
TileLayer,
View,
WMTSSource,
useWMTSTileGrid,
} from 'cc-openlayers/react';
import type { DragAndDropFormat } from 'cc-openlayers/core';
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' },
];
const withStyles: DragAndDropFormat[] = [GPX, GeoJSON, IGC, new KML({ extractStyles: true }), TopoJSON];
const withoutStyles: DragAndDropFormat[] = [GPX, GeoJSON, IGC, new KML({ extractStyles: false }), TopoJSON];
const gridOptions = {
origin: getTopLeft(EXTENT),
resolutions: Array.from({ length: 20 }, (_, z) => size / 2 ** z),
matrixIds: Array.from({ length: 20 }, (_, z) => `EPSG:3857:${z}`),
};
async function 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();
}
/** GPX, GeoJSON, IGC, KML and TopoJSON files dropped on the map become vector layers; the KML styles can be left out. */
export function DragAndDrop() {
const [extractStyles, setExtractStyles] = useState(true);
const [info, setInfo] = useState('');
const map = useRef<OLMap>(null);
const tileGrid = useWMTSTileGrid(gridOptions);
/** The names of the features under the pointer. */
const describe = (event: MapBrowserEvent): void => {
if (event.dragging) return;
const names: string[] = [];
map.current?.forEachFeatureAtPixel(event.pixel, (feature) => {
names.push(feature.get('name'));
});
setInfo(names.join(', '));
};
/** Shows the dropped features in a new layer and fits the view to them, 40 pixels inside the map's edges. */
const show = (event: DragAndDropEvent): void => {
const source = new VectorSource({ features: event.features as Feature[] });
const current = map.current;
if (!current) return;
current.addLayer(new VectorLayer({ source }));
current.getView().fit(source.getExtent() as Extent, { padding: [40, 40, 40, 40] });
};
return (
<>
<Map ref={map} height="480px" onPointerMove={describe} onClick={describe}>
<DefaultInteractions />
{/* OpenLayers reads the formats once, so each choice of the KML styles is its own interaction. */}
{extractStyles ? (
<DragAndDropInteraction key="with" formatConstructors={withStyles} onAddFeatures={show} />
) : (
<DragAndDropInteraction key="without" formatConstructors={withoutStyles} onAddFeatures={show} />
)}
<DefaultControls />
<View zoom={12}>
<Coordinate x={19.9368} y={50.0614} srid="EPSG:4326" />
</View>
<TileLayer>
<WMTSSource
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"
tileGrid={tileGrid}
/>
</TileLayer>
</Map>
<div className="example-controls">
<label>
<input type="checkbox" checked={extractStyles} onChange={(event) => setExtractStyles(event.target.checked)} />
Extract styles from KML
</label>
<span>
Download samples
{SAMPLES.map((sample) => (
<button key={sample.file} type="button" onClick={() => void download(sample.file)}>
{sample.label}
</button>
))}
</span>
<p className="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>
</>
);
}How the React version works
GPX, GeoJSON, IGC, KML and TopoJSON files dropped on the orthophoto become layers and the view fits them; a checkbox decides about the KML styles, and buttons download sample files.
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.
From Angular to React
| Angular | React |
|---|---|
<aol-interaction-draganddrop [formatConstructors] (addFeatures)> | <DragAndDropInteraction formatConstructors onAddFeatures>; the format lists are module constants |
the checkbox's (change) and @if with two interactions | onChange and two <DragAndDropInteraction> elements with different keys, so a change creates a new interaction |
<aol-source-tilewmts> with <aol-tilegrid-wmts> | <WMTSSource> with a grid from useWMTSTileGrid |
(pointerMove) and viewChild of the map | onPointerMove (and onClick) on Map with useRef<OLMap>; the reading in useState |
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 onAddFeatures handler adds the layers of dropped files to the map; they go away with the map on unmount.
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-draganddroptries each parser informatConstructorsin order until one extracts valid features.(addFeatures)delivers features already transformed into the view projection;showmounts a newVectorLayerand fits the view with 40 px padding.- Switching
@ifbranches toggles KML parsing cleanly betweenextractStyles: trueandextractStyles: false. - Sample file buttons and live pointer hover inspection make testing multi-format drops effortless.
Pitfalls
- Each file drop appends another
VectorLayerto the map—add a Clear / layer-removal UI in production apps so repeated drops do not accumulate unbounded layers in memory. - Parser order inside
formatConstructorsmatters: place stricter schemas ahead of overly permissive formats so the right parser claims each file.
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.