2

I'm busy developing a web app. Below is code from Googles API that displays the directions between the two points which a user manually inputs. Google has a Distance Matrixs API which is calculated on static locations. My web app uses locations from users thus code from a static location won't help.

I want to know what is missing from my code to display my outcome on google maps like the image below.

This is what i want the outcome to kinda look like on the app - IMAGE This is what i want the outcome to kinda look like on the app - IMAGE

 function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      mapTypeControl: false,
      center: {lat: -25.7234, lng: 28.4222},
      zoom: 14
    });

    new AutocompleteDirectionsHandler(map);
  }

  function AutocompleteDirectionsHandler(map) {
    this.map = map;
    this.originPlaceId = null;
    this.destinationPlaceId = null;
    this.travelMode = 'DRIVING';
    var originInput = document.getElementById('origin-input');
    var destinationInput = document.getElementById('destination-input');
    var modeSelector = document.getElementById('mode-selector');
    this.directionsService = new google.maps.DirectionsService;
    this.directionsDisplay = new google.maps.DirectionsRenderer;
    this.directionsDisplay.setMap(map);

    var originAutocomplete = new google.maps.places.Autocomplete(
        originInput, {placeIdOnly: true});
    var destinationAutocomplete = new google.maps.places.Autocomplete(
        destinationInput, {placeIdOnly: true});

    this.setupClickListener('changemode-walking', 'WALKING');
    this.setupClickListener('changemode-transit', 'TRANSIT');
    this.setupClickListener('changemode-driving', 'DRIVING');

    this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
    this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
  }

  // Sets a listener on a radio button to change the filter type on Places
  // Autocomplete.
  AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
    var radioButton = document.getElementById(id);
    var me = this;
    radioButton.addEventListener('click', function() {
      me.travelMode = mode;
      me.route();
    });
  };

  AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
    var me = this;
    autocomplete.bindTo('bounds', this.map);
    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.place_id) {
        window.alert("Please select an option from the dropdown list.");
        return;
      }
      if (mode === 'ORIG') {
        me.originPlaceId = place.place_id;
      } else {
        me.destinationPlaceId = place.place_id;
      }
      me.route();
    });

  };

  AutocompleteDirectionsHandler.prototype.route = function() {
    if (!this.originPlaceId || !this.destinationPlaceId) {
      return;
    }
    var me = this;

    this.directionsService.route({
      origin: {'placeId': this.originPlaceId},
      destination: {'placeId': this.destinationPlaceId},
      travelMode: this.travelMode
    }, function(response, status) {
      if (status === 'OK') {
        me.directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  };
ClarkeFL
  • 131
  • 2
  • 13
  • 1
    1) Your question doesn't contain a question. 2) The code you provided doesn't allow to reproduce any part of what you described above as it is incomplete. 3) Please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) that allows to reproduce the problem, as a stackoverflow code snippet or a jsfiddle. 4) Reword your "question" to include what doesn't work and ask a clear question. – MrUpsidown Apr 30 '18 at 13:45
  • 1
    Possible duplicate of [Calculate distance between two points in google maps V3](https://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google-maps-v3) – Zannith Apr 30 '18 at 15:57
  • 1
    Possible duplicate of [How can i get the total distance in KM in my javascript](https://stackoverflow.com/questions/31680105/how-can-i-get-the-total-distance-in-km-in-my-javascript) – geocodezip May 01 '18 at 00:11
  • 1
    Possible duplicate of [Google Maps API: Total distance with waypoints](https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints) – geocodezip May 01 '18 at 00:15
  • No, I've already looked at those questions. I wanted to see if there was a solution to add to my code to allow the distance between the two points. I don't want to calculate the distance using Math nor using static locations. The below answer worked and is correct! – ClarkeFL May 01 '18 at 11:48

1 Answers1

1

The directions response includes both the distance and duration for each leg.

  me.directionsDisplay.setDirections(response);
  var center = response.routes[0].overview_path[Math.floor(response.routes[0].overview_path.length / 2)];
  infowindow.setPosition(center);
  infowindow.setContent(response.routes[0].legs[0].duration.text + "<br>" + response.routes[0].legs[0].distance.text);
  infowindow.open(me.map);

proof of concept fiddle

screenshot of resulting map

code snippet:

var infowindow;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    mapTypeControl: false,
    center: {
      lat: -25.7234,
      lng: 28.4222
    },
    zoom: 14
  });
  infowindow = new google.maps.InfoWindow();

  new AutocompleteDirectionsHandler(map);
}

function AutocompleteDirectionsHandler(map) {
  this.map = map;
  this.originPlaceId = null;
  this.destinationPlaceId = null;
  this.travelMode = 'DRIVING';
  var originInput = document.getElementById('origin-input');
  var destinationInput = document.getElementById('destination-input');
  var modeSelector = document.getElementById('mode-selector');
  this.directionsService = new google.maps.DirectionsService();
  this.directionsDisplay = new google.maps.DirectionsRenderer();
  this.directionsDisplay.setMap(map);

  var originAutocomplete = new google.maps.places.Autocomplete(
    originInput, {
      placeIdOnly: true
    });
  var destinationAutocomplete = new google.maps.places.Autocomplete(
    destinationInput, {
      placeIdOnly: true
    });

  this.setupClickListener('changemode-walking', 'WALKING');
  this.setupClickListener('changemode-transit', 'TRANSIT');
  this.setupClickListener('changemode-driving', 'DRIVING');

  this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
  this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}

// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
  var radioButton = document.getElementById(id);
  var me = this;
  radioButton.addEventListener('click', function() {
    me.travelMode = mode;
    me.route();
  });
};

AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
  var me = this;
  autocomplete.bindTo('bounds', this.map);
  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.place_id) {
      window.alert("Please select an option from the dropdown list.");
      return;
    }
    if (mode === 'ORIG') {
      me.originPlaceId = place.place_id;
    } else {
      me.destinationPlaceId = place.place_id;
    }
    me.route();
  });

};

AutocompleteDirectionsHandler.prototype.route = function() {
  if (!this.originPlaceId || !this.destinationPlaceId) {
    return;
  }
  var me = this;

  this.directionsService.route({
    origin: {
      'placeId': this.originPlaceId
    },
    destination: {
      'placeId': this.destinationPlaceId
    },
    travelMode: this.travelMode
  }, function(response, status) {
    if (status === 'OK') {
      me.directionsDisplay.setDirections(response);
      var center = response.routes[0].overview_path[Math.floor(response.routes[0].overview_path.length / 2)];
      infowindow.setPosition(center);
      infowindow.setContent(response.routes[0].legs[0].duration.text + "<br>" + response.routes[0].legs[0].distance.text);
      infowindow.open(me.map);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
};
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="origin-input" value="New York, NY" />
<input id="destination-input" value="Newark, NJ" />
<div id="mode-selector">
  <input id="changemode-walking" type="radio" value="WALKING" />
  <input id="changemode-transit" type="radio" value="TRANSIT" />
  <input id="changemode-driving" type="radio" value="DRIVING" checked="checked" />
</div>
<div id="total"></div>
<div id="map"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245