Remove KM on google map distance calculation using html and javascript - 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", "")
);

Related

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();
}
?>

how to store google map data in a mysql database

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>

google maps route in ASP

I need to get a route between 2 location in asp, since I want variables to improve my page navigation. I found an excellent method online that works wonders, but it activates a onclick function to work. I need to reload the page to obtain variables from my database.
The original version is this one:
<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;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var rome = new google.maps.LatLng(41.918357, 12.485029);
var mapOptions = {
zoom: 4,
center: rome
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").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.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "<strong>" + "Distanza:" + "</strong>" + " " + distance + "<br />";
dvDistance.innerHTML += "<strong>" + "Durata:" + "</strong>" + " " + duration;
} else {
alert("Impossibile trovare la distanza stradale");
}
});
}
</script>
it's activated by a onclick="GetRoute()" command in the request form, where I input my departure and destination in two fields. It will then display a map with the two locations with the route informations by its side.
Now, what I want, is to activate it with asp, since I need to access my sql.So the button type will become a submit without the onclick instruction, the page will reload, I'll get the data I need questioning my database and the gmaps script will run as usual, automatically triggering that GetRoute() function. I hope I've been clear, my english is a bit rusty, I could provide the work in progress address where I'm trying to fix this bad boy.
I'd like the whole script to be activated automatically after the page is reloaded, without the onclick command. So, basically, I want to get rid of the GetRoute() command. As long as I have the data needed by the script (txtSource and txtDestination), is there a way to obtain my map and route, once the page has reloaded?
You could do this with a slight modification to your existing code,
using the GetRoute function, without the onclick:
In the GetRoute function, set the source and destination variables to the request values:
function GetRoute()
{
source = "<%=Request("txtSource")%>";
destination = "<%=Request("txtDestination")%>";
if( source != "" && destination != "")
{
/*the rest of your code as is,except the following change:
comment out the following two lines, as we are already setting this with the request values
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
*/
}
}
And in the html, for the body tag, add <body onload="GetRoute();"> so that the function will be called after all the elements are loaded.
thank you for your help. I used your suggestions and the map appears, but without the route, so maybe I did something wrong in the code. I can confiirm that the two requests (txtsource and txtdestination) are passed correctly.
<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;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', 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()
{
source = "<%=Request.form("txtSource")%>";
destination = "<%=Request.form("txtDestination")%>";
if( source != "" && destination != "")
{
var rome = new google.maps.LatLng(41.918357, 12.485029);
var mapOptions = {
zoom: 4,
center: rome
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
/*source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").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.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "<strong>" + "Distanza:" + "</strong>" + " " + distance + "<br />";
dvDistance.innerHTML += "<strong>" + "Durata:" + "</strong>" + " " + duration;
} else {
alert("Impossibile trovare la distanza stradale");
}
});
}
}
</script>
Edit: I have divs in my HTML for the map and the route. That doesn't appear to be the problem, since the map shows, but I have no route on it
<div class="row">
<div class="col-md-6">
<div id="dvMap" style="height: 500px"></div>
</div>
<div class="col-md-6" style="height:500px; overflow-x:hidden; overflow-y:auto;">
<div id="dvPanel" ></div>
</div>

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>

google maps Autocomplete with building not working for routing

Here is a small application i'm writing to check a taxi fare in my country. everything is working well, including autocomplete. but if i type a building/mall name, the route is not showing. but if i type a road name, then the route is showing.
road name example in my city is : "jalan salemba raya" and "jalan medan merdeka timur"
mall name example : "Amaris Hotel Mangga Dua Square"
where is the problem ?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<title>Distance Calculator</title>
<script type="text/javascript" src="http://maps.google.co.id/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var city = new google.maps.LatLng(-6.17503,106.826935);
var myOptions = {
zoom:17,
mapTypeId: google.maps.MapTypeId.HYBRID,
center: city
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('start'));
var autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('end'));
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var distanceDisplay = document.getElementById("distance");
var timeDisplay = document.getElementById("time");
var tarifDisplay = document.getElementById("tarif");
var request = {
origin:start,
destination:end,
avoidTolls:true,
provideRouteAlternatives:true,
region:'co.id',
avoidHighways:true,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
jarak = Math.round((response.routes[0].legs[0].distance.value / 1000) * 100) /100;
distanceDisplay.value = jarak + ' km';
timeDisplay.value = Math.round((response.routes[0].legs[0].duration.value+1020) /60, 2) + ' menit';
tarifDisplay.value = 'Rp '+ Math.floor( (jarak*3240) + 3500) + ',-';
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div>
<p>
<label for="start">Start: </label>
<input type="text" name="start" id="start" placeholder="masukkan alamat"/>
<label for="end">End: </label>
<input type="text" name="end" id="end" placeholder="masukkan alamat"/>
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Jarak: </label>
<input type="text" name="distance" id="distance" readonly />
</p>
<p>
<label for="time">Estimasi waktu: </label>
<input type="text" name="time" id="time" readonly />
</p>
<p>
<label for="tarif">Tarif: </label>
<input type="text" name="tarif" id="tarif" readonly />
</p>
</div>
<div id="map_canvas" style="height:100%;width:100%"></div>
</body>
</html>
Since all you need is the distance and the route, you should use the coordinates provided by the autocomplete service. See the documentation for how to access the coordinates that result when the user selects a suggestion:
var startCoord, endCoord;
google.maps.event.addListener(autocomplete1, 'place_changed', function() {
var place = autocomplete1.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
startCoord = place.geometry.location
});
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
var place = autocomplete2.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
endCoord = place.geometry.location
});
Then use startCoord and endCoord in your directions request.
proof of concept fiddle
code snippet:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var startCoord, endCoord;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var city = new google.maps.LatLng(-6.17503, 106.826935);
var myOptions = {
zoom: 17,
mapTypeId: google.maps.MapTypeId.HYBRID,
center: city
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('start'));
var autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('end'));
google.maps.event.addListener(autocomplete1, 'place_changed', function() {
var place = autocomplete1.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
startCoord = place.geometry.location
});
google.maps.event.addListener(autocomplete2, 'place_changed', function() {
var place = autocomplete2.getPlace();
if (!place.geometry) {
// Inform the user that a place was not found and return.
return;
}
// place coordinate
endCoord = place.geometry.location
});
}
function calcRoute() {
var start, end;
if (!startCoord) {
start = document.getElementById("start").value;
} else {
start = startCoord;
}
if (!endCoord) {
end = document.getElementById("end").value;
} else {
end = endCoord;
}
var distanceDisplay = document.getElementById("distance");
var timeDisplay = document.getElementById("time");
var tarifDisplay = document.getElementById("tarif");
var request = {
origin: start,
destination: end,
avoidTolls: true,
provideRouteAlternatives: true,
region: 'co.id',
avoidHighways: true,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
jarak = Math.round((response.routes[0].legs[0].distance.value / 1000) * 100) / 100;
distanceDisplay.value = jarak + ' km';
timeDisplay.value = Math.round((response.routes[0].legs[0].duration.value + 1020) / 60, 2) + ' menit';
tarifDisplay.value = 'Rp ' + Math.floor((jarak * 3240) + 3500) + ',-';
} else {
alert("directions request failed, status=" + 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?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div>
<p>
<label for="start">Start:</label>
<input type="text" name="start" id="start" placeholder="masukkan alamat" value='Museum Taman Prasasti, South Petojo, Special Capital Region of Jakarta, Indonesia' />
<label for="end">End:</label>
<input type="text" name="end" id="end" placeholder="masukkan alamat" value='Mangga Dua Square' />
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
</p>
<p>
<label for="distance">Jarak:</label>
<input type="text" name="distance" id="distance" readonly />
</p>
<p>
<label for="time">Estimasi waktu:</label>
<input type="text" name="time" id="time" readonly />
</p>
<p>
<label for="tarif">Tarif:</label>
<input type="text" name="tarif" id="tarif" readonly />
</p>
</div>
<div id="map_canvas"></div>

Categories

Resources