I want learning how to make simply ruler (measurement) on Leaflet

I want create simply ruler based on example below:

enter image description here

I know many plugin about measurement in Leaflet, but for some reasons, I want make itself without plugin. I need advise and help for this.

This my function code:

var markersRulerGroup = L.layerGroup();
markersRulerGroup.addTo(map);

var tooltipRulerGroup = L.layerGroup();
tooltipRulerGroup.addTo(map);

var rulerIcon = L.divIcon({className: 'bi bi-dot text-ruler-map', iconSize: [0, 0], iconAnchor: [26, 36]});
var markerRuler;
var markersCount;
var tooltipRuler;

function measureDistance(){
  if ($('#measureDistanceCheckedState').is(":checked")) {
      $('#measureDistanceCheckedState').prop('checked', false);
      btnMeasureDistance.style.backgroundColor = '#ffffff';
      
      // markersRulerGroup.removeLayer(markerRuler);
      map.eachLayer(function(layer) {
          if(layer.options.alt === "markerRuler") layer.removeFrom(markersRulerGroup);
          if(layer.options.alt === "tooltipRuler") layer.removeFrom(tooltipRulerGroup);
      });
      
      map.off('click');
  }   else {
      $('#measureDistanceCheckedState').prop('checked', true);
      btnMeasureDistance.style.backgroundColor = '#dbdbdb';
      
      map.on('click', function(e){
      markerRuler = new L.marker(e.latlng, {alt: 'markerRuler', icon: rulerIcon});
      markersRulerGroup.addLayer(markerRuler);
      
      markersCount = markersRulerGroup.getLayers().length;
      
      tooltipRuler = new L.tooltip(e.latlng, {alt: 'tooltipRuler', permanent: true, direction:'bottom', offset:[1,6]})
      .setContent("THIS MARKER:" +markersCount);
      tooltipRulerGroup.addLayer(tooltipRuler);
      });
  };
};

Based on my function above, when i click on map, will adding marker like as below picture:

enter image description here

My problem actually is, I don’t know how to define marker[before] and marker[after]. This important for calculating distance and adding line between two markers. If I know to define marker[before] and marker[after], i expected my result next are below:

enter image description here