How to parse Distance Matrix in JS to only get the distance and the duration?

118 views Asked by At

I have been trying to only get the distance and duration using the Google Distance Matrix API.

I tried and built and modified as I logically could but nothing. I even slice the response because I did not succeed to parse it.

I have multiple approaches but let show two script use.

function calculateDistance() {
  var origin = $('#origin').val();
  var destination = $('#destination').val();
  var service = new google.maps.DistanceMatrixService();
  
  service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL, // Miles and feet.
    // unitSystem: google.maps.UnitSystem.metric, // Kilometers and meters.
    avoidHighways: false,
    avoidTolls: false
  }, callback);
}

// Get distance results.
function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    $('#result').html(err);
  } else {
    var origin = response.originAddresses[0];
    var destination = response.destinationAddresses[0];
    
    if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
      $('#result').html("Better use a plane. There are no roads between " + origin + " and " + destination);
    } else {
      var distance = response.rows[0].elements[0].distance;
      var duration = response.rows[0].elements[0].duration;
      
      console.log(response.rows[0].elements[0].distance);
      
      var distance_in_kilo = distance.value / 1000; // The kilometer.
      var distance_in_mile = distance.value / 1609.34; // The mile.
      var duration_text = duration.text;
      var duration_value = duration.value;
      
      $('#in_mile').text(distance_in_mile.toFixed(2));
      $('#in_kilo').text(distance_in_kilo.toFixed(2));
      $('#duration_text').text(duration_text);
      $('#duration_value').text(duration_value);
      $('#from').text(origin);
      $('#to').text(destination);
    }
  }
}

The second one:

<script>
// @ts-nocheck TODO remove when fixed

function initMap() {
  const bounds = new google.maps.LatLngBounds();
  const markersArray = google.maps.Marker = [];
  const map = new google.maps.Map(document.getElementById("map"), {
      center: {
        lat: 55.53,
        lng: 9.4
      },
      zoom: 10,
    });

  // Initialize services.
  const geocoder = new google.maps.Geocoder();
  const service = new google.maps.DistanceMatrixService();

  // Build request.
  const origin2 = "634 Pretorius street, Pretoria, South Africa";
  const destinationA = "263 luttig street, Pretoria, South Africa";
  const request = {
    origins: [origin2],
    destinations: [destinationA],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
  };

  // Put request on page.
  document.getElementById("request").innerText =
    JSON.stringify(request),

    // Get distance matrix response.
    service.getDistanceMatrix(request).then((response) => {
      // Put response.
      document.getElementById("response").innerHTML = JSON.stringify(response);
    });
}

function myDistance() {
  const x = document.getElementById("response").innerHTML;
  // const y = x.slice(43, 70);
  // JSON.parse(x);
  var y = x.rows[0].elements[0].distance.text;
  
  document.getElementById("distance").innerHTML = y;
}
</script>

I tried both script above. I want to only get the distance in km an the duration in minutes.

0

There are 0 answers