Google 交通方向时间
Google direction time with traffic
我为我的网站使用 google 地图,我想在交通中获取路线,如何在交通中获得 google 地图路线中的预计时间?
我使用以下代码在没有路况的情况下获取路线。
function direction(){
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var nmap = new google.maps.Map(document.getElementById('direction-map'), mapOptions);
directionsRenderer.setMap(nmap);
calcRoute();
}
function calcRoute() {
var blng = parseFloat($("#beginning-lng").val());
var blat = parseFloat($("#beginning-lat").val());
var dlng = parseFloat($("#destination-lng").val());
var dlat = parseFloat($("#destination-lat").val());
var start = new google.maps.LatLng(blat, blng);
var end = new google.maps.LatLng(dlat, dlng);
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING',
avoidTolls: true
};
directionsService.route(request, function (result, status) {
if (status == 'OK') {
directionsRenderer.setDirections(result);
console.log(result);
var distance = result.routes[0].legs[0].distance.value / 1000;
var time = result.routes[0].legs[0].duration.value / 60;
}
});
}
要在路况期间获取路线,请参阅 DrivingOptions 的文档:
departureTime (required for the drivingOptions object literal to be valid) specifies the desired time of departure as a Date object. The value must be set to the current time or some time in the future. It cannot be in the past. (The API converts all dates to UTC to ensure consistent handling across time zones.) For Google Maps Platform Premium Plan customers, if you include the departureTime in the request, the API returns the best route given the expected traffic conditions at the time, and includes the predicted time in traffic (duration_in_traffic) in the response. If you don't specify a departure time (that is, if the request does not include drivingOptions), the returned route is a generally good route without taking traffic conditions into account.
trafficModel (optional) specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. Defaults to bestguess. The following values are permitted:
- bestguess (default) indicates that the returned duration_in_traffic should be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer the departureTime is to now.
- pessimistic indicates that the returned duration_in_traffic should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.
- optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.
Note: If departure time is not specified, choice of route and duration are based on road network and average time-independent traffic conditions. Results for a given request may vary over time due to changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency.
Note: To ensure that your request uses live traffic information, set the departureTime to now. Requests using traffic information are billed at a higher rate. Learn more about how Google Maps Platform products are billed.
基于文档中的请求和文档中的示例:
- https://developers.google.com/maps/documentation/javascript/examples/directions-simple
- https://developers.google.com/maps/documentation/javascript/examples/directions-panel
代码片段:
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: {
lat: 41.85,
lng: -87.65
},
});
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById("sidebar"));
calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService
.route({
origin: 'Anaheim, CA',
destination: 'Los Angeles, CA',
travelMode: 'DRIVING',
drivingOptions: {
departureTime: new Date(Date.now() + 10000), // for the time 10000 milliseconds from now.
trafficModel: 'optimistic'
}
})
.then((response) => {
directionsRenderer.setDirections(response);
})
.catch((e) => window.alert("Directions request failed due to " + status));
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
width: 50%;
float: left
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#sidebar {
flex-basis: 15rem;
flex-grow: 1;
padding: 1rem;
max-width: 30rem;
height: 100%;
width: 50%;
box-sizing: border-box;
overflow: auto;
}
#sidebar {
flex: 0 1 auto;
padding: 0;
}
#sidebar>div {
padding: 0.5rem;
}
<!DOCTYPE html>
<html>
<head>
<title>Directions Service</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<div id="sidebar"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>
我将驾驶选项添加到请求中:
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING',
avoidTolls: true,
drivingOptions: {
departureTime: new Date(Date.now() + 10000),
trafficModel: 'bestguess'
}
};
并从结果中获取交通时间:
var time = result.routes[0].legs[0].duration_in_traffic.value / 60;
我为我的网站使用 google 地图,我想在交通中获取路线,如何在交通中获得 google 地图路线中的预计时间?
我使用以下代码在没有路况的情况下获取路线。
function direction(){
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var nmap = new google.maps.Map(document.getElementById('direction-map'), mapOptions);
directionsRenderer.setMap(nmap);
calcRoute();
}
function calcRoute() {
var blng = parseFloat($("#beginning-lng").val());
var blat = parseFloat($("#beginning-lat").val());
var dlng = parseFloat($("#destination-lng").val());
var dlat = parseFloat($("#destination-lat").val());
var start = new google.maps.LatLng(blat, blng);
var end = new google.maps.LatLng(dlat, dlng);
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING',
avoidTolls: true
};
directionsService.route(request, function (result, status) {
if (status == 'OK') {
directionsRenderer.setDirections(result);
console.log(result);
var distance = result.routes[0].legs[0].distance.value / 1000;
var time = result.routes[0].legs[0].duration.value / 60;
}
});
}
要在路况期间获取路线,请参阅 DrivingOptions 的文档:
departureTime (required for the drivingOptions object literal to be valid) specifies the desired time of departure as a Date object. The value must be set to the current time or some time in the future. It cannot be in the past. (The API converts all dates to UTC to ensure consistent handling across time zones.) For Google Maps Platform Premium Plan customers, if you include the departureTime in the request, the API returns the best route given the expected traffic conditions at the time, and includes the predicted time in traffic (duration_in_traffic) in the response. If you don't specify a departure time (that is, if the request does not include drivingOptions), the returned route is a generally good route without taking traffic conditions into account.
trafficModel (optional) specifies the assumptions to use when calculating time in traffic. This setting affects the value returned in the duration_in_traffic field in the response, which contains the predicted time in traffic based on historical averages. Defaults to bestguess. The following values are permitted:
- bestguess (default) indicates that the returned duration_in_traffic should be the best estimate of travel time given what is known about both historical traffic conditions and live traffic. Live traffic becomes more important the closer the departureTime is to now.
- pessimistic indicates that the returned duration_in_traffic should be longer than the actual travel time on most days, though occasional days with particularly bad traffic conditions may exceed this value.
- optimistic indicates that the returned duration_in_traffic should be shorter than the actual travel time on most days, though occasional days with particularly good traffic conditions may be faster than this value.
Note: If departure time is not specified, choice of route and duration are based on road network and average time-independent traffic conditions. Results for a given request may vary over time due to changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency. Note: To ensure that your request uses live traffic information, set the departureTime to now. Requests using traffic information are billed at a higher rate. Learn more about how Google Maps Platform products are billed.
基于文档中的请求和文档中的示例:
- https://developers.google.com/maps/documentation/javascript/examples/directions-simple
- https://developers.google.com/maps/documentation/javascript/examples/directions-panel
代码片段:
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: {
lat: 41.85,
lng: -87.65
},
});
directionsRenderer.setMap(map);
directionsRenderer.setPanel(document.getElementById("sidebar"));
calculateAndDisplayRoute(directionsService, directionsRenderer);
}
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService
.route({
origin: 'Anaheim, CA',
destination: 'Los Angeles, CA',
travelMode: 'DRIVING',
drivingOptions: {
departureTime: new Date(Date.now() + 10000), // for the time 10000 milliseconds from now.
trafficModel: 'optimistic'
}
})
.then((response) => {
directionsRenderer.setDirections(response);
})
.catch((e) => window.alert("Directions request failed due to " + status));
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
width: 50%;
float: left
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#sidebar {
flex-basis: 15rem;
flex-grow: 1;
padding: 1rem;
max-width: 30rem;
height: 100%;
width: 50%;
box-sizing: border-box;
overflow: auto;
}
#sidebar {
flex: 0 1 auto;
padding: 0;
}
#sidebar>div {
padding: 0.5rem;
}
<!DOCTYPE html>
<html>
<head>
<title>Directions Service</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<div id="sidebar"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>
我将驾驶选项添加到请求中:
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING',
avoidTolls: true,
drivingOptions: {
departureTime: new Date(Date.now() + 10000),
trafficModel: 'bestguess'
}
};
并从结果中获取交通时间:
var time = result.routes[0].legs[0].duration_in_traffic.value / 60;