[GIS] Leaflet mouse move to get coordinate

javascriptleafletmouse positionmouse-cursor

I hope to be able to display the coordinates on the map when the mouse moves, not to use marker.
But my code can't run successfully.

This is my code:

<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml">

<link rel="stylesheet" href="https://leaflet.github.io/Leaflet.markercluster/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://leaflet.github.io/Leaflet.markercluster/dist/MarkerCluster.Default.css" />
<script src="https://leaflet.github.io/Leaflet.markercluster/dist/leaflet.markercluster-src.js"></script>

<div id="map" style="height: 100%; border: 1px solid #AAA;"></div>

<script>
    L.CursorHandler = L.Handler.extend({

        addHooks: function () {
            this._popup = new L.Popup();
            this._map.on('mouseover', this._open, this);
            this._map.on('mousemove', this._update, this);
            this._map.on('mouseout', this._close, this);
        },

        removeHooks: function () {
            this._map.off('mouseover', this._open, this);
            this._map.off('mousemove', this._update, this);
            this._map.off('mouseout', this._close, this);
        },

        _open: function (e) {
            this._update(e);
            this._popup.openOn(this._map);
        },

        _close: function () {
            this._map.closePopup(this._popup);
        },

        _update: function (e) {
            this._popup.setLatLng(e.latlng)
                .setContent(e.latlng.toString());
        }


    });

    L.Map.addInitHook('addHandler', 'cursor', L.CursorHandler);

    var map = new L.Map('leaflet', {
        center: [0, 0],
        zoom: 0,
        cursor: true,
        layers: [
            new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                'attribution': 'Map data © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            })
        ]
    });

    /*
    var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        osmAttrib = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        osm = L.tileLayer(osmUrl, { maxZoom: 20, attribution: osmAttrib });
    var map = L.map('map').setView([24.151687694799833, 120.64116954803465], 15).addLayer(osm);
    */

    $.getJSON("https://sta.ci.taiwan.gov.tw/STA_Rain/v1.0/Things?$expand=Locations&$select=name,properties&$count=true", function (data) {

        var markerGroup = L.featureGroup();
        data.value.forEach(function (itemData, itemInd) {
            var latLng = L.latLng(itemData.Locations[0].location.coordinates[1],
                itemData.Locations[0].location.coordinates[0]);
            var myMarker = L.marker(latLng).addTo(markerGroup);

            var popupContent = '<b>Name<b>: ' + itemData.name +
                '<br /></b>stationID: ' + itemData.properties.stationID +
                '<br /><b>latlng: ' + itemData.Locations[0].location.coordinates[1] +
                ',' + itemData.Locations[0].location.coordinates[0] +
                '<br /></b>Attribute: ' + itemData.properties.Attribute;

            map.addLayer(markers);

            myMarker.bindPopup(popupContent);

        });

        markerGroup.addTo(map);
        map.fitBounds(markerGroup.getBounds());

    });

</script>
</body>

Best Answer

This is another way of doing it by extending a leaflet control:

let Position = L.Control.extend({ 
        _container: null,
        options: {
          position: 'bottomleft'
        },

        onAdd: function (map) {
          var latlng = L.DomUtil.create('div', 'mouseposition');
          this._latlng = latlng;
          return latlng;
        },

        updateHTML: function(lat, lng) {
          var latlng = lat + " " + lng;
          //this._latlng.innerHTML = "Latitude: " + lat + "   Longitiude: " + lng;
          this._latlng.innerHTML = "LatLng: " + latlng;
        }
      });
      this.position = new Position();
      this.leafletMap.addControl(this.position);

Then add an event listener for mouse move:

this.leafletMap.addEventListener('mousemove', (event) => {
    let lat = Math.round(event.latlng.lat * 100000) / 100000;
    let lng = Math.round(event.latlng.lng * 100000) / 100000;
    this.position.updateHTML(lat, lng);
  }
});