如何在JavaScript中获取以KM为单位的总距离

问题描述:

如何在JavaScript中获取以KM为单位的总距离.它已经显示在面板顶部,但是我的JavaScript也需要此值.我的JavaScript如下:

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);

   }
 }); 

该功能正在运行,但我也想提醒总距离.这可以在面板顶部看到.将来该面板将不可见,因此getelementbyID函数还不够.

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.

有人可以帮我吗?

谢谢!

塞尔吉奥

在您的请求中,设置units=metric.

然后在您的警报中使用:distance = response.routes[0].legs[0].distance.text;.

Then use: distance = response.routes[0].legs[0].distance.text; in your alert.