JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"> </script>
</head>
<body>
<div id="msg"></div>
</body>
</html>
JavaScript
// 建立 DirectionsService 物件
var directionsService = new google.maps.DirectionsService();
// DirectionsRequest
var request = {
// 起點
origin: new google.maps.LatLng(25.080155,121.522534 ),
// 終點
destination: new google.maps.LatLng(25.078561,121.521461),
waypoints: [],
// 路線最佳化
optimizeWaypoints: true,
// 交通模式,目前有 開車/步行 以及腳踏車(僅限美國) 三種路線規劃
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
// 取得距離
// console.log(route.legs[0].distance.text);
// 取得從起點至終點的大約時間
// console.log(route.legs[0].duration.text);
document.getElementById('msg').innerHTML = route.legs[0].distance.text + ', ' + route.legs[0].duration.text ;
}
});