打印自驾 距离 与 时间

此示例是一个自驾车搜索。搜索从西单到搜狐网络大厦,的驾车路线。并显示在地图上。并打印耗时与里程。

关键代码

function callback(result){
	var option={'map':map,'panel':document.getElementById('result'),'drivingResult':result};
	var dRenderer=new sogou.maps.DrivingRenderer(option);
	alert('全程共:'+Math.round(result.data.distance/1000)+'公里'+',耗时:'+result.data.time);
}
var request={
     'map':map,       
     'destination':'搜狐网络大厦',
     'origin':'西单',
     'tactic':2       //驾车策略。 0: 距离短;1 :时间短 默认策略 (不选为1);2 :不走高速

}
var nav=new sogou.maps.Driving();
nav.route(request,callback);
			

代码解析

首先要先初始化一个自驾车实例,设置请求参数。调用route方法。

var request={
     'map':map,       
     'destination':'搜狐网络大厦',
     'origin':'西单',
     'tactic':2       //驾车策略。 0: 距离短;1 :时间短 默认策略 (不选为1);2 :不走高速

}
var nav=new sogou.maps.Driving();
nav.route(request,callback);
			

接下来将查询结果返回给回调函数,显示到地图上,打印耗时,里程。需要先初始化渲染类。再调用自驾的setRenderer方法,进行结果渲染及打印。

function callback(result){
	var option={'map':map,'panel':document.getElementById('result'),'drivingResult':result};
	var dRenderer=new sogou.maps.DrivingRenderer(option);
	alert('全程共:'+Math.round(result.data.distance/1000)+'公里'+',耗时:'+result.data.time);
}
			

完整代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>自驾 距离 与 时间</title>
<style type="text/css">
#map{position:absolute;width:500px; height:600px;}
</style>
<script type="text/javascript" src="http://api.go2map.com/maps/js/api_v2.5.1.js"></script>
</head>

<body>
    <div id="map" style="float:left"></div>
	<div id="result" style="margin-left:500px;font-size:12px;">
		
	</div>
</body>
<script>

var myLatLng = new sogou.maps.Point(12957062,4827187);
var myOptions = {
  zoom: 10,
  center: myLatLng
};
var map = new sogou.maps.Map(document.getElementById("map"), myOptions);


function callback(result){
	var option={'map':map,'panel':document.getElementById('result'),'drivingResult':result};
	var dRenderer=new sogou.maps.DrivingRenderer(option);
	alert('全程共:'+Math.round(result.data.distance/1000)+'公里'+',耗时:'+result.data.time);
}
var request={
     'map':map,       
     'destination':'搜狐网络大厦',
     'origin':'西单',
     'tactic':2       //驾车策略。 0: 距离短;1 :时间短 默认策略 (不选为1);2 :不走高速

}
var nav=new sogou.maps.Driving();
nav.route(request,callback);
</script>
</html>
			

运行代码