Google Map API を利用して二点間のルートを表示する

ここではナビゲーションで使用されるような経路を表示する方法を紹介します。

始点と終点の郵便番号を入力してボタンを押すと、その二点間の経路を表示するというようなサンプルプログラムです。

ちなみに、アメリカの郵便番号を利用したサンプルになっています。90501 はカリフォルニア州のトーランス市にある郵便番号、 92802 は同じくカリフォルニア州のアナハイムにある郵便番号です。アナハイムはディズニーランドがあるところです。

Start: End:

二点間の経路を示す地図

コードは次のとおりです。

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

$(document).ready(function(){
	geocoder = new google.maps.Geocoder();

	directionsDisplay = new google.maps.DirectionsRenderer();
	var hollywood = new google.maps.LatLng(34.086787, -118.337517);
	var myOptions = {
		zoom:7,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: hollywood
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	directionsDisplay.setMap(map);
});

function calcRoute() {
	var start = document.getElementById("startZip").value;
	var end = document.getElementById("endZip").value;
	var request = {
		origin:start,
		destination:end,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
}

function showRoute(){
	calcRoute();
}
</script>
<div style='clear:both;'>
Start: <input type='text' value='90501' id='startZip' style='width:75px;'> 
End: <input type='text' value='92802' id='endZip' style='width:75px;'>
 <input type='button' value='Show Route' onclick='showRoute();'>
</div>
<div id="map_canvas" style="width:400px;height:300px;"></div>

経路を表示する地図を DirectionsRenderer に関連付けします。

DirectionService の route メソッドで経路検索を行い、 その結果を DirectionsRenderer の setDirections メソッドでレンダラに関連付けします。

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Web/DB プログラミング徹底解説