Source: map/tools/CoordinateControl.js

import { UiElement } from '../../ui/UiElement.js';
import { roundNumber } from '../../utils/utils.js';
import { formatLatLng } from '../utils/formatLatLng.js';
import "./CoordinateControl.css";

export { CoordinateControl };

/**
 * Simple overlay that shows the currently hovered coordinates
 *
 * @extends UiElement
 * @memberof vef.map.tools
 */
class CoordinateControl extends UiElement {

    /**
     * Creates an instance of CoordinateControl.
     * @param {Map} map - The map object.
     * @param {string} [position="bottom-left"] - The position of the control.
     * @param {LayerTree} layerTree - The layer tree object.
     */
    constructor(map, position, layerTree) {
        super();

        this.map = map;
        this.position = position || "bottom-left";

        this.currentView_ = 0;
        this.lat_ = 0;
        this.lng_ = 0;

        // initialize element
        const element = this.getElement();
        element.classList.add("coordinate-control");
        element.addEventListener("click", () => this.switchView());

        this.map.on("mousemove", e => this.setCoordinates(e.lat, e.lng))
        this.map.addTool(this, this.position);
    }

    /**
     * Switches the view of the coordinate display.
     */
    switchView() {
        this.currentView_ = (this.currentView_ + 1) % 3;
        this.displayCoordinates_();
    }

    /**
     * Displays the coordinates based on the current view.
     * @private
     */
    displayCoordinates_() {
        let html = "";
        let coords = "";

        switch (this.currentView_) {
            case 0:
                const lat = roundNumber(this.lat_, 2, true);
                const lng = roundNumber(this.lng_, 2, true);
                html = `<span style="min-width: 92px;">Latitude: ${lat}°</span><span>Longitude: ${lng}°</span>`;
                break;
            case 1:
                coords = formatLatLng(this.lat_, this.lng_).split(", ");
                html = `<span style="min-width: 55px;">${coords[0]}</span><span>${coords[1]}</span>`;
                break;
            case 2:
                coords = formatLatLng(this.lat_, this.lng_, "degreeminutes").split(", ");
                html = `<span style="min-width: 77px;">${coords[0]}</span><span>${coords[1]}</span>`;
                break;
        }

        this.getElement().innerHTML = html;
    }

    /**
     * Sets the coordinates to be displayed.
     * @param {number} lat - The latitude.
     * @param {number} lng - The longitude.
     */
    setCoordinates(lat, lng) {
        this.lat_ = lat;
        this.lng_ = lng;
        this.displayCoordinates_();
    }
}