如何使用谷歌地图API浏览路线?

如何使用谷歌地图API浏览路线?

问题描述:

我正在使用谷歌地图API浏览用户的位置之间的路线,以固定的位置,我用DirectionsService导航,但它不起作用。如何使用谷歌地图API浏览路线?

<script type="text/javascript"> 

$("#map-page").live("pageinit", function() { 

    var defaultLatLng = new google.maps.LatLng(22.983587,120.22599); // Default to Hollywood, CA when no geolocation support 
    // 建立 DirectionsService 物件 
    var directionsService = new google.maps.DirectionsService(); 


    if (navigator.geolocation) { 
     function success(pos) { 
      // Location found, show map with these coordinates 
      drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); 
       // DirectionsRequest 
     var request = { 
     origin: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude), // 起點 
     destination: new google.maps.LatLng(22.981666,120.194301), // 終點 
     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); 
    } 
}); 

     } 

     function fail(error) { 
      console.log(error); 
      drawMap(defaultLatLng); // Failed to find location, show default map 
     } 

     // Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds 
     navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000}); 
    } else { 
     drawMap(defaultLatLng); // No geolocation support, show default map  
    } 

    function drawMap(latlng) { 
     var myOptions = { 
      zoom: 10, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 

     }; 

     var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions); 

     // Add an overlay to the map of current lat/lng 
     var marker = new google.maps.Marker({ 
      position: latlng, 
      map: map, 
      title: "Greetings!" 
     }); 
    } 
    </script> 

谁能告诉我什么是错的,THX

通过我上面的

http://appkon.com/demo/project2/maps.html

+0

“不行”是什么意思? – Marcelo 2012-08-08 13:28:50

的代码演示看着Chrome的JavaScript控制台的方式,我出现错误,此资源即将到达404,无法加载: http://appkon.com/demo/JQuery%20Mobile%20%E7%A8%8B%E5%BC%8F%E7%A2%BC/ch9/maps.js

我怀疑这是你的问题的开始。我会解决这个问题,看看还有什么不对。这是使用Chrome开发工具调试Maps API的很好的参考视频: http://www.youtube.com/watch?v=nb4gvrNrDWw