OVERLAY KML ON OPENTOPOMAP USING OPENLAYERS

A small page outlining how I spent far too long figuring out how to overlay some KML onto an OpenTopoMap map using OpenLayers.

There are many reasons why I struggled: I found the OpenLayers examples to be mostly unhelpful (what's with all the examples centring the map on [0, 0], which, incidentally, is in metres, and not longitude/latitude, sparking a bajillion Stack Exchange questions right from the get-go?); the OpenLayers API has evolved a good deal over its lifetime, and many web examples are now very out-of-date; and, the OpenStreetMap help has a small 'bug' (see below).

To get set-up (especially if you've never used Node.js before), start here. Once you've got that up-and-running, augment your JS file as follows:

import 'ol/ol.css';
import {Map, View} from 'ol';
import KML from 'ol/format/KML';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import VectorSource from 'ol/source/Vector';
import XYZ from 'ol/source/XYZ';
import {fromLonLat} from 'ol/proj';

const kml = new VectorLayer({source: new VectorSource({url: 'TWR.kml', format: new KML()})});

const map = new Map({
 target: 'map',
 layers: [new TileLayer({title: 'My OpenTopoMap',
 type: 'base',
 visible: true,
 source: new XYZ({attributions: 'Kartendaten: © OpenStreetMap -Mitwirkende, SRTM | Kartendarstellung: © OpenTopoMap (CC-BY-SA)', url: 'https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png'})}), kml],
 view: new View({center: fromLonLat([175.31546, -40.80160]), zoom: 11})
});

Notes

Hope this helps someone!