Use Google Maps to plan your route and find out the distance in kilometers as well as the

Feeling a bit overwhelmed with the project I'm working on, but hoping for some guidance.

We're aiming to create a form where users input a starting point and an ending point, similar to the examples on Google Maps (http://code.google.com/apis/maps/documentation/examples/directions-advanced.html). This form should then output a map displaying the route, along with the total number of kilometers between the two points.

The challenge here is converting those kilometers into dollars.

While this seems feasible, there are additional variables to consider, such as the number of passengers (to be selected from a dropdown menu).

I'm unsure about merging all these components together. Should I create a custom form or utilize PHP? I'm feeling lost. Any suggestions on how to proceed?

For context: assume 1 km = $100, and each additional person beyond the first will add $100 to the total cost.

So, for example, 20 km with 2 persons would amount to $300.

Questions:

  1. Is it possible to embed variables within the Google code?
  2. What would be the ideal format for calling upon the form?

Thank you in advance for your assistance.

Google Code

var map;
var gdir;
var geocoder = null;
var addressMarker;

function initialize() {
  if (GBrowserIsCompatible()) {      
    map = new GMap2(document.getElementById("map_canvas"));
    gdir = new GDirections(map, document.getElementById("directions"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    setDirections("San Francisco", "Mountain View", "en_US");
  }
}

function setDirections(fromAddress, toAddress,

locale) { gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale }); }

function handleErrors(){
 if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
   alert("No corresponding geographic location could be found for

one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code); else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

 else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
   alert("The HTTP q parameter was either missing or had no value. For

geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

// else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS) <--- Doc bug... this is either not defined, or Doc is wrong // alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

 else if (gdir.getStatus().code == G_GEO_BAD_KEY)
   alert("The given key is either invalid or does not match the domain

for which it was given. \n Error code: " + gdir.getStatus().code);

 else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
   alert("A directions request could not be successfully parsed.\n

Error code: " + gdir.getStatus().code);

 else alert("An unknown error occurred.");
      }

function onGDirectionsLoad(){ // Use this function to access information about the latest load() // results.

  // e.g.
  // document.getElementById("getStatus").innerHTML

= gdir.getStatus().code; // and yada yada yada...

Answer №1

Here is the complete code snippet for you:

<html>
<head>
     <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <title>Distance Calculator</title> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <style type="text/css">
        #map_canvas { 
            height:500px;
        }
    </style>

    <script type="text/javascript">
    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;  

    function initialize() {
        var start = document.getElementById("start");
        var end = document.getElementById("end");
        var autocompletePickpUp = new google.maps.places.Autocomplete(start);
        var autocompleteDelivery = new google.maps.places.Autocomplete(end);
        var uk = new google.maps.LatLng(51.511035, -0.132315);
        var myOptions = {
            zoom:12,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: uk
        } 

        //testing


        directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setMap(map);
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        autocompletePickpUp.bindTo('bounds', map); 
        autocompleteDelivery.bindTo('bounds', map);   

    }

    function calcRoute() { 
        var startValue =start.value;
        var endValue = end.value;
        var distanceInput = document.getElementById("distanceKm");
        var distanceMl = document.getElementById("distanceMl");
        var price = document.getElementById("price");

        var request = {
            origin:startValue, 
            destination:endValue,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                distanceInput.value = response.routes[0].legs[0].distance.value / 1000; 
                distanceMl.value =  response.routes[0].legs[0].distance.value * 0.000621371;
                price.value = distanceMl.value * 2.50;

            }
        });         
    }

    </script>
</head>
<body onload="initialize()">
    <div>
        <p>
            <label for="start">Start: </label>
            <input type="text" name="start" id="start" />

            <label for="end">End: </label>
            <input type="text" name="end" id="end" />

            <input type="submit" value="Calculate Route" onclick="calcRoute()" /> 
        </p>
        <p>
            <label for="distanceInKm">Distance (km): </label>
            <input type="text" name="distanceKm" id="distanceKm" readonly="true" />
        </p>

        <p>
            <label for="distanceInMiles">Distance (ML): </label>
            <input type="text" name="distanceMl" id="distanceMl" readonly="true" />
        </p>

        <p>
            <label for="price">Price: </label>
            <input type="text" name="price" id="price" readonly="true" />
        </p>
    </div>
    <div id="map_canvas"></div>
</body>

Copy and paste this code into an HTML file to test it out. The functionality includes calculating the distance in kilometers, converting it to miles, and then determining a price in British Pounds.

I have tested it briefly, so there may be some errors, but it should give you a good starting point.

To calculate the total number of passengers, you can use the following form:

<div class="form-group">
   <label>Table</label>
    <select class="form-control required" name="kitchen_table" id="kitchen_table">
       <option value="" selected>Quantity</option>
        <option value="0">0</option>
        <option value="10">1</option>
        <option value="20">2</option>
        <option value="30">3</option>
        <option value="40">4</option>
        </select>
     </div>

 <div class="live_quote">
         <p>Your total is: <span id="total_quote"></span> </p>
 </div>

To display the total quantity selected, use the following JavaScript:

$('select').change(function(){
  var total = 0;

  $('select :selected').each(function() {
    total += Number($(this).val());
  });
$("#total_quote").html(total);

})

Once again, there might be some errors, but it will give you a clear idea and guidance on how to proceed.

Answer №2

If you're looking to retrieve the distance in kilometers within your onGDirectionsLoad() function, you can achieve this by using the following code snippet:

 gdir.getDistance().meters/1000 

Assuming you are familiar with the process of rounding numbers, you may multiply it by 100 and account for any additional passenger fees if necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

Ways to launch numerous URLs in express.js

I am currently developing a service similar to a URL shortener. While a typical URL shortener redirects the user to one page, my service needs to open multiple URLs simultaneously. When a user clicks on a link from my website, I want it to open multiple l ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

Using various hues for segmented lines on ChartJS

I am working with a time line chart type and I want to assign colors to each step between two dots based on the values in my dataset object. In my dataset data array, I have added a third item that will determine the color (if < 30 ==> green / >30 ==> red ...

Troubleshooting and Fixing AJAX Calls

When working with Asynchronous JavaScript, it is common to encounter issues where we are unsure of the posted request and received response. Is there a simple method for debugging AJAX requests? ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...

Whenever I try to import a function, I encounter the error message "no exported member."

I am facing an issue with my node/typescript application where I am attempting to import a function from another file. In order to export it, I utilized exports.coolFunc = coolFunc, and for importing, I used import {coolFunc} from '../controller/coolS ...

Run a PHP statement when a JavaScript condition evaluates to true

I am attempting to run a php statement if my javascript condition is true. Here is the code snippet that I have written: <input id="checkbox1" type="checkbox"> MSI<br></input> <script> $(document).ready(function(){ $(&apos ...

Ways to automatically close the external window upon logging out in Angular 12

I have successfully created an external window in my Angular application. Everything is working as expected, but I am facing an issue when trying to automatically close the external window upon user logout. Although I have written the code below and it wo ...

trigger a label click when a button is clicked

I am in need of assistance with simulating a label click when a button is clicked. I attempted to make the label the same size as the button so that when the button is clicked, it would check my checkbox. I then tried using JavaScript to simulate the label ...

Node.js refuses to launch - the dreaded error 404, signaling that it has mysteriously vanished

I am brand new to node.js, so please be patient with me as I learn. Currently, I am using the express framework and attempting to create a basic application that displays content as HTML. Below is the essentials of my app.js: var express = require(' ...

Updating a Nested Form to Modify an Object

There is an API that fetches an object with the following structure: { "objectAttributes": [ { "id": "1", "Name": "First", "Comment": "First" }, { "id": "2", "Name": "Second", "Comment": "Second" } ] ...

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

Error in Angular: Trying to access property 'setLng' of a null component variable

Just starting out with Angular and I've come across the error message Cannot read property 'setLng' of null. Can anyone help explain why this is happening? import { Component, OnInit, Input } from '@angular/core'; @Component({ ...

Incorporate a binary document into a JSPdf file

I am currently utilizing JsPDF to export HTML content into a downloadable PDF. Explore the following example which involves taking some HTML content and generating a downloaded PDF file using JsPdf import React from "react"; import { render } fro ...

Load custom JS with Google

I have integrated the Google Ajax API and now I need to load custom javascript that relies on the libraries loaded by the ajaxapi. What is the best way to accomplish this? ...

The Helper Text fails to display the error, and the error message does not appear when the login data is incorrect

Currently, I am facing an issue with displaying error messages within my helper text component while using Material UI. Despite successfully testing my backend code using Postman to identify errors, I am unable to see the error message under the button whe ...

Long-term responsibilities in Node.js

Currently, I have a node.js server that is communicating between a net socket and a python socket. The flow is such that when a user sends an asynchronous ajax request with data, the node server forwards it to Python, receives the processed data back, and ...