Skip to content

Add custom icons with Markers

Add custom marker icons to your map.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Add custom icons with Markers</title>
    <meta property="og:description" content="Add custom marker icons to your map." />
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/trackasia-gl.css" />
    <script src="https://unpkg.com/[email protected]/dist/trackasia-gl.js"></script>
    <style>
        body { margin: 0; padding: 0; }
        html, body, #map { height: 100%; }
        .marker {
            display: block;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            padding: 0;
        }
    </style>
</head>
<body>

<div id="map"></div>

<script>
    const geojson = {
        'type': 'FeatureCollection',
        'features': [
            {
                'type': 'Feature',
                'properties': {
                    'message': 'Foo',
                    'iconSize': [60, 60]
                },
                'geometry': {
                    'type': 'Point',
                    'coordinates': [99.891196,7.680506]
                }
            },
            {
                'type': 'Feature',
                'properties': {
                    'message': 'Bar',
                    'iconSize': [50, 50]
                },
                'geometry': {
                    'type': 'Point',
                    'coordinates': [103.017138,13.081618]
                }
            },
            {
                'type': 'Feature',
                'properties': {
                    'message': 'Baz',
                    'iconSize': [40, 40]
                },
                'geometry': {
                    'type': 'Point',
                    'coordinates': [109.257659,12.653202]
                }
            }
        ]
    };

    const map = new trackasiagl.Map({
        container: 'map',
        style: 'https://maps.track-asia.com/styles/v2/streets.json?key=public_key',
        center: {"lat":10.762622,"lng":106.660172},
        zoom: 4.9
    });

    // add markers to map
    geojson.features.forEach((marker) => {
        // create a DOM element for the marker
        const el = document.createElement('div');
        el.className = 'marker';
        el.style.backgroundImage =
            `url(https://picsum.photos/${
                marker.properties.iconSize.join('/')
            }/)`;
        el.style.width = `${marker.properties.iconSize[0]}px`;
        el.style.height = `${marker.properties.iconSize[1]}px`;

        el.addEventListener('click', () => {
            window.alert(marker.properties.message);
        });

        // add marker to map
        new trackasiagl.Marker({element: el})
            .setLngLat(marker.geometry.coordinates)
            .addTo(map);
    });
</script>

</body>
</html>