ウェブ学のすすめ

Study of Web Design & Programing

Google Maps JavaScript APIを使ったルート検索

プレビュー


↓別ウィンドウを開いて見る
ルート検索マップ(詳細)

QRコード

※おすすめQRコード読み取りアプリ

お父さんQR
カテゴリ: ユーティリティ
サイズ: 2.3 MB
価格: 無料

ポイント

Google Maps APIを呼び出す
<script src="http://maps.google.com/maps/api/js?sensor=true&language=ja"></script>
緯度経度を指定する
new google.maps.LatLng(緯度,経度);
地図のタイプを設定する
mapTypeId: google.maps.MapTypeId.ROADMAP
  • ROADMAP:デフォルトの道路地図
  • SATELLITE:航空写真
  • HYBRID:通常のビューと航空写真の混合
  • TERRAIN:物理的なマップ
ドラッグ操作の有効/無効を設定する
draggable: true
出発点を指定する
origin: 場所
到着点を指定する
destination: 場所
交通手段を指定する
travelMode: google.maps.DirectionsTravelMode.DRIVING
  • DRIVING:運転ルート
  • WALKING:徒歩ルート
  • BICYLING:自転車ルート
高速道路の指定
avoidHighways: true or false
有料区間を除外するかどうかの指定
avoidTolls: true or false

コード

HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<title>ルート検索マップ(詳細)</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&language=ja"></script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:480px"></div>
<div id="directionsPanel" style="width:100%; height:480px"></div>
</body>
</html>
CSS
html { 
    height: 100% 
}
body { 
    height: 100%; 
    margin: 0px; 
    padding: 0px 
}
#map_canvas { 
    height: 100% 
}
JavaScript
function initialize(position){
    var latlng = new google.maps.LatLng(35.724398350536845, 139.71546694636345);
    var myOptions = {
      zoom: 17,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    var rendererOptions = {
        draggable: true,
        preserveViewport:false
    };
    var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    var directionsService = new google.maps.DirectionsService();
    var request = {
        origin: "池袋駅",
        destination: latlng,
        travelMode: google.maps.DirectionsTravelMode.WALKING,
        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"));
        
        }
    });
    
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
    directionsDisplay.setMap(map);
}

参考