Help me with google direction to include distance matrix
on my site, im using the below code to get Google map. what code should i add to also show distance between from and to and also traveling time?
thank you.
<div style="width: 298px;">
<div id="map" style="width: 298px; height: 400px; float: left;"></div>
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: '<?php echo $contents['pickupname']; ?>',
destination: '<?php echo $contents['dropoffname']; ?>',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
Make this changes:
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
var myRoute = response.routes[0].legs[0];
var duration = myRoute.duration.value;
var distance = myRoute.distance.value;
});
Also note this code is just for demonstration. You need to modify the code to check cases where there are multiple routes, legs.
For detailed information see DirectionsResult, DirectionsRoute, DirectionsLeg
This is the solution I'm using:
First add element that will show your data in HTML. I'm using input element like this:
<input type="text" name="distance" id="distance" readonly="true" />
When you do the calculation in you JS send that data to input. For example:
var distanceInput = document.getElementById('distance');
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
Related
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);
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 the total distance in KM in my javascript. It is shown already on top of the Panel, but i need this value also in my javascript. My javascript is as followed:
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var een = '52.3641205';
var twee = '4.905697000000032';
var drie = '52.6010666';
var vier = '4.73768229999996';
var p1 = new google.maps.LatLng(een, twee);
var p2 = new google.maps.LatLng(drie, vier);
var request = {
origin: p1,
destination: p2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
alert('Total travel distance is:' + response);
directionsDisplay.setDirections(response);
}
});
The functionality is working but i would also like to alert the total distance. This is seen at the top of the panel. The panel will be invisible in the future so a getelementbyID function is not enough.
Can someone help me with this?
Thank You!
Sergio
The distance is available in each of the route legs
google.maps.Distance object specification
A representation of distance as a numeric value and a display string.
Properties Type Description
text string A string representation of the distance value, using the UnitSystem specified in the request.
value number The distance in meters.
proof of concept fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var een = '52.3641205';
var twee = '4.905697000000032';
var drie = '52.6010666';
var vier = '4.73768229999996';
var p1 = new google.maps.LatLng(een, twee);
var p2 = new google.maps.LatLng(drie, vier);
var request = {
origin: p1,
destination: p2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
document.getElementById('distance').innerHTML = 'Total travel distance is: ' + (response.routes[0].legs[0].distance.value / 1000).toFixed(2) + " km";
alert('Total travel distance is: ' + (response.routes[0].legs[0].distance.value / 1000).toFixed(2) + ' km');
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="distance"></div>
<div id="map" style="border: 2px solid #3872ac;"></div>
<div id="panel"></div>
As per the documentation:
unitSystem
Type: UnitSystem
Preferred unit system to use when displaying distance. Defaults to the unit system used in the country of origin.
So if you want to force it to METRIC:
var request = {
origin: p1,
destination: p2,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
This will force the value of response.routes[0].legs[0].distance.text to use the metric system.
And as explained in #geocodezip answer, you can also rely on the response.routes[0].legs[0].distance.value which is always returned in meters, even if the country of origin uses the imperial system.
You can easily get the distance by getting:
directionsDisplay.directions.routes[0].legs[0].distance.text
The result, for example, would be text like "20,5 km".
In your request, set units=metric.
Then use: distance = response.routes[0].legs[0].distance.text; in your alert.
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
Hi i'm wanting to create a map that, when a function is called, generates directions to a point based on the users current geolocation. I have tried to do this and so far my attepts have been fruitless, here is my current JS code:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = latlon;
var end = "Darwin, NSW, Australia";
var request =
{
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVIN
};
function initialize()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
directionsDisplay = new google.maps.DirectionsRenderer();
var latlon = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions =
{
zoom:15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
}
}
function getdirections()
{
directionsService.route(request, function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
}
});
}
Any Help would be greatly appreciated, but keep in mind it must use the google maps api, v3. Thank you :)
Please checkout this jsfiddle,
Here i have hard-coded the starting position and end position is the users current position.
Is this what you are looking for ?