Skip to content

Display contextmenu

Example display contextmenu with TrackAsia GL.

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Display contextmenu</title>
        <meta name="og:description" content="Example display contextmenu with TrackAsia GL." />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/[email protected]/dist/trackasia-gl.js"></script>
        <link href="https://unpkg.com/[email protected]/dist/trackasia-gl.css" rel="stylesheet" />
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        #map {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 100%;
        }

        #where-is-this-with-google-map {
            cursor: pointer;
        }

        #where-is-this-with-google-map:hover {
            color: lightskyblue;
        }
    </style>
</head>

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

    <script>
        var 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: 10
        });

        let contextMarker = new trackasiagl.Marker();
        let popup = new trackasiagl.Popup({ anchor: 'top' });

        function displayContextMenu(map, lngLat) {
            const innerHTML =
                '<p id="where-is-this-with-google-map">Where is this with Google Map?</p>';

            if (popup) popup.remove();
            if (contextMarker) contextMarker.remove();

            contextMarker.setLngLat(lngLat).addTo(map);
            popup.setLngLat(lngLat).setHTML(innerHTML).addTo(map);

            document
                .getElementById('where-is-this-with-google-map')
                .addEventListener('click', () => {
                    window.open(
                        `http://maps.google.com/maps?f=q&q=${lngLat.lat},${lngLat.lng}`,
                        '_blank'
                    );
                    if (popup) popup.remove();
                });
        }

        map.on('contextmenu', function (event) {
            // Handle right-click event here
            // You can access the event object (e.g., event.clientX, event.clientY) to get mouse coordinates

            // Prevent the default context menu from appearing
            event.preventDefault();
            displayContextMenu(map, event.lngLat);
        });
    </script>

</body>
</html>