0

こちらのサイト
http://wataame.sumomo.ne.jp/archives/6905
http://mizuame.sakura.ne.jp/blog_sample/googlemap/index6.html
を参考に、2点間のルートを検索できるアプリケーションを作っていたところ、下記のエラーが出ました。

cannot read property setDirections of undefined

setDirectionsundefinedとのことなのですが、いまひとつ原因がわかりません。googleのdeveloperサイトには下記のコメントがありました。

The DirectionsResult contains the result of the directions query, which you may either handle yourself, or pass to a DirectionsRenderer object, which can automatically handle displaying the result on a map.

To display a DirectionsResult using a DirectionsRenderer, you simply need to do the following:

1.Create a DirectionsRenderer object.
2.Call setMap() on the renderer to bind it to the passed map.
3.Call setDirections() on the renderer, passing it the DirectionsResult as noted above. Because the renderer is an MVCObject, it will automatically detect any changes to its properties and update the map when its associated directions have changed.

エラーの原因がわかるかた、教えていただければ幸いです。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>two point route search</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBouRngjBWxP4S7H1wqfShSsPkserg0xBw"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
    #map_canvas{
        margin: 0;
        padding: 0;
        margin-bottom: 1em;
        height: 550px;
    }

</style>
</head>
<body>
    <div id="content">
        <h2>2点間のルート検索</h2>
        <form action="" method="post">
            <p><span class="bold">住所・地名から検索</span></p>
            Brgin: <input type="text" name="sp" id="inputBegin">
            End: <input type="text" name="ep" id="inputEnd">
            <input type="submit" name="regist" value="検索" id="searchButton">
        </form>
    </div>

    <div id="map_canvas"></div>
    <div id="directionsPanel"></div>


<script>
var map, begin, end;
var directionsDisplay;
var directionsService;

begin = '東京駅';
end = '東京スカイツリー';

$(function() {
    $('#searchButton').click(function(e) {
        e.preventDefault();         // hrefが無効になり、画面遷移が行わない

        begin = $('#inputBegin').val();
        end   = $('#inputEnd').val();

        // ルート説明をクリア
        $('#directionsPanel').text(' ');

        google.maps.event.addDomListener(window, 'load', initialize(begin, end));
        google.maps.event.addDomListener(window, 'load', calcRoute(begin, end));
    });
});


function initialize(begin, end) {
    // インスタンス[geocoder]作成
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({
        // 起点のキーワード
        'address': begin

    }, function(result, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            // 中心点を指定
            var latlng = result[0].geometry.location;

            // オプション
            var myOptions = {
                zoom: 14,
                center: latlng,
                scrollwheel: false,     // ホイールでの拡大・縮小
                mapTypeId: google.maps.MapTypeId.ROADMAP,
            };

            // #map_canvasを取得し、[mapOptions]の内容の、地図のインスタンス([map])を作成する
            map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

            // 経路を取得
            directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById('directionsPanel'));     // 経路詳細

            // 場所
            // $('#begin').text(begin);
            // $('#end').text(end);

        } else {
            alert('取得できませんでした…');
        }
    });
}

// ルート取得
function calcRoute(begin, end) {

    var request = {
        origin: begin,         // 開始地点
        destination: end,      // 終了地点
        travelMode: google.maps.TravelMode.DRIVING,     // [自動車]でのルート
        avoidHighways: true,        // 高速道路利用フラグ
    };

    // インスタンス作成
    directionsService = new google.maps.DirectionsService();

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else {
            alert('ルートが見つかりませんでした…');
        }
    });
}

// キック
google.maps.event.addDomListener(window, 'load', function() {
    initialize(begin, end);
    calcRoute(begin, end);
});
</script>
</body>
</html>

1 件の回答 1

1

cannot read property setDirections of undefined

このエラーはsetDirectionsundefinedなのではなく、directionsDisplayundefinedだという意味です。

directionsDisplayの初期化はgeocoder.geocode()のコールバック内で非同期に(geocodeの通信結果を待ってから)行われているため、calcRoute()を呼んだ時点ではまだdirectionsDisplayundefinedの状態です。

ということで、calcRoute()の呼び出し場所を変えて、geocoder.geocode()のコールバック内、directionsDisplayの初期化の後に呼ぶようにすれば動くのではないでしょうか。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。