JSFiddle - React, Tailwind, and code Playground

by Lawrence Ross

HTML

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&amp;ext=.js"></script>
<input id="heading" />
<input id="origin" />
<input id="destination" />
<div id="map"></div>

CSS

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

JavaScript

var marker1, marker2;
var poly, geodesicPoly;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: 34,
      lng: -40.605
    }
  });

  map.controls[google.maps.ControlPosition.TOP_CENTER].push(
    document.getElementById('info'));

  marker1 = new google.maps.Marker({
    map: map,
    draggable: true,
    position: {
      lat: 51.5073509, 
      lng: -0.12775829999998223
    }
  });

  marker2 = new google.maps.Marker({
    map: map,
    draggable: true,
    position: {
      lat: 25.7616798, 
      lng: -80.1917902
    }
  });

  var bounds = new google.maps.LatLngBounds();
  bounds.extend(marker1.getPosition());
  bounds.extend(marker2.getPosition())
  map.fitBounds(bounds);


  google.maps.event.addListener(marker1, 'position_changed', update);
  google.maps.event.addListener(marker2, 'position_changed', update);

  poly = new google.maps.Polyline({
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 3,
    map: map,
  });

  /*geodesicPoly = new google.maps.Polyline({
    strokeColor: '#CC0099',
    strokeOpacity: 1.0,
    strokeWeight: 3,
    geodesic: true,
    map: map
  });*/

  update();
}

function update() {
  var path = [marker1.getPosition(), marker2.getPosition()];
  poly.setPath(path);
  var heading = google.maps.geometry.spherical.computeHeading(path[0], path[1]);
  document.getElementById('heading').value = heading;
  document.getElementById('origin').value = path[0].toString();
  document.getElementById('destination').value = path[1].toString();
}
google.maps.event.addDomListener(window, "load", initMap);