google maps route in ASP - javascript

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>

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

Google Map doesn't loads properly in ligh box pop up

I have two textbox in which we can enter locations & on button click route between two points shows in the map. Problem is on page it shows properly but when I use lighbox popup then map only shows grey color like below image. For pop up box I have used asp.net control modalpopupextender.
JS Code.
<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() {
debugger;
var mumbai = new google.maps.LatLng(18.9750, 72.8258);
var mapOptions = {
zoom: 7,
center: mumbai
};
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 distance2 = response.rows[0].elements[0].distance.text; /*used for ID firstNumber*/
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
var firstNumber = document.getElementById("firstNumber");
var dvDuration = document.getElementById("dvDuration");
var dvDurationC = document.getElementById("dvDurationC")
dvDistance.innerHTML = "";
dvDistance.value = parseFloat(distance);
firstNumber.innerHTML = distance2 /*used for ID firstNumber*/
dvDuration.innerHTML = duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
Try making these two changes:
Remove the display property and set visibility: hidden on #map.
Move #map to a place where the space it inhabits won’t be noticed. Right before is probably a good choice.
Refer to this tutorial.

How to find out whether traffic information is available in the requested area?

I'm using Google API V3, and JavaScript and want to calculate the delay to get from one point to another that is caused by the traffic.
So, I made two requests (also see code below): One with durationInTraffic = true and one with durationInTraffic = false Strangely enough, both return the same values (I tested several bigger areas like Munich, Berlin, London, Sidney). Now I wonder whether my code is wrong or there are simply no traffic data available in the requested area.
function getRoute(){
var directionsService = new google.maps.DirectionsService();
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var startValue=document.getElementById('start').value;
var zielValue=document.getElementById('ziel').value;
var stundeValue=document.getElementById('stunde').value;
var minuteValue=document.getElementById('minute').value;
var tagValue=document.getElementById('tag').value;
var monatValue=document.getElementById('monat').value;
var jahrValue=document.getElementById('jahr').value;
//departure time in Epoch time
var abfahrtsZeitValue=monatValue+"/"+tagValue+"/"+jahrValue+" "+stundeValue+":"+minuteValue;
var request_withTraffic = {
origin: startValue,
destination: zielValue,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
transitOptions: {
departureTime: new Date(abfahrtsZeitValue)
},
durationInTraffic: true
};
var request_withoutTraffic = {
origin: startValue,
destination: zielValue,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
transitOptions: {
departureTime: new Date(abfahrtsZeitValue)
},
durationInTraffic: false
};
directionsService.route(request_withTraffic, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the duration:
document.getElementById('durationWithTraffic').innerHTML="Dauer mit Vekehr: ";
document.getElementById('durationWithTraffic').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
}
});
directionsService.route(request_withoutTraffic, function(response, status) {
if (status == google.maps.DirectionsStatus.OK)
{
document.getElementById('durationWithoutTraffic').innerHTML="Dauer ohne Verkehr: ";
document.getElementById('durationWithoutTraffic').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
}
});
}

Getting current location in google map and pass it to a variable in javascript

I want to display a direction in google map from current location to a known location. my code is shown below:
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var bne = new google.maps.LatLng(-27.572832, 153.065247);
var mapOptions = {
zoom:7,
center: bne
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
navigator.geolocation.getCurrentPosition(
function (pos) {
var start = new google.maps.LatLng(pos.coords.latitiude,
pos.coords.longitude);
var end = 'sunnybank,brisbane';
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
},
function (err) {
alert('ERROR(' + err.code + '): ' + err.message);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
It seems that navigator.geolocation.getCurrentPosition() doesn't work for me, is there other ways to retrieve current location and pass it to start variable?
Per the documentation, the getCurrentPosition function passes a Position object to its callback function (it is asynchronous so can't return anything), which is not a google.maps.LatLng object (but contains the information required to create one).
function calcRoute() {
navigator.geolocation.getCurrentPosition(function(pos) {
var start = new google.maps.LatLng(pos.coords.latitiude,
pos.coords.longitude);
var end = 'sunnybank,brisbane';
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else alert("Directions request failed: "+status);
});
}, function(err) {
alert('ERROR(' + err.code + '): ' + err.message);
});
}
proof of concept fiddle
There could be 3 reasons:
Your browser doesn't support geolocation.
You have disabled geolocation tracking. In google chrome you can enable it looking in options, searching location in your settings.
If you are working on a HTML file on your pc directly as file:/// geolocation is disabled for security reasons.

Google Maps Places Search, calculate distance to each result

I'm currently making an app for a university assignment. I'm using the google maps places api and gmaps.js.
What I want to do is let user search places and show the results in a simple list (which I've got working) but I want to calculate the distance to each of the search results as well, which is sort of working (I think!) but I'm not sure how to make it display how I want, e.g:
"Search Result - 1.1 mi away"
"Search Result - 0.8 mi away"
What it is doing right now is calculating the distances but all the values are being set next to all of the search results, instead of next to each other. In one line (all bunched together).
(Had to remove a link to post a new one)
I don't know how to split them or do it more cleanly from the start. I think the problem lies in the function which is calculating the distances using "google.maps.DistanceMatrixService".
var origin = currentLocation;
var destination = place.geometry.location;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.WALKING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, getDistance);
function getDistance(response, status) {
if (status == "OK") {
var distance = response.rows[0].elements[0].distance.text;
console.log(distance);
$(".distance").append(distance);
} else {
return false;
console.log(response + status)
}
}
getDistance();
This line is my best guess:
response.rows[0].elements[0].distance.text;
But I'm quite lost with it.
Full code of my search request:
$("#place-search").submit(function(e){
e.stopPropagation(); e.preventDefault();
var query = $("#place-query").val();
map.addLayer("places", {
location: cheltenham, //new google.maps.LatLng(51.902707,-2.073361),
radius: 500, //experiment with the distance (in metres)
query: query,
opennow: true,
textSearch: function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
$(".results-list").html(""); //remove previous results
removeMarkers(); //remove previous markers
var bounds = new google.maps.LatLngBounds();
//console.log(bounds);
//I think if we set i to say 10, it will limit the search results - by default the places api returns 20 result sets
for (var i = 0; i < results.length; i++) {
//console.log(i);
var place = results[i];
var image = { //set to better sizes and positions (icons from search results)
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
/* ---------- */
var origin = currentLocation; //new google.maps.LatLng(51.902707,-2.073361);
var destination = place.geometry.location; //new google.maps.LatLng(51.899464, -2.074641);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.WALKING, //this needs to be a choice
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, getDistance);
function getDistance(response, status) {
if (status == "OK") {
var distance = response.rows[0].elements[0].distance.text; //the one I need
console.log(distance);
$(".distance").append(distance);
} else {
return false;
console.log(response + status)
}
}
getDistance();
/* ---------- */
map.addMarker({
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
icon: image,
animation: google.maps.Animation.DROP,
title: place.name,
//we need to style and build these better - ideas? should be simple I think, Name + Location + Image
infoWindow: {
content: '<h2>'+place.name+'</h2>' + '<p>Rating: '+place.rating+'</p>' + '<p>'+(place.vicinity ? place.vicinity : place.formatted_address)+'</p><img src="'+place.icon+'"" width="100"/>'
}
});
bounds.extend(place.geometry.location);
$(".results-list").append("<li>" + place.name + "<span class=\"distance\"></span></li>");
}
map.fitBounds(bounds); //fit to the new bounds
}//end if search OK
}
});
});
Any help or pointers would be greatly appreciated!
Update:
I've tried moving the line that puts the items into the list with jQuery into the function getDistance(), and that ends up putting the distances with the place name but it's the same place name for every distance that is calculated. It is the last result from the search.
getDistance()
function getDistance(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
var distance = element.distance.text;
var duration = element.duration.text;
var from = origins[i];
var to = destinations[j];
$(".results-list").append("<li><span class=\"name\">" + place.name + "</span>" + distance + "</li>")
}
}
} else {
return false;
console.log(response + status)
}
}
What the output looks like: http://i.imgur.com/FSCMMzF.png
Thanks to everyone who's taken a look so far!

Categories

Resources