Google Maps APIで始点と終点からルート検索
プレビュー
↓別ウィンドウを開いて見る
Google Mapsで始点と終点からルート検索 - js do it
※おすすめQRコード読み取りアプリ
お父さんQR
カテゴリ: ユーティリティ
サイズ: 2.3 MB
価格: 無料
ポイント
HTML
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <title>Google Mapsでルート検索</title> <script src="http://maps.google.com/maps/api/js?sensor=false"></script> </head> <body onload="initialize();"> <div id="container"> <h1>Google Mapsでルート検索</h1> <p>テキストフィールドに始点と終点を入力すると、ルート検索を行います。</p> <p>※なるべく駅名を入れてください。(例:○○駅)</p> <table> <tr><th>始点:</th><td><input type="text" name="start" id="start" size="12" maxlength="100"></td></tr> <tr><th>終点:</th><td><input type="text" name="end" id="end" size="12" maxlength="100"></td></tr> </table> <p> <input type="button" value="検索" onclick="searchRoute()"> </p> <div id="map_canvas" style="width:100%; height:320px;"></div> <div id="directionsPanel"></div> </div> </body> </html>
CSS
html { height: 100%; } body { height: 100%; margin: 0; padding: 0; background-color:#eee; font-family: "ヒラギノ角ゴ Pro W3", "Hiragino Kaku Gothic Pro", "メイリオ", Meiryo, Osaka, "MS Pゴシック", "MS PGothic", sans-serif; } #container { margin:10px; padding-bottom:30px; } h1 { font-size:1.2em; background-color:#8AA5E5; color:#fff; padding:20px; } #map_canvas { height: 100%; } #directionsPanel { background-color:#fff; }
JavaScript
var map; var directionsDisplay; var directionsService; //initialize関数 function initialize() { var latlng = new google.maps.LatLng(35.681382,139.766084); var myOptions = { zoom:14, center:latlng, mapTypeId:google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: '#FF0000', strokeWeight: 4, strokeOpacity: 0.7 } }); directionsDisplay.setMap(map); } //searchRoute関数 function searchRoute() { var start = document.getElementById("start").value; var end = document.getElementById("end").value; var rendererOptions = { draggable: true, preserveViewport:false }; directionsService = new google.maps.DirectionsService(); var request = { origin: start, destination: end, travelMode: google.maps.DirectionsTravelMode.DRIVING, unitSystem: google.maps.DirectionsUnitSystem.METRIC, optimizeWaypoints: true, avoidHighways: false, avoidTolls: false }; directionsService.route(request, function(response, status){ if (status == google.maps.DirectionsStatus.OK){ directionsDisplay.setDirections(response); directionsDisplay.setPanel(document.getElementById("directionsPanel")); } }); map = new google.maps.Map(document.getElementById("map_canvas"), response); directionsDisplay.setMap(map); }