Skip to main content

Draggable Marker

Add a draggable marker to the map.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="https://maps-sdk.trimblemaps.com/v3/trimblemaps-3.17.0.css" />
        <script src="https://maps-sdk.trimblemaps.com/v3/trimblemaps-3.17.0.js"></script>
        <style>
            body { margin: 0; padding: 0; }

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

            .map-panel {
                position: absolute;
                width: 225px;
                top: 10px;
                left: 10px;
                padding: 10px;
                background-color: #fff;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
                font-family: Arial, Helvetica, sans-serif;
                font-size: .85em;
            }

            .group {
                padding: 3px 0;
            }

            .group .label {
                display: inline-block;
                width: 65px;
                font-style: italic;
                color: #888;
            }

            .group .value {
                display: inline-block;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
        <div class="map-panel">
            <div class="group">
            <span class="label">Longitude:</span>
            <span id="longitude" class="value"></span>
            </div>
            <div class="group">
            <span class="label">Latitude:</span>
            <span id="latitude" class="value"></span>
            </div>
        </div>

        <script>
            TrimbleMaps.APIKey = 'YOUR_API_KEY_HERE';
            const map = new TrimbleMaps.Map({
                container: 'map', // container id
                center: [-87, 38],
                zoom: 8
            });

            // Save the panel elements
            const lngElem = document.getElementById('longitude');
            const latElem = document.getElementById('latitude');

            const marker = new TrimbleMaps.Marker({
                draggable: true
            }).setLngLat([-87, 38]).addTo(map);

            lngElem.innerHTML = '-87.00';
            latElem.innerHTML = '38.00';

            // Listen to the dragend event of the marker
            marker.on('dragend', function(e){
                // Extract the lngLat object from the marker in the event
                const lngLat = e.target.getLngLat();

                // Update the values in the panel
                lngElem.innerHTML = lngLat.lng;
                latElem.innerHTML = lngLat.lat;
            });
        </script>
    </body>
</html>
Last updated June 15, 2023.