how to store google map data in a mysql database - javascript

I am facing problem in storing data like distance,duration,route_info into my database mysql. I am coding using eclipse luna and connected with mysql database.my database structure are
Trip(trip_id,source_addr,dest_addr)
Route(route_id,trip_id,route_info,distance,duration)
how can i insert data into my tables,i am really expecting a help from the community. Thanks in advance.
<html>
<head>
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay; // The whole map rendering or displaying.
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = response.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" style="width: 200px" />
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>

Related

Remove KM on google map distance calculation using html and javascript

I basically want to remove KM next to distance number because I want to calculate fare price and I can't make any calculations. I hope the given example below its understandable and please find the snippet code for HTML and javascript.
Example
Usually, it writes like this: 5 km
and I want it to be like this: 5
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
// initialise the location of the map on Chichester in England (ref lat and lng)
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: { lat: 50.834697, lng: -0.773792 },
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('travelfrom'));
new google.maps.places.SearchBox(document.getElementById('travelto'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
directionsDisplay.setMap(map);
source = document.getElementById("travelfrom").value;
destination = document.getElementById("travelto").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.value;
var dvDistance = document.getElementById("dvDistance");
var price = document.getElementById("price");
duration = parseFloat(duration / 60).toFixed(2);
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Time:" + duration + " min";
price.innerHTML = distance * 2.00;
} else {
alert("Unable to find the distance via road.");
}
});
}
<div class="row">
<div class="col-md-12">
<div>
<div>
Travel From : <input id="travelfrom" type="text" name="name" value="Chichester, UK" />
To : <input id="travelto" type="text" name="name" value="Goodwood aerodrone, UK" />
<input type="button" value="Get Route" onclick="GetRoute()" />
</div>
<br />
<div>
<div id="dvDistance">
</div>
<br />
<div id="price">
</div>
<br />
<br />
</div>
</div>
<div id="dvMap" style="min-height:500px"></div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
The text property of distance is a string which can contain a units specifier.
If you want a number, use the value property of distance which is a number and is always in meters.
var distance = response.rows[0].elements[0].distance.value/1000;
code snippet:
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
// initialise the location of the map on Chichester in England (ref lat and lng)
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: {
lat: 50.834697,
lng: -0.773792
},
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addDomListener(window, 'load', function() {
new google.maps.places.SearchBox(document.getElementById('travelfrom'));
new google.maps.places.SearchBox(document.getElementById('travelto'));
directionsDisplay = new google.maps.DirectionsRenderer({
'draggable': true
});
});
function GetRoute() {
directionsDisplay.setMap(map);
source = document.getElementById("travelfrom").value;
destination = document.getElementById("travelto").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.value / 1000;
var duration = response.rows[0].elements[0].duration.value;
var dvDistance = document.getElementById("dvDistance");
var price = document.getElementById("price");
duration = parseFloat(duration / 60).toFixed(2);
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Time:" + duration + " min";
price.innerHTML = distance * 2.00;
} else {
alert("Unable to find the distance via road.");
}
});
}
html,
body {
height: 100%;
width: 100%;
}
<div class="row" style="height:100%;">
<div class="col-md-12" style="height:100%;">
<div style="height: 130px;">
<div>
Travel From : <input id="travelfrom" type="text" name="name" value="Chichester, UK" /> To : <input id="travelto" type="text" name="name" value="Goodwood aerodrone, UK" />
<input type="button" value="Get Route" onclick="GetRoute()" />
</div>
<br />
<div>
<div id="dvDistance">
</div>
<br />
<div id="price">
</div>
<br />
<br />
</div>
</div>
<div id="dvMap" style="height:65%;"></div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
How about just removing the "KM" form the string:
var distance = response.rows[0].elements[0].distance.text.toLowerCase().replace(" km", "");
If you want to make calculations with the distance, you should also change the variable's type to Number.
var distance = parseFloat(
response.rows[0].elements[0].distance.text.toLowerCase().replace(" km", "")
);

How do I get Google Maps Directions API to choose the correct Airport?

When I ask google for directions, both "MMU" and "MMU Airport" work fine, but when I use the API it keeps going to MLU airport... what gives?
Code:
var directionService = new google.maps.DirectionsService;
var geocoder = new google.maps.Geocoder;
directionService.route({
origin: $('#selAirport').val() + ' Airport',
destination: $('#selZIPZone').val(),
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
console.log(response, status);
...
dev-tools photo showing it received "MMU Airport" as the origin, but set the Start Address to MLU Airport instead
That looks like a data problem. The directions service/geocoder recognize Morristown Municipal Airport, but not MMU. I reported that through the Google Maps "report an error" (lower right hand corner of the map), not sure if it will be accepted.
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var directionService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionService.route({
origin: 'Morristown Airport',
destination: "Florham Park , NJ",
travelMode: google.maps.TravelMode.DRIVING
},
function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
console.log(response);
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
Taking into account your last comment it looks like you have an autocomplete of places library. In this case you can retrieve the place ID from the autocomplete element and pass it to directions service. This way you will be sure that directions service is working with an exact choice of the user.
Please look at this example and use autocomplete to search your route:
http://jsbin.com/xuyisem/edit?html,output
code snippet:
var directionsDisplay;
var directionsService;
var map;
var placeId1, placeId2;
function initialize() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true
});
var mapOptions = {
zoom:10,
center: new google.maps.LatLng(32.5101466,-92.0436835)
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
var inputFrom = document.getElementById('from');
var autocompleteFrom = new google.maps.places.Autocomplete(inputFrom, {});
autocompleteFrom.bindTo('bounds', map);
autocompleteFrom.addListener('place_changed', function() {
var place = autocompleteFrom.getPlace();
placeId1 = place.place_id;
});
var inputTo = document.getElementById('to');
var autocompleteTo = new google.maps.places.Autocomplete(inputTo, {});
autocompleteTo.bindTo('bounds', map);
autocompleteTo.addListener('place_changed', function() {
var place = autocompleteTo.getPlace();
placeId2 = place.place_id;
});
}
function calcRoute() {
if (!placeId1) {
alert("Please select origin");
return;
}
if (!placeId2) {
alert("Please select destination");
return;
}
var start = {
placeId: placeId1
};
var end = {
placeId: placeId2
};
var request = {
origin: start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives: false
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<input type="text" name="from" id="from" placeholder="Select origin" />
<input type="text" name="to" id="to" placeholder="Select destination" />
<input type="button" name="calcroute" value="Get route" onclick="calcRoute();return false;" />
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initialize"></script>

how can i get distance and duration for all travel modes like driving,transit,cycling,walking in my page,and storing the same in db

I only succeded in displaying and storing the data of a single travel mode but now i want to store the data like distance and duration from all travel modes,here is the code,what changes do i need to perform,thanks in advance
mapper.html
<html>
<head>
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var routeArr = [];
var directionsDisplay; // The whole map rendering or displaying.
var globalResponse;
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute()
{
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status){ // RouteService
if (status == google.maps.DirectionsStatus.OK)
{
globalResponse = response;
routeArr = [];
for(i=0;i<globalResponse.routes.length;i++)
{
routeArr.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
}
var s = 'Possible routes are: <br />';
for(i = 0; i < routeArr.length; ++i)
{
routeArr[i][0] = routeArr[i][0].trim();
routeArr[i][0] = routeArr[i][0].substring(0,routeArr[i][0].length-3)
routeArr[i][1] = routeArr[i][1].split(' ');
if(routeArr[i][1].length==2)
{
routeArr[i][1]=parseInt(routeArr[i][1][0]);
}
else
{
routeArr[i][1]=parseInt(routeArr[i][1][0])*60 + parseInt(routeArr[i][1][2]);
}
s += "Distance: " + routeArr[i][0] + ", " + "Duration: " + routeArr[i][1] + "<br />";
}
document.getElementById("dvDistance").innerHTML = s;
directionsDisplay.setDirections(response);
}
// Here's the AJAX request
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() { // here the function name that is designed to handle the response
if (httpRequest.readyState == 4 && httpRequest.status == 200) { //200 OK response code. // 4 is complete response received
alert(httpRequest.responseText);
}
};
httpRequest.open("POST", "mapdb.php", true); // here true means asynchronously server is called,i.e,without page reloading
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("source=" + source + "&destination=" + destination + "&sel=" + sel + "&i=" + i + "&routes=" + JSON.stringify(routeArr));
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status){
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
/*var distance = globalResponse.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = globalResponse.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var distance = globalResponse.routes[0].legs[0].distance.text;
var duration = globalResponse.routes[0].legs[0].duration.text;
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;//+ " "+typeof response.routes.length;*/
}else {
alert("Unable to find the distance via road.");
}
});
var sel = document.getElementById('modes').value; // which mode the user is preferring
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" style="width: 200px" />
Travel Mode:
<select id="modes">
<option value="driving" >Driving</option>
<option value="cycling">Cycling</option>
<option value="transit">Transit</option>
<option value="walking"selected>Walking</option>
</select>
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>
mapdb.php
<?php
if(isset($_POST['source'], $_POST['destination'], $_POST['sel'], $_POST['i']) && count($_POST['routes']))
{
$routes_array = json_decode($_POST['routes'], true);
// Create connection
$conn = new mysqli("localhost", "root", "", "testdb");
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$i = $_POST['i'];
$sel = $_POST['sel'];
$source = $_POST['source'];
$destination = $_POST['destination'];
$query = "INSERT INTO trip(source, destination, mode, num_routes) VALUES('{$source}', '{$destination}', '{$sel}', '{$i}')";
if($conn->query($query)){
$trip_id = $conn->insert_id;
foreach($routes_array as $route){
$distance = $route[0];
$duration = $route[1];
$query = "INSERT INTO route(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')"; //distance in km and durtion
$conn->query($query);
}
echo "Sumeet!!!Success";
}
else
{
echo "Something went wrong!!! Record couldn't be inserted";
}
// Close connection
$conn->close();
}
?>
Change the MODE to Walking , Transit, Bicycling in your request.First check the output using google directions APIs endpoint on your browser.
Walking and Bicycling results are not available for every pair of locations.
Appending the last part of your travelMode: google.maps.TravelMode."Change here".
enter link description here
If iteration(loop) is not possible repeat the code thrice.

when i press get route button i want my javascript variable to get stored in a database

I want my data fetched from google maps api to be inserted into my (mysql) database.i want the data like source_address,destination_address,distance,duration of all the alternative routes to be inserted into my mysql database in just a click of get_route function that i wrote.
<html>
<head>
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay; // The whole map rendering or displaying.
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = response.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" style="width: 200px" />
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>
You have to use AJAX for this. After getting all the details like source, destination, distance and duration, gather and package up all data using AJAX and send them asynchronously to a different page, for example saveDetails.php to save all data to your database table.
Here's the AJAX reference:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
So your JavaScript should be like this:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay; // The whole map rendering or displaying.
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = response.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
// Here's your AJAX request
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
};
httpRequest.open("POST", "saveDetails.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("source=" + source + "&destination=" + destination + "&distance=" + distance + "&duration=" + duration);
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
And on saveDetails.php page, process your data like this:
<?php
if(isset($_POST['source']) && isset($_POST['destination']) && isset($_POST['distance']) && isset($_POST['duration'])){
// do your database operations
}
?>
Edited:
As per your requirement,
i want to store the distance and duration of multiple alternative routes in the table...and i want my database to be trip(trip_id,source,destination) route(route_id.trip_id,distance,duration) one to many relationship between trip and route. trip_id being the foreign key
Here's the complete solution:
First of all, create two tables named trip and route. Their structures would be like this:
CREATE TABLE trip(
trip_id INT(11) NOT NULL AUTO_INCREMENT,
source VARCHAR(255) NOT NULL,
destination VARCHAR(255) NOT NULL,
PRIMARY KEY(trip_id)
);
CREATE TABLE route(
route_id INT(11) NOT NULL AUTO_INCREMENT,
trip_id INT(11) NOT NULL,
distance VARCHAR(50) NOT NULL,
duration VARCHAR(50) NOT NULL,
PRIMARY KEY(route_id),
FOREIGN KEY(trip_id) REFERENCES trip(trip_id)
);
And now comes to your HTML and JavaScript code,
<html>
<head>
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var routeArr = [];
var directionsDisplay; // The whole map rendering or displaying.
var globalResponse;
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute()
{
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.TRANSIT
};
directionsService.route(request, function (response, status){ // RouteService
if (status == google.maps.DirectionsStatus.OK){
/*for (var i = 0; i < response.routes.length; i++) {
var dr = new google.maps.DirectionsRenderer();
dr.setDirections(response);
// Tell the DirectionsRenderer which route to display
dr.setRouteIndex(i);
dr.setMap(map);
// Code ommited to display distance and duration
}*/
globalResponse = response;
routeArr = [];
for(i=0;i<globalResponse.routes.length;i++){
routeArr.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
}
var s = 'Possible routes are: <br />';
for(i = 0; i < routeArr.length; ++i){
s += "Distance: " + routeArr[i][0] + ", " + "Duration: " + routeArr[i][1] + "<br />";
}
document.getElementById("dvDistance").innerHTML = s;
directionsDisplay.setDirections(response);
}
// Here's the AJAX request
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() { // here the function name that is designed to handle the response
if (httpRequest.readyState == 4 && httpRequest.status == 200) { //200 OK response code. // 4 is complete response received
alert(httpRequest.responseText);
}
};
httpRequest.open("POST", "mapdb.php", true); // here true means asynchronously server is called,i.e,without page reloading
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("source=" + source + "&destination=" + destination + "&routes=" + JSON.stringify(routeArr));
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.TRANSIT,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status){
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
/*var distance = globalResponse.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = globalResponse.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var distance = globalResponse.routes[0].legs[0].distance.text;
var duration = globalResponse.routes[0].legs[0].duration.text;
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;//+ " "+typeof response.routes.length;*/
}else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" style="width: 200px" />
Travel Mode:
<select>
<option value="1" >Driving</option>
<option value="2">Cycling</option>
<option value="3">Transit</option>
<option value="4"selected>Walking</option>
</select>
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>
</html>
Finally, your mapdb.php page would be like this:
<?php
if(isset($_POST['source'], $_POST['destination']) && count($_POST['routes'])){
$routes_array = json_decode($_POST['routes'], true);
// Create connection
$conn = new mysqli("localhost", "root", "", "testdb");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$source = $_POST['source'];
$destination = $_POST['destination'];
$query = "INSERT INTO trip(source, destination) VALUES('{$source}', '{$destination}')";
if($conn->query($query)){
$trip_id = $conn->insert_id;
foreach($routes_array as $route){
$distance = $route[0];
$duration = $route[1];
$query = "INSERT INTO route(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";
$conn->query($query);
}
echo "success";
}else{
echo "Record couldn't be inserted";
}
// Close connection
$conn->close();
}
?>

Waypoints code in Google maps

I am using a html form to get inputs of 3 zip-codes (PortZip, ImporterZip, ExporterZip).
<form>
Calculation of OUT OF ROUTE DISTANCE.<br>
Enter 5 digit VALID US ZipCodes<br><br>
Port ZipCode:<br>
<input type="text" id="PortZip" value="31402">
<br><br>
Importer ZipCode:<br>
<input type="text" id="ImporterZip" value="30308">
<br><br>
Exporter ZipCode:<br>
<input type="text" id="ExporterZip" value="30901">
<br><br>
<input type="button" value="Calculate" onclick="calcRoute()" />
</form>
I want to plot the path bfrom PortZip to PortZip via ExporterZip. The code below-
function calcRoute() {
var start = document.getElementById('PortZip').value;
var end = document.getElementById('ImporterZip').value;
var waypts = document.getElementById('ExporterZip').value;
var request = {
origin:start,
destination:end,
waypoints:waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Is the waypoints formulation right? This code is not leading to any result. If I run the code without waypoints:waypts, it works. What's wrong with my code?
A Waypoint is a javascript anonymous object, the waypoints property of the directions request should be an array of waypoint objects (like you had in your last question on this). If you run that code you get a javascript error: Uncaught InvalidValueError: in property waypoints: not an Array
function calcRoute() {
var start = document.getElementById('PortZip').value;
var end = document.getElementById('ImporterZip').value;
var waypts = [{location:document.getElementById('ExporterZip').value}];;
var request = {
origin:start,
destination:end,
waypoints:waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
code snippet:
var map;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
function initialize() {
//CONVERT THE MAP DIV TO A FULLY-FUNCTIONAL GOOGLE MAP
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('PortZip').value;
var end = document.getElementById('ImporterZip').value;
var waypts = [{
location: document.getElementById('ExporterZip').value
}];;
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<form>Calculation of OUT OF ROUTE DISTANCE.
<br />Enter 5 digit VALID US ZipCodes
<br />
<br />Port ZipCode:
<br />
<input type="text" id="PortZip" value="31402" />
<br />
<br />Importer ZipCode:
<br>
<input type="text" id="ImporterZip" value="30308" />
<br />
<br />Exporter ZipCode:
<br />
<input type="text" id="ExporterZip" value="30901" />
<br />
<br />
<input type="button" value="Calculate" onclick="calcRoute()" />
</form>
<div id="map_canvas"></div>

Categories

Resources