0

I'm trying to create a codepen which calculates the distance from point A to point B and C. Also let's say for argument's sake that fuel/gas costs £1 per mile. I'm trying to add up the total distance between all the points (based on user input) and then multiply it by the fuel price and display it to the user.

I'm trying to use the Google Distance Matrix API to achieve this.

I have obviously taken out my API key since you need to pay for it but it works.

The documentation is great but it the locations are hard coded and i'm not sure how to right the code so it takes the result and multiplies it by the fuel price.

I'm trying to make it something like this:

const locationA = document.getElementById = "locationA".value;
const locationB = document.getElementById = "locationB".value;
const locationC = document.getElementById = "locationC".value;

let totalDistance = locationA + locationB + locationC
let fuel price = 1

let totalPrice = fuelPrice * totalDistance 

document.write(totalPrice)
body{
  text-align: center;
}

p {
  color: #969696;
  font-style: italic;
  margin: 20px 0;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
  <title>Document</title>
</head>
<body>
  <h3>Fuel Price Est.</h3>
  <label>Location A</label>
  <br>
  <input type="text" placeholder="Street address, P.O. Box, Company Name..." id="locationA">
  <br>
  <label>Location B</label>
  <br>
  <input type="text" placeholder="Street address, P.O. Box, Company Name..." id="locationB">
    <br>
  <label>Location C</label>
  <br>
  <input type="text" placeholder="Street address, P.O. Box, Company Name..." id="locationC">
  <p>(Est based on £1 per mile basis)</p>
  
  <div id="result">
    
  </div>
      </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>
</html>
Connor
  • 351
  • 8
  • 23

2 Answers2

0

There are many issues with your code. For starters, you can't do a document.write like that. The browser is not a console.

The syntax for this is incorrect:

const locationA = document.getElementById = "locationA".value;

it should be:

const locationA = document.getElementById("locationA").value;

That will result in a STRING, not a number, so you can't do math with it. What if the value is "AAA"? and not something like "30" You need to validate the input, convert it to a number, then do the math.

You've got a ways to go before you can get this to work.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

This isn't all of it but it's most of it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
      integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
      crossorigin="anonymous"
    />

    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"
      integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
      integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
      crossorigin="anonymous"
    ></script>

    <title>Document</title>
  </head>
  <body>
<div class="container">
  <div class="row">
    <div class="jumbotron">
      <h1>Calculate the Distance Between two Addresses demo</h1>
    </div>

    <div class="col-md-6">
      <form id="distance_form">
        <div class="form-group"><label>Origin: </label> <input class="form-control" id="from_places" placeholder="Enter a location" />
          <input id="origin" name="origin" required="" type="hidden" /></div>

        <div class="form-group"><label>Destination: </label> <input class="form-control" id="to_places" placeholder="Enter a location" />
          <input id="destination" name="destination" required="" type="hidden" /></div>
        <input class="btn btn-primary" type="submit" value="Calculate" />
      </form>

      <div id="result">
        <ul class="list-group">
          <li class="list-group-item d-flex justify-content-between align-items-center" id="in_mile">Distance In Mile :</li>
          <li class="list-group-item d-flex justify-content-between align-items-center" id="in_kilo">Distance is Kilo:</li>
          <li class="list-group-item d-flex justify-content-between align-items-center" id="duration_text">IN TEXT:</li>
          <li class="list-group-item d-flex justify-content-between align-items-center" id="duration_value">IN MINUTES:</li>
          <li class="list-group-item d-flex justify-content-between align-items-center" id="from">FROM:</li>
          <li class="list-group-item d-flex justify-content-between align-items-center" id="to">TO:</li>
        </ul>
      </div>
    </div>
  </div>
</div>
    <script>
  $(function () {
    // add input listeners
    google.maps.event.addDomListener(window, "load", function () {
      var from_places = new google.maps.places.Autocomplete(
        document.getElementById("from_places")
      );
      var to_places = new google.maps.places.Autocomplete(
        document.getElementById("to_places")
      );

      google.maps.event.addListener(from_places, "place_changed", function () {
        var from_place = from_places.getPlace();
        var from_address = from_place.formatted_address;
        $("#origin").val(from_address);
      });

      google.maps.event.addListener(to_places, "place_changed", function () {
        var to_place = to_places.getPlace();
        var to_address = to_place.formatted_address;
        $("#destination").val(to_address);
      });
    });
    // calculate distance
    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 get on 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 kilom
          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);
        }
      }
    }
    // print results on submit the form
    $("#distance_form").submit(function (e) {
      e.preventDefault();
      calculateDistance();
    });
  });

    </script>

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY&libraries=places&language=en"></script>
  </body>
</html>
Connor
  • 351
  • 8
  • 23