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.
Related
The below code shows two points in the map and draws the driving path between those points. What I'm trying to achieve is when I move a point, it should move the marker and re-draw the path. How can I do that? I appreciate any hints. Thanks.
function mapLocation() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var istanbul = new google.maps.LatLng(41.015137, 28.979530);
var mapOptions = {
zoom: 7,
center: istanbul
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = new google.maps.LatLng(41.01524, 28.975994);
//var end = new google.maps.LatLng(38.334818, -181.884886);
var end = new google.maps.LatLng(41.013232, 28.978676);
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);
directionsDisplay.setMap(map);
} else {
alert("Directions Request from " + start.toUrlValue(6) + " to " + end.toUrlValue(6) + " failed: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
mapLocation();
You can set the draggable option of the DirectionsRendererOptions to true and pass it to the DirectionsRenderer to allow users to edit the rendered route(s).
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true
});
See the documentation.
Really need some ideas on this. Been working on Google map API, which I'm using Geocoding, Reverse Geocoding and Geolocation. With this piece of code, below,I am able to use Direction API of Google map, which works perfectly.
var locations = [
{lat: 6.4261139, lng: 3.4363691}
];
var mapContainer = $('.map-container'),
map = new google.maps.Map(mapContainer[0], {
center: center,
zoom : 10
});
var markers = _(locations)
.map(function (loc) {
return new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng)
});
})
.each(function (marker) {
marker.setMap(map);
})
.value();
var mc = new MarkerClusterer(map, markers);
var directionsService = new google.maps.DirectionsService(),
directionsDisplay = new google.maps.DirectionsRenderer(),
displayRoute = function () {
directionsService.route({
origin: 'Akin Ogunlewe street VI',//6.512596400000001+','+3.3541297 Pass this in place of the address
destination: 'Falolu road Surulere',//'Falolu road Surulere',//6.4261139+','+3.4363691 Pass this in place of the address
travelMode : google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
};
directionsDisplay.setMap(map);
displayRoute();
Is there a way I can pass Latitude and Longitude in Origin and Destination Instead of physical address (string)?
I tried it but did not work.
I need to pass the numeric (float) value like:6.512596400000001,3.3541297 Instead of Falolu road Surulere
Any help is appreciated thanks
The documentation for the v3 API says a google.maps.LatLng or a string. For geographic locations, create and pass in a google.maps.LatLng; for addresses, pass in a string.
origin: LatLng | String | google.maps.Place,
destination: LatLng | String | google.maps.Place,
And in the reference
destination | Type: Place | Location of destination. This can be specified as either a string to be geocoded, or a LatLng, or a Place. Required.
origin | Place | Location of origin. This can be specified as either a string to be geocoded, or a LatLng, or a Place. Required.
proof of concept fiddle
code snippet:
var map;
function initialize() {
var locations = [{
lat: 6.4261139,
lng: 3.4363691
}];
var mapContainer = $('.map-container'),
map = new google.maps.Map(mapContainer[0], {
center: locations[0],
zoom: 10
});
var directionsService = new google.maps.DirectionsService(),
directionsDisplay = new google.maps.DirectionsRenderer(),
displayRoute = function() {
directionsService.route({
origin: new google.maps.LatLng(6.512596400000001, 3.3541297), // Pass this in place of the address 'Akin Ogunlewe street VI'
destination: new google.maps.LatLng(6.4261139, 3.4363691), // Pass this in place of the address 'Falolu road Surulere'
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
};
directionsDisplay.setMap(map);
displayRoute();
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" class="map-container"></div>
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;
}
}
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
I have the following code:
<script>
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var England = new google.maps.LatLng(53.7415, 1.6860);
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: England
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
map.setTilt(45);
directionsDisplay.setMap(map)
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: 'postcode',
destination: 'postcode',
waypoints:[{location: 'waypoint postcode'}, {location: 'waypoint postcode'}, {location: 'waypoint postcode'}],
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
document.getElementById('total').innerHTML = total + ' km';
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
The map, shows an origin and destination, with certain waypoints along the way, using google api's direction service. The directions panel shows all distances in metric units. How do I change it, so that all distances are shown in imperial units i.e miles,feet?
From the docs
Unit Systems
By default, directions are calculated and displayed using the unit
system of the origin's country or region. (Note: origins expressed
using latitude/longitude coordinates rather than addresses always
default to metric units.) For example, a route from "Chicago, IL" to
"Toronto, ONT" will display results in miles, while the reverse route
will display results in kilometers. You may override this unit system
by setting one explicitly within the request using one of the
following UnitSystem values:
UnitSystem.METRIC specifies usage of the metric system. Distances are shown using kilometers.
UnitSystem.IMPERIAL specifies usage of the Imperial (English) system. Distances are shown using miles.
Note: this unit system setting only affects the text displayed to the
user. The directions result also contains distance values, not shown
to the user, which are always expressed in meters.