Skip to content

Animate symbol to follow the mouse

Animate symbol to follow the mouse.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Animate symbol to follow the mouse</title>
    <meta property="og:description" content="Animate symbol to follow the mouse." />
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.0.1/dist/maplibre-gl.css' />
    <script src='https://unpkg.com/maplibre-gl@5.0.1/dist/maplibre-gl.js'></script>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        html,
        body,
        #map {
            height: 100%;
        }
    </style>
</head>

<body>
    <div id="map"></div>
    <script>
        const map = new maplibregl.Map({
            container: 'map',
            projection: {type: 'globe'},
            style:
                'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
            center: [0, 0],
            zoom: 2
        });

        map.on('mousemove', (e) => {
            const lngLat = e.lngLat.wrap();
            const pointSource = map.getSource('point');

            if (pointSource && lngLat.lng && lngLat.lat) {
                pointSource.setData({
                    'type': 'Point',
                    'coordinates': [lngLat.lng, lngLat.lat]
                });
            }
        });
        map.addControl(new maplibregl.GlobeControl());

        map.on('load', () => {

            map.addSource('point', {
                'type': 'geojson',
                'data': {
                    'type': 'Point',
                    'coordinates': [0, 0]
                }
            });

            map.addLayer({
                'id': 'point',
                'source': 'point',
                'type': 'symbol',
                'layout': {
                    'icon-image': 'airport_15',
                    'icon-allow-overlap': true,
                    'icon-ignore-placement': true
                },
            });
        });
    </script>
</body>

</html>