dimanche 25 février 2018

if..else statement in Google Distance Matrix results

I'm using Google Distance Matrix API to calculate the driving distance + time from one point to another.

I would like to add if..elseif..else statements to the result of the distance search to vary the answers according to how big the distances (e.g. < or > 10 km) are but I'm a newbie to JS and can't seem to figure out where to stick the statements into my code. Any tips?

Here's my code:

$(function(){
   function calculateDistance(origin, destination) {
      var service = new google.maps.DistanceMatrixService();
      service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, callback);
    }

    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("We can't seem to find "
                            + origin + ". Are you sure you entered a valid postcode and place?");
        } else {
          var distance = response.rows[0].elements[0].distance;
          var duration = response.rows[0].elements[0].duration;
          var distance_value = distance.value;
          var distance_text = distance.text;
          var duration_value = duration.value;
          var duration_text = duration.text;
          var kilometer = distance_text.substring(0, distance_text.length - 3);
          $('#result').html("It is " + kilometer + " kilometer from " + origin + " to " + destination + " and it takes " + duration_text + " to drive.");
        }
      }
    }

    $('#distance_form').submit(function(e){
        event.preventDefault();
        var origin = $('#origin').val();
        var destination = $('#destination').val();
        var distance_text = calculateDistance(origin, destination);
    });

  });

Aucun commentaire:

Enregistrer un commentaire