通过google API 查询路线

      google APi主要通过DirectionsService这个类来实现路线的查询,可以直接传入两个地点的名称作为参数来查询,也可以传入坐标来查询,直接上代码 

<html>
   <head></head>
   <div id="map-canvas" style="width:1000px;height:1000px"></div>
   <div>
       <strong>Mode of Travel: </strong>
       <select id="mode" onchange="calcRoute();">
             <option value="DRIVING">Driving</option>
             <option value="WALKING">Walking</option>
            <option value="BICYCLING">Bicycling</option>
            <option value="TRANSIT">Transit</option>
       </select>
   </div>
</html>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=&sensor=true"></script>  //引入googel的API
<script type="text/javascript">
     var directionsDisplay;
     var directionsService = new google.maps.DirectionsService();
     var map;
     var haight = new google.maps.LatLng(22.278619, 114.153301);                 //这里用坐标初始化要查询的两个地点之间的经纬度
     var oceanBeach = new google.maps.LatLng(22.281044, 114.159785);

   //初始化的方法

function initialize() {
       directionsDisplay = new google.maps.DirectionsRenderer();

       //初始化地图的选项
       var mapOptions = {
             zoom: 14,
             mapTypeId: google.maps.MapTypeId.ROADMAP,
             center: haight
       }
      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
      directionsDisplay.setMap(map);
}

 

//计算路径的方法

function calcRoute() {
       var selectedMode = document.getElementById("mode").value;
       var request = {
           origin: haight,                    //这里也可以传入字符串 如 '西直门,西三旗'
           destination: oceanBeach,
            travelMode: google.maps.TravelMode[selectedMode]  //这里选择方式 DRIVING WALKING BICYCLING TRANSIT四种方式
        };

      //从服务器传回的结果
       directionsService.route(request, function(response, status) {
       console.log(response);

       if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
       }
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

posted on 2013-03-21 19:53  李乐已存在  阅读(272)  评论(0编辑  收藏  举报

AmazingCounters.com