JavaScript - GoogleMap 路線規劃

JavaScript - GoogleMap 路線規劃

參考文件:

https://dotblogs.com.tw/atowngit/2011/01/11/20746

需載入google map js library 

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=<YOUR_KEY>"></script>

及 設置你的GoogleMap

<div id="map_canvas"style=" height:100%;width:100%"></div>

再來就是 

初始化地圖與建立起始點、結束點,再使用google direction service

<script type="text/javascript">
	var map;
    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

	function initMap() {
		var latlng = {lat:25.0705149,lng:121.4701983};
		var latlng2 = {lat:25.0689899,lng:121.5393153};
		//zoom 參數可控制地圖預設縮放大小
		var settings = {
			zoom: 13,
			center: latlng,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
			navigationControl: true,
			navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		map = new google.maps.Map(document.getElementById("map_canvas"), settings);

	    directionsDisplay = new google.maps.DirectionsRenderer({
	        'map': map,
	        'preserveViewport': true,
	        'draggable': true
	    });	

	    renderRouter(latlng,latlng2);
	}

    function renderRouter(pFrom,pEnd) {
		var start = pFrom;
		var end = pEnd;
	    var request = {
	        origin:start,		//起始地
	        destination:end,	//目的地
	        travelMode: google.maps.DirectionsTravelMode.DRIVING //旅行工具 WALKING | DRIVING
	    };
	    directionsService.route(request, function(response, status) {
	        if (status == google.maps.DirectionsStatus.OK) {
	        	directionsDisplay.setDirections(response);			
	        }
	    });		
  	}

	$(document).ready(function(){
		initMap();
	});
</script>