Skip to content

Instantly share code, notes, and snippets.

@jacmaes
Created February 14, 2020 14:41
Show Gist options
  • Save jacmaes/a96f98fcffac60f573046985fd38c6ba to your computer and use it in GitHub Desktop.
Save jacmaes/a96f98fcffac60f573046985fd38c6ba to your computer and use it in GitHub Desktop.
Google Maps distance #js
// From Kreativan's gist: https://gist.github.com/kreativan/0ea5ea16dce287c324b5494a57c20286
/**
* Need to include google maps api with initMap callback
* @function initMap
*
*/
function initMap() {
/* start - end addresses */
var start = 'Beograd';
var end = 'Pancevo';
/* or use lng */
var start = new google.maps.LatLng(44.795184, 20.444743);
var end = new google.maps.LatLng(43.236553, 21.592068);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [start],
destinations: [end],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC
}, callback);
function callback(response, status) {
console.log(response);
if (status == 'OK') {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration.text;
var km = distance.value / 1000;
console.log(distance.text);
console.log(distance.value);
console.log(duration);
console.log(km);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment