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

Utilizing a mouse-over script for image popup alignment

I recently came across the mouse over script below on a website, and I must say it works really well and is very easy to use. The only issue I have with it is the placement of the image. Currently, the image follows the cursor as it moves. Question: Is th ...

Monitor modifications to the form as the user navigates away from the page or refreshes

Currently, I am working on a form that was created using Formik and React Hooks. I would greatly appreciate any suggestions on how to track changes made to the form when a user clicks the home button or refreshes/reloads the page. I attempted to use the b ...

Learning how to utilize getDerivedStateFromProps over componentWillReceiveProps in React

To address a deprecated error, I am looking to update my code from using componentWillReceiveProps to getDerivedStateFromProps. The component is being passed a date prop, and whenever this date changes, the getList function needs to be run with the new dat ...

Troubleshooting issues with the delete functionality in a NodeJS CRUD API

I've been struggling to implement the Delete functionality in my nodejs CRUD API for the past couple of days, but I just can't seem to get it right. As I'm still learning, there might be a small detail that I'm overlooking causing this ...

Oops! An issue occurred at ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 where a module cannot be located. The module in question is 'http'

I have been troubleshooting an issue with Next.js The error I am encountering => error - ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 Module not found: Can't resolve 'http' Import trace for req ...

Issue: The object identified as #<Object> does not contain the 'toUpperCase' method

I am currently encountering the error Object #<Object> has no method 'toUpperCase' right before the POST request is initiated. Any assistance you can provide would be greatly appreciated! Thank you in advance. function ajaxeo(url, data, me ...

What is the best way to continuously monitor MongoDB for updates and sync them with my user interface?

Looking to continuously monitor a user's notifications in MongoDB, updating them on specific actions and displaying updates on my React frontend without reloading every time the user logs in. I am currently utilizing Node and Mongoose models for datab ...

There is an issue with Nuxt 3 layers not functioning properly when trying to access a project page from a different

Is there a way to make a project function independently while still being accessible through layers and able to run smoothly? The current project structure is as follows: ...

Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide TEST: import { render, screen } from 'test-util'; import { Sideb ...

What is preventing me from deleting cookies on Express?

Whenever a new user is registered, the number of cookies just keeps increasing endlessly. userRoutes.js: const { registerUser, loginUser, registerVerify } = require("./userController"); const express=require('express') const router=ex ...

Denied running the inline script in Redocly

Experimenting with redoc-cli (https://github.com/Redocly/redoc/) in order to generate static documentation. Unfortunately, encountered some stumbling blocks due to errors related to the Content-Security-Policy, which seems to be blocking JavaScript code ex ...

Bootstrap Dropdown Functionality Malfunctioning

Here is a simple piece of HTML code that I have created: <!doctype html> <html> <head> <meta charset="utf-8"> <title>.:Home Page:. The Indian Sentinel</title> <link rel="stylesheet" href=" ...

A guide on loading theme JavaScript files in Next.js

I am planning to incorporate a theme from themeforest into Next.js Despite my attempts, I encountered issues with loading jquery core and certain plugins in Nextjs. import { useEffect } from "react" import { SessionProvider } from "next-aut ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...

Ensuring the accuracy of user input in JavaScript, even after fixing a mistake and submitting again, will not cause the code to exit the else clause

I am currently working on a coupon code field that needs to accept a specific set of coupon keys. Below is the code I have written for validation. If a user enters an invalid key at first, they receive an alert saying "Invalid Key." However, if they corr ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

Issue with a stationary directional light tracking the movement of a rotating object and/or changes in the camera perspective

I've been facing a challenge in implementing a day-night cycle with a directional light in an Earth model using custom shaders. Everything seems to work fine with the night and day maps, as well as the light, as long as I don't manipulate the cam ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...