Skip to content

Measure Distances

Click the map to place points and measure the distance between them using Turf.js.

const API_KEY = 'toursprung';

    const map = new maptoolkit.Map({
        container: 'map',
        style: `https://static.maptoolkit.net/styles/toursprung/terrain.json?api_key=${API_KEY}`,
        center: [12.0, 47.5],
        zoom: 7,
        attributionControl: { compact: false }
    });

    map.addControl(new maptoolkit.NavigationControl(), 'top-right');

    const geojson = { type: 'FeatureCollection', features: [] };
    const linestring = { type: 'Feature', geometry: { type: 'LineString', coordinates: [] } };

    map.on('load', () => {
        map.addSource('geojson', { type: 'geojson', data: geojson });

        map.addLayer({ id: 'measure-points', type: 'circle', source: 'geojson',
            paint: { 'circle-radius': 5, 'circle-color': '#ee8a65' },
            filter: ['==', '$type', 'Point']
        });

        map.addLayer({ id: 'measure-lines', type: 'line', source: 'geojson',
            paint: { 'line-color': '#888', 'line-width': 2.5, 'line-dasharray': [3, 2] },
            filter: ['==', '$type', 'LineString']
        });

        map.on('click', (e) => {
            const point = { type: 'Feature', geometry: { type: 'Point', coordinates: [e.lngLat.lng, e.lngLat.lat] } };
            if (geojson.features.length > 1) geojson.features.pop();
            geojson.features.push(point);

            if (geojson.features.length > 1) {
                linestring.geometry.coordinates = geojson.features.map(f => f.geometry.coordinates);
                geojson.features.push(linestring);
                const dist = turf.length(linestring, { units: 'kilometers' });
                document.getElementById('distance').textContent = `Distance: ${dist.toFixed(2)} km`;
            }

            map.getSource('geojson').setData(geojson);
        });

        map.on('mouseenter', 'measure-points', () => { map.getCanvas().style.cursor = 'crosshair'; });
        map.on('mouseleave', 'measure-points', () => { map.getCanvas().style.cursor = ''; });
        map.getCanvas().style.cursor = 'crosshair';
    });
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Measure Distances – Maptoolkit Maps JS</title>
    <meta property="og:description" content="Click the map to place points and measure the distance between them using Turf.js." />
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://unpkg.com/@maptoolkit/maps@11.0.0-beta.2/dist/maptoolkit.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@maptoolkit/maps@11.0.0-beta.2/dist/maptoolkit.css" />
    <script src="https://unpkg.com/@turf/turf@6/turf.min.js"></script>
    <style>
        html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
        #map { width: 100%; height: 100%; }
        #distance {
            position: absolute;
            top: 10px;
            left: 10px;
            background: white;
            padding: 10px 14px;
            border-radius: .4rem;
            font-family: sans-serif;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div id="map"></div>
<div id="distance">Click to add points and measure distance</div>
<script>
    const API_KEY = 'toursprung';

    const map = new maptoolkit.Map({
        container: 'map',
        style: `https://static.maptoolkit.net/styles/toursprung/terrain.json?api_key=${API_KEY}`,
        center: [12.0, 47.5],
        zoom: 7,
        attributionControl: { compact: false }
    });

    map.addControl(new maptoolkit.NavigationControl(), 'top-right');

    const geojson = { type: 'FeatureCollection', features: [] };
    const linestring = { type: 'Feature', geometry: { type: 'LineString', coordinates: [] } };

    map.on('load', () => {
        map.addSource('geojson', { type: 'geojson', data: geojson });

        map.addLayer({ id: 'measure-points', type: 'circle', source: 'geojson',
            paint: { 'circle-radius': 5, 'circle-color': '#ee8a65' },
            filter: ['==', '$type', 'Point']
        });

        map.addLayer({ id: 'measure-lines', type: 'line', source: 'geojson',
            paint: { 'line-color': '#888', 'line-width': 2.5, 'line-dasharray': [3, 2] },
            filter: ['==', '$type', 'LineString']
        });

        map.on('click', (e) => {
            const point = { type: 'Feature', geometry: { type: 'Point', coordinates: [e.lngLat.lng, e.lngLat.lat] } };
            if (geojson.features.length > 1) geojson.features.pop();
            geojson.features.push(point);

            if (geojson.features.length > 1) {
                linestring.geometry.coordinates = geojson.features.map(f => f.geometry.coordinates);
                geojson.features.push(linestring);
                const dist = turf.length(linestring, { units: 'kilometers' });
                document.getElementById('distance').textContent = `Distance: ${dist.toFixed(2)} km`;
            }

            map.getSource('geojson').setData(geojson);
        });

        map.on('mouseenter', 'measure-points', () => { map.getCanvas().style.cursor = 'crosshair'; });
        map.on('mouseleave', 'measure-points', () => { map.getCanvas().style.cursor = ''; });
        map.getCanvas().style.cursor = 'crosshair';
    });
</script>
</body>
</html>