要實現這個功能必須使用Directions Service類別的route方法
route能帶入DirectionsRequest以及一個function
DirectionsRequest這個物件裡面有這些屬性
最基本的設定起點與目的地以及導航模式
將設定好資料透過該function回傳Google Drive Service
正確的話會得到JSON資料,將資料透過DirectionsRenderer的setDirections方法來繪製到地圖上
程式碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
$(function () {
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(22.63961980, 120.30211060)
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin: new google.maps.LatLng(22.631386, 120.301951),
destination: new google.maps.LatLng(22.63961980, 120.30211060),
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
console.debug(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
</script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { height: 95% ; width: 100% }
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
執行結果:
本篇文章程式碼參考於『Directions Service』
參考資料:
https://developers.google.com/maps/documentation/javascript/directions
https://developers.google.com/maps/documentation/javascript/reference#DirectionsService
https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest
https://developers.google.com/maps/documentation/javascript/reference#TravelMode
https://developers.google.com/maps/documentation/javascript/reference#DirectionsRenderer





