Map Simple

by Wolf

HTML

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

CSS

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

JavaScript

function initMap() {
	var first = true;
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat:47.4528684119519, lng:8.561266277968343},
    zoom: 17
  });
 var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();
  var a = new google.maps.Marker({
    label: 'A'
  });
  var b = new google.maps.Marker({
    label: 'B'
  });
  
	map.addListener('click', e => {
    console.log(e.latLng.toJSON());
    if (first) {
      a.setPosition(e.latLng);
      a.setMap(map);
      directionsDisplay.setMap(null);
      b.setMap(null);
    } else {
    	b.setPosition(e.latLng);
      b.setMap(map);
      directionsService.route({
      	origin: a.getPosition(),
        destination: b.getPosition(),
        travelMode: 'WALKING'
      }, (response, status) => {
      	if (status === 'OK') {
        	directionsDisplay.setDirections(response);
          directionsDisplay.setMap(map);
        } else {
        	console.log('meh. :(  ' + status);
        }
      })
    }
    first = !first;
  });
}