1

アプリ全体で Google マップを使用している MVC アプリケーションがあります。簡単にするために、マップを初期化し、マップ表示を設定する JavaScript ファイルを作成しました。

私のアプリケーションでは、フロント エンドの開発者が単純な JavaScript 呼び出しで地図の位置の中心を変更できるようにしたいと考えています。残念ながら、マップを宣言してアプリケーションをロードした後、JavaScript コールバックをマップ変数に行おうとすると、マップ JS 変数 (およびすべての変数) が null になります。これにより、インスタンスがマップにドロップされ、場所を変更できなくなります (私は信じています)。

以下の JS コードでは、HTML ページから setLocation を呼び出して場所をリセットしようとしています。これは、コードの失敗部分です。助けていただければ幸いです。

var map;
var geocoder;
var marker;

$(document).ready(function () {
    initialize();
    $(function () {
        $("#address").autocomplete({
            //This bit uses the geocoder to fetch address values
            source: function (request, response) {
                geocoder.geocode({ 'address': request.term }, function (results, status) {
                    response($.map(results, function (item) {
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            latitude: item.geometry.location.lat(),
                            longitude: item.geometry.location.lng()
                        }
                    }));
                })
            },

            select: function (event, ui) {
                $("#Place_Latitude").val(ui.item.latitude);
                $("#Place_Longitude").val(ui.item.longitude);
                var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                marker.setPosition(location);
                map.setCenter(location);
            }
        });
    });
});

function setLocation(lat, lon) {
    var location = new google.maps.LatLng(lat, lon);
    marker.setPosition(location);
    map.setCenter(location);
}
function initialize() {
    var location = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        center: location, zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    marker = new google.maps.Marker({
        map: map,
        draggable: true
    });
    marker.setPosition(location);

    geocoder = new google.maps.Geocoder();
}
4

2 に答える 2

0

あなたがここでやろうとしていることの例があります...

placeMarker関数と、それらがマップをどのように初期化したかを見てください...

私の提案は、この例から始めて、それが機能することを確認することです。その場合、実装で何が違うのかを判断するのは比較的簡単です。

于 2012-12-06T21:02:59.310 に答える
0

これは見栄えが悪いです:

return {
       label: item.formatted_address,
       value: item.formatted_address,
       latitude: item.geometry.location.lat(),
       longitude: item.geometry.location.lng()
       }

ジオコーダーは非同期であり、コールバック ルーチンから何も返すことができません。コールバック内で変数を使用する必要があります。

于 2012-12-04T19:12:16.123 に答える