Get and show direction without showing a google map - javascript

Hi is it possible to get the direction from googlemaps without showing a map?
I can get the directions from calling like this:-
https://maps.googleapis.com/maps/api/directions/json?origin=52.4076963,-1.4853391999999985&destination=52.6114729,-1.6812878000000637&key=KEYHERE
<div id="result"></div>
And the code I am trying to call it with is :
function calcRoute() {
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var result = document.getElementById('result');
result.innerHTML= "";
for (var i =0; i < response.routes[0].legs[0].steps.length; i++){
result.innerHTML+=response.routes[0].legs[0].steps[i].instructions+"<br>"
}
console.log(response)
directionsDisplay.setDirections(response);
}
});
}
calcRoute();
How I get this to run with calcRoute and just show the direction in the div?
Thanks

To display the directions text without a map using the Google Maps Javascript API v3:
don't set the map property of the DirectionsRenderer
set the panel property of the DirectionsRenderer
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setPanel(document.getElementById('result'));
directionsDisplay.setDirections(response);
}
});
}
proof of concept fiddle
function initialize() {
function calcRoute() {
var directionsService = new google.maps.DirectionsService();
var start = "52.4076963,-1.4853391999999985";
var end = "52.6114729,-1.6812878000000637";
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setPanel(document.getElementById('result'));
directionsDisplay.setDirections(response);
}
});
}
calcRoute();
}
google.maps.event.addDomListener(window, "load", initialize);
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="result"></div>

The solution to a lot of "how to use the maps API without showing a map?" questions assumes that it's going to be ok to use setPanel and for a journey plan to appear on your page instead of a map.
In case anyone wondered, if you don't want this and just want to extract data from the API without any google html being injected into your page at all you still need to use setPanel, but parse a null to it.
directionsDisplay.setPanel(null);

Related

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 use direction route object to get data

With the code below, I display a journey betwen two points.
Now I try to use direction result object and direction leg to get information like steps, legs or distance in a variable, but I have no idea to how use this method...
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(44.912198, -0.605530);
var oceanBeach = new google.maps.LatLng(44.893356, -0.739138);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute()
}
calcRoute()
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
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);
Thanks
I've resolved a part of the problem with this code :
Variable duration, path, and polyline1 are ok, I've tried it with an alert.
Now I want to save those variables in a data base like sql, how I do ? using php ?
function calcRoute() {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var duration = myRoute.steps[i].duration.text;
var path = myRoute.steps[i].path;
var polyline1 = myRoute.steps[i].distance.text;
}
}

Google maps api directions zoom not working

Im using below code to show a distance between two distances but zoom doesn't work it always will be in default zoom level. I tried setting lot of values but it's not working. Please help.
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var from = "";
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.preserveViewport = false;
var dallas = new google.maps.LatLng(32.8931567, -97.0402193);
var mapOptions = {
zoom: 15,
center: dallas
};
map = new google.maps.Map(document.getElementById('googleMap'), mapOptions);
map.setZoom(map.getZoom()+5);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = 'dallas airport terminal a';
var end = 'SpringHill Suites';
console.log("HotelDetail: " + end);
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
For what you want to achieve, the preserveViewport property needs to be set to true like this.
directionsDisplay = new google.maps.DirectionsRenderer({
preserveViewport: true
});
//directionsDisplay.preserveViewport = false;
In addition, your code sets a zoom level of 20 which is too high to see anything on the map. Here is a working example with an initial zoom level of 12: JSFiddle

Find latitude and longitude from starting point of route finding in Google Map

I have to find latitude and longitude from starting point of route finding in Google Map api v3. Because through these latitude and longitude, i have to find store location nearby starting point like :
searchLocationsNear(lat,lng);
Code:-
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
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);
}
});
searchLocationsNear(lat,lng);
}
In above code inside start variable location will be like St. Louis
Took some time to set up a fiddle and figure it out, but this is how you'd get the latitude and longitude
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var position = response.routes[0].legs[0].start_location;
var lat = position.k;
var lng = position.B;
searchLocationsNear(lat, lng);
}
});
FIDDLE

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.

Categories

Resources