Skip to main content

Mouse Position

Track the location of the mouse pointer as it moves around 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: 'Open Sans', sans-serif;
                font-size: .85em;
            }

            .group {
                padding: 3px 0;
            }

            .group .label {
                display: inline-block;
                width: 70px;
                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
              style: TrimbleMaps.Common.Style.TRANSPORTATION, //hosted style id
              center: [-77.38, 40], // starting position
              zoom: 7 // starting zoom
            });

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

            // Listen to the mousemove event on the map
            map.on('mousemove', function(e) {
              // Extract the lngLat object from the event
              const lngLat = e.lngLat;

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