Waypoints code in Google maps - javascript

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>

Related

Remove KM on google map distance calculation using html and javascript

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

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

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

Directions Service of Google Maps API doesn't work

Do you have any idea why my directions service of Google Maps API doesn't work? It seems that method directionsService.route() isn't executed (cause alert with status is not displayed), but I don't know why. I'm newbie in Google Maps API and JS, so try to be forgiving, if it's something simple. :)
var map = null;
var pos = null;
const STORED_LOC = new google.maps.LatLng(50.405196, 11.894855);
var currentLat = document.getElementById("latLabel");
var currentLng = document.getElementById("lngLabel");
var additionalInfo = document.getElementById("additionalInfo");
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize()
{
pos = STORED_LOC;
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
options =
{
center: pos,
zoom: 15
}
marker = new google.maps.Marker(
{
position: pos,
map: map,
title: "Chosen localization"
}
);
map = new google.maps.Map(document.getElementById("mapContainer"), options);
marker.setMap(map);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
}
$("#yes").click(function () {
getPosition();
hideUserConsentSection();
});
$("#no").click(function () {
hideUserConsentSection();
showSetCustomLocationSection();
});
function showSetCustomLocationSection() {
$("#setCustomLocationSection").show();
}
function hideUserConsentSection() {
$("#userConsentSection").hide();
}
function getPosition() {
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 2000
}
navigator.geolocation.getCurrentPosition(showPosition, errorPosition, options);
}
else
{
additionalInfo.innerHTML += "Your browser doesn't support geolocation";
}
}
function showPosition(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
currentLat.innerHTML = pos.lat();
currentLng.innerHTML = pos.lng();
var request =
{
origin: STORED_LOC,
destination: pos,
travelmode: google.maps.TravelMode.DRIVING
}
directionsService.route(request, function(result, status)
{
alert(status);
if (status == google.maps.DirectionsStatus.OK)
{
alert("OKAY");
directionsDisplay.setDirections(result);
}
});
//map = new google.maps.Map(document.getElementById("mapContainer"), options);
//marker.setMap(map);
}
function errorPosition(position) {
switch (position.code) {
case 1:
showSetCustomLocationSection();
break;
case 2:
showSetCustomLocationSection();
break;
case 3:
showSetCustomLocationSection();
break;
default:
break;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
My HTML looks like that:
<h3>How to reach us?</h3>
<div id="userConsentSection">Can we use your geolocation?<br />
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" /><br /><br />
</div>
<div id="setCustomLocationSection" style="display:none">
Enter your geolocation. <br /><br />
<input type="text" id="customLocation" />
<input type="button" id="setCustomLocationButton" value="Show" /><br /><br />
</div>
<span>Latitude: </span>
<div id="latLabel">
</div>
<span>Longitude: </span>
<div id="lngLabel">
</div>
<div id="additionalInfo">
</div>
<div id="mapContainer" style="height: 400px; width: 100%">
</div>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=XXXX&sensor=true">
</script>
The answer is typo in request object - travelmode instead travelMode. This parameter is required and as the result - route method doesn't execute. Be careful with that name!

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>

Adding distance matrix to google direction

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;

Categories

Resources