Storing Google Maps V3 distance calculations in a MySQL database: A step-by-step guide

(and please forgive me for asking such a basic question)

My MySQL database contains location information, and I have a PHP script that allows users to add new locations to the database. After adding a new location, I want to immediately calculate the distances between this location and a selected group of existing locations in the database using a Google Maps directions request, and then save these distances in the database.

I know how to retrieve the subset of locations using PHP and fetch distance data with JavaScript from Google Maps. However, I'm unsure about how to transfer these JavaScript variables to my database. What is the most effective way to store a collection of JavaScript variables as individual entries in a MySQL database?

Appreciate your assistance!

Carl

Answer №1

If you've successfully stored the distances in your JavaScript variables, you can then use an XmlHttpRequest to transmit them to your server where a PHP script will handle inserting them into the database. Here's an example of how you could achieve this:

JavaScript:

function saveDistance(pointA, pointB, distance) {
  var xhr = new XmlHttpRequest();
  xhr.open("POST", "/savedistance.php", true);
  xhr.send("pointA=" + pointA + "&pointB=" + pointB + "&distance=" + distance);
}

PHP:

$pointA = $_POST['pointA'];
$pointB = $_POST['pointB'];
$distance = $_POST['distance'];
mysqli_query("INSERT INTO distances VALUES ($pointA, $pointB, $distance)");

Answer №2

During a recent project, I encountered a similar issue that required me to navigate between two points A and B. For assistance with this, you may find the following link helpful:

If you are dealing with a specific number of points, consider utilizing the code snippet below:

editroutes = JSON.parse(editroutes);
origin = editroutes.ag.origin;
destination = editroutes.ag.destination;
var ag = editroutes.ag.waypoints;

for(i=0;i<ag.length;i++){
    if(typeof ag[i].location == 'object'){
        waypoints.push({location:new google.maps.LatLng(ag[i].location.Ia, ag[i].location.Ja),stopover:ag[i].stopover});
    }else if(typeof ag[i].location == 'string'){
        waypoints.push({location:ag[i].location,stopover:ag[i].stopover});
    }
}

avoidHighways =  editroutes.ag.avoidHighways;
avoidTolls = editroutes.ag.avoidTolls;
var request = {
       origin: origin,
       destination: destination,
       waypoints: waypoints,
       travelMode: google.maps.DirectionsTravelMode.DRIVING,
       optimizeWaypoints: false,
       avoidHighways: avoidHighways,
       avoidTolls: avoidTolls
};
directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) { 
        directionsDisplay.setDirections(response);
    }
});

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

Increase value continuously when button is pressed down using Material UI

I am looking for a way to continuously increment a value while holding down a button. I have already managed to make it increment on click, but now I want to keep it increasing as long as the button is held down. How can this be achieved using material u ...

Unable to retrieve nested element from its parent

I am facing an issue with accessing a child element's method from the parent element using ref='menu'. When I try to call $refs.menu.show in a button element within the Vue app, it works fine. However, when I try to do the same in a photo el ...

Guide to center align fields in Ionic and Angular

I am working on creating a login screen that resembles the image provided. I have managed to set the background image, input fields, and buttons successfully. However, I am encountering a few issues: The width of my input field is taking up the entire spa ...

Steps to convert a combined object data types sent via POST into an integer:

I have a mixed data types that have been POSTed to an API. I am looking to use parseInt() on certain data elements (Price, vat, status, company_id). When attempting to POST the form, I receive an error: POST https://api.factarni.tn/article/create 420 Furt ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

Navigating through a Single Page Application (SPA) can be achieved without

Can the CSS (Level 4) @document rule handle URLs that have the # symbol or include query parameters? For those who are not familiar with this topic Currently, only Firefox supports this feature with the @-moz-document prefix. If other browsers start supp ...

Unable to execute event.target.blur() function as expected

I am facing an issue with my Bootstrap buttons setup. Here is an example: <button :disabled="page === lastPage" type="button" class="btn btn-default" @click="getPage(lastPage)"> <span class="glyphicon glyphicon-forward"></span> </ ...

Javascript coding for monitoring health status using a three.js health bar

After updating to version r127, my health bar stopped working. I'm not sure what changes I need to make to get it working again. There seems to be an error with the shader in this version. Here is the code: Code: import * as THREE from './thre ...

Display upon hovering, conceal with a button located within a popup container

There seems to be an issue with the code below. Even though it works perfectly in jsfiddle, it breaks in my Chrome and other browsers right after displaying the ".popup" div. Can anyone point out what I might be doing wrong? I found similar code on this si ...

Experiencing AJAX errors 403 and 404 despite successful implementation in other instances

I am facing a perplexing issue with my code that is causing a 403 error when attempting to delete a row. The strange thing is, the code works perfectly on another website I created. The concept is quite simple - attaching an event listener to a button trig ...

Javascript variable capturing only the initial word from a string

Currently, I am working on a simple JavaScript function but my brain seems to be in a fog right now. Any assistance would be greatly appreciated as I suspect there might be a syntax error... The issue I am encountering involves a select value that contain ...

Vue: Utilizing computed properties to monitor changes in offsetHeight of elements

I am working on a component that requires an array of 50 objects to be passed as a prop. <template> <div v-for="(item,index) in items" ref="items" :key="index"gt; // </div> </template> props: ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

The most efficient method to generate output containing every possible combination of a large dataset

Being new to SQL, I have a query regarding handling a table with 90 columns and 200 rows. Is there a more efficient way to write a query that can easily select and fetch all combinations of data? For example, fetching data from row 34 and column 78, row ...

The React axios request triggers the UseEffect cleanup function to terminate all subscriptions and asynchronous tasks

I'm currently retrieving data from my API using axios, but the requests are not inside a useEffect function. In fact, I haven't used useEffect at all. Here's a snippet of my code: JSX: <form onSubmit={onSubmitLogin}> <div c ...

What is the best way to apply conditional hovering in styled components?

Is there a way to customize the hover effect of a component based on specific props? I want the background to change when hovering over it if certain props are set, but do nothing if different props are specified. export const Container = styled.div` ...

Ways to extract specific file types and content from a directory using Node.js

Currently, I am working on a Node.js application on my Windows machine to extract specific content from XML or HTML files. Unfortunately, some Npm packages seem to only work on Apple or Linux machines, causing limitations for me. In order to access the nec ...

Error #1442 - Unable to modify table 'passenger' within stored trigger as it is currently being accessed by the statement that called this stored function/trigger

Unable to resolve the issue Code CREATE TRIGGER `insertDetails` AFTER INSERT ON `passenger` FOR EACH ROW UPDATE passenger INNER JOIN trains ON (trains.train_no = passenger.train_no) SET passenger.train_name = trains.train_name, passenger.startPlace = ...

Turning away swiftly from a popover triggered by hovering does not automatically conceal the popover

When utilizing hover-triggered popovers for specific highlighted rows within a table, I noticed an issue. If you scroll away quickly using the mouse wheel, the popover remains visible for an extra second even though you are no longer hovering over the targ ...

Is it possible to use a variable from a popup window's JavaScript to call a jQuery function in the parent window?

Is there a way to use JavaScript in a popup window to call a function from the parent window that contains jQuery? Are there any straightforward examples available for reference? ...