Inserting a total cost for kilometers driven

Hi,

I am new to this site and I have been modifying the following code to have it in the french language. That in itself works fine but I need to add a field where the distance multiplied with a fixed cost could show up after the Distance field. I’m sure this can be done but when I modify it to include a totalCost variable and add other lines to take into consideration this variable, I get a 500 error.

Below is the code.

Any help will be appreciated.

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAwk8Uo9ZkiYLo0bvznt5qbxS0fmsgnMxnrcWKglYCnXntU3LFdxT1T4fzWClpC8GEnLS-QqpemIG3fg" type="text/javascript"></script>
    <script type="text/javascript">
    var geocoder, location1, location2, gDir;
    function initialize() {
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
        GEvent.addListener(gDir, "load", function() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
            document.getElementById('results').innerHTML = '<strong>Adresse 1: </strong>' + location1.address + ' <br /><strong>Adresse 2: </strong>' + location2.address + ' <br /><strong>Distance: </strong><!' + drivingDistanceMiles + ' miles> ' + drivingDistanceKilometers + ' kilometres ';
        });
    }

    function showLocation() {
        geocoder.getLocations(document.forms[0].address1.value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Désolé! Nous ne sommes pas en mesure d’activer le Geocode de la première adresse");
            }
            else
            {
                location1 = { address: response.Placemark[0].address};
                geocoder.getLocations(document.forms[0].address2.value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Désolé! Nous ne sommes pas en mesure d’activer le Geocode de la seconde adresse ");
                    }
                    else
                    {
                    location2= { address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}
</script>

</head>

<body onload="initialize()">
    <form action="#" onsubmit="showLocation(); return false;">
        <p>
            <input type="text" name="address1" value="Adresse 1" />
            <input type="text" name="address2" value="Adresse 2" />
            <input type="submit" value="Rechercher"/>
        </p>
    </form>
    <p id="results"></p>
</body>

</html>```

I don’t see any code?

if you edit/update your question, leave a reply so i get a notification. take the following steps to ensure your code visible:

select your code and press ctrl + k (or cmd + k if you use a mac)

if this instructions are unclear, you can also insert 3 backticks before and after your code, like so:

```
<p>visible</p>
```

the backtick is located above the tab key on your keyboard

Hey Stetim,

Thanks for the prompt response. Here is the code (took a few tries to understand how this works).

    <script type="text/javascript">
    var geocoder, location1, location2, gDir;
    function initialize() {
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
        GEvent.addListener(gDir, "load", function() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
            var  totalCost = gDir.getDistance().meters * .46;
            document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' <br /><strong>Address 2: </strong>' + location2.address + ' <br /><strong>Distance: </strong><!' + drivingDistanceMiles + ' miles> ' + drivingDistanceKilometers + ' kilometres ' + <strong>Total Cost:</strong>< + var totalCost  + ' Cost '>;
        });
    }

    function showLocation() {
        geocoder.getLocations(document.forms[0].address1.value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Sorry! We are not able to activate the Geocode for this first address.");
            }
            else
            {
                location1 = { address: response.Placemark[0].address};
                geocoder.getLocations(document.forms[0].address2.value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Sorry! We are not able to activate the Geocode for this second address.");
                    }
                    else
                    {
                    location2= { address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}
</script>

</head>

<body onload="initialize()">
    <form action="#" onsubmit="showLocation(); return false;">
        <p>
            <input type="text" name="address1" value="Address 1" />
            <input type="text" name="address2" value="Address 2" />
            <input type="submit" value="Search"/>
        </p>
    </form>
    <p id="results"></p>
</body>

</html>

This isn’t part of the ‘Introductions to Functions in JS’ section.

@stetim94 please recategorize.

oh wow, complex code, the moment i put in jsbin it threw errors, the biggest problem seemed to be in line 8, this bit:

+ <strong>Total Cost:</strong>< + var totalCost  + ' Cost '>;

some missing and misplaced ', changed it to:

'<strong>Total Cost:</strong><' + totalCost  + ' Cost>';

which seems to make more sense. updated version of your code

I moved it to corner bar. After a few tries (more bad gateway errors)

1 Like

Hey Stetim and Jibblyj

Please accept my apologies for the misplaced request as I am new to this forum

I inserted your changes but I still get an internal server 500 error as you have probably noticed. If I remove the
“var totalCost = gDir.getDistance().meters * .46;” and the "+ Total Cost:<’ + totalCost + ’ Cost >’ " the app works well but it is incomplete for my need. I want to see a new box that would contain the result of multiplying the Distance by a fixed amount and I am just not sure what I am doing wrong for this to happen.

Thanks for any and all help.

1 Like

But you can just append such a box in the same way you insert other elements in to the page with js? The problem with the fact if i had to write that code, is that i first have to go through your code, to understand it all, which is soo time consuming

Stetim,

I was able to fix the issue at hand as per the attached image. However now I am running into a NaN problem (bottom of image) where I believe it has to do with the calculation of the Total Cost Per KM. I’ve include the whole code that I am running. Not sure how to go about coding this even though I searched the site and the web.

<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Calculate driving distance with Google Maps API</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAwk8Uo9ZkiYLo0bvznt5qbxS0fmsgnMxnrcWKglYCnXntU3LFdxT1T4fzWClpC8GEnLS-QqpemIG3fg" type="text/javascript"></script>
    <script type="text/javascript">
    var geocoder, location1, location2, gDir;
    function initialize() {
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
     GEvent.addListener(gDir, "load", function() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
           var drivingCostPerKm = gDir.getDistance().meters * (drivingCostPerKm);
                  document.getElementById('results').innerHTML = '<strong>Adresse 1: </strong>' + location1.address + ' <br /><strong>Adresse 2: </strong>' + location2.address + ' <br /><strong>Distance: </strong><!' + drivingDistanceMiles + ' miles> ' + drivingDistanceKilometers + ' kilometres ' + ' <br /><strong>Coût total pour frais de déplacement: </strong>' + drivingDistanceKilometers * (drivingCostPerKm) + ' dollars ';
        });
    }

    function showLocation() {
        geocoder.getLocations(document.forms[0].address1.value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Sorry! We are not able to activate the Geocode for this first address.");
            }
            else
            {
                location1 = { address: response.Placemark[0].address};
                geocoder.getLocations(document.forms[0].address2.value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Sorry! We are not able to activate the Geocode for this second address.");
                    }
                    else
                    {
                    location2= { address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}
</script>

</head>

<body onload="initialize()">
    <form action="#" onsubmit="showLocation(); return false;">
        <p>
            <input type="text" name="address1" value="Address 1" />
            <input type="text" name="address2" value="Address 2" />
<br /><br /><input type="text" name=" drivingCostPerKm " id="Cost per km" />
            <br /><br /><input type="submit" value="Search"/>
        </p>
    </form>
    <p id="results"></p>
</body>

</html>

I like to debug with alerts, i put your code here, as you can see, drivingCostPerKm isNaN, i would take a close look at where you define this.

The problem seems to be here:

var drivingCostPerKm = gDir.getDistance().meters * (drivingCostPerKm);

here you define drivingCostPerKm, which equals to the distance times drivingCostPerKm (which is the variable you declare, that is a bit of a problem)

What I am trying to achieve is to not hard code an amount because it may change. I need to input a variable that will be inserted on the form and multiplied by the distance to give me the total cost. That is why there is a new empty field in my code to take into consideration the amount and then do its calculating thereafter.

Can’t you simply do something like this, to get the value of the field. You do understand what is wrong with the declaration of that line i pointed out?

Morning Stetim,

To be very honest I am not very proficient at programming and am in fact searching for snippets of code that I tend to group together and come up with certain results. So far, what I have shown you is very close to what I need. So to respond to your question, I understand that I have a coding error but I am not sure how to go about it to correct it nor where (with the code you are suggesting) to insert the answer you have provided. However I will “play” with it to see the results. Eventually I will get it but it may take some time howbeit, your help will shorten my trial and error methodology.

I thank you for your understanding and assistance.

I used id to get the value out of the form, as you can see here, but i simple do not understand it, why do you already call the initialize function on body load? I could understand, but there you already called your drivingcost, while you don’t know this value

Stetim,

Are you talking about the

? If so, in my understanding, this is to show a field box where I need to input the cost per km so that it is taken into consideration when calculating the total cost of kms driven. I’ve inserted a modified code ensuring the the third field contains the description of what is required.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Calculate driving distance with Google Maps API</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAwk8Uo9ZkiYLo0bvznt5qbxS0fmsgnMxnrcWKglYCnXntU3LFdxT1T4fzWClpC8GEnLS-QqpemIG3fg" type="text/javascript"></script>
    <script type="text/javascript">
    var geocoder, location1, location2, gDir;
    function initialize() {
        geocoder = new GClientGeocoder();
        gDir = new GDirections();
     GEvent.addListener(gDir, "load", function() {
            var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
            var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
           var drivingCostPerKm = gDir.getDistance().meters * (drivingCostPerKm);
                  document.getElementById('results').innerHTML = '<strong>Adresse 1: </strong>' + location1.address + ' <br /><strong>Adresse 2: </strong>' + location2.address + ' <br /><strong>Distance: </strong><!' + drivingDistanceMiles + ' miles> ' + drivingDistanceKilometers + ' kilometres ' + ' <br /><strong>Coût total pour frais de déplacement: </strong>' + drivingDistanceKilometers * (drivingCostPerKm) + ' dollars ';
        });
    }

    function showLocation() {
        geocoder.getLocations(document.forms[0].address1.value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Sorry! We are not able to activate the Geocode for this first address.");
            }
            else
            {
                location1 = { address: response.Placemark[0].address};
                geocoder.getLocations(document.forms[0].address2.value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Sorry! We are not able to activate the Geocode for this second address.");
                    }
                    else
                    {
                    location2= { address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}
</script>
</head>

<body onload="initialize()">
    <form action="#" onsubmit="showLocation(); return false;">
        <p>
            <input type="text" name="address1" value="Address 1" />
            <input type="text" name="address2" value="Address 2" />
<br /><br /><input type="text" name="Cost per km" value="Cost per km" />
            <br /><br /><input type="submit" value="Search"/>
        </p>
    </form>
    <p id="results"></p>
</body>

</html>

We are not on the same page, let’s start with this:

var drivingCostPerKm = gDir.getDistance().meters * (drivingCostPerKm);

you declare a variable, which is equal to a distance in meters times the variable you are declaring, that is just wrong. Plus, you don’t know what the drivingcostperkm is, you want to get this value from the user. You don’t get the drivingcostperkm from the user anywhere so far i can tell.

Your result is called in initialize function, why? why not in showlocation function? i made you thing which will extract the users driving cost (click here), since this is user input, i would use isNaN to check if it is a number. You stitched things together from the internet, but i do not think you understand what you have done in this process.

Here is the problem: i am helping you, but i get the feeling you do not understand this code enough, or am i wrong?

I can remove this line of code without a hiccup as I get the results as long as I hard code the driving cost per km. You are right in stating that I don’t fully understand the code and please accept my apologies for this as I know that you are going above and beyond to help me out.

I have removed the variable in my code and I get the results by doing the following in the line document.getElementById…

Coût total pour frais de déplacement: ’ + drivingDistanceKilometers * 0.46 + ’ dollars ';

Now from this, how can I insert the code you are proposing so that I may have a user input of the drivingcostperkm, it may calculate the total driving cost?

The problem i am facing because you do not fully understand the code is that it is really hard to make suggestion, the forum is to help, not for me to write your program, see the dilemma?

Well, if you opened the link i provided you, and you press run with js, you will see that i wrote some code to fetch the userinput, i will leave it to you to figure out how to get this userinput to show in the result

Thanks a lot Stetim. It is very much appreciated.

You’re welcome, you think you are going to manage? I will help you, but i hope you understand i draw a line somewhere