Distance between markers

Distance between markers

Drag markers to see distance in meters.

<!DOCTYPE html>
<html>
  <head>
    <title>Distance between markers</title>
    <script src="https://maps.cercalia.com/maps/loader.js?key=YOUR_API_KEY&v=5&lang=en&theme=1976d2"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script>
      document.addEventListener('cercalia-ready', initMap);

      var map;
      var marker1, marker2;

      function calculateDistance() {
        var position1 = marker1.getPosition();
        var position2 = marker2.getPosition();
        var distance = cercalia.Util.distanceTo(position1, position2);
        var distanceKm = Number(distance / 1000).toFixed(2);
        var label1 = marker1.getLabel();
        var label2 = marker2.getLabel();
        label1.setText('Distance to Marker2: ' + distanceKm + 'km');
        label2.setText('Distance to Marker1: ' + distanceKm + 'km');
      }


      function initMap() {
        var map = new cercalia.Map({
          target: 'map',
          controls: []
        });

        marker1 = new cercalia.Marker({
          position: new cercalia.LonLat(2.165802217, 41.392919622),
          draggable: true,
          label: new cercalia.Label({
            text: 'Drag to start..'
          }),
          onDragEnd: calculateDistance
        });

        marker2 = new cercalia.Marker({
          position: new cercalia.LonLat(-2.541541, 42.15422),
          draggable: true,
          label: new cercalia.Label({
            text: 'Drag to start..'
          }),
          onDragEnd: calculateDistance
        });


        map.addMarkers([marker1, marker2]);
      }
    </script>
  </body>
</html>