1

特定の住所をジオコーディングするためにGoogleと連携するLocationというクラスオブジェクトがあります。ジオコード要求はAJAX呼び出しを介して行われ、応答が到着するとクラスメンバーを開始するコールバックを介して処理されます。

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

function Location(address) {
    this.geo = new GClientGeocoder();
    this.address = address;
    this.coord = [];

    var geoCallback = function(result) {
        this.coord[0] = result.Placemark[0].Point.coordinates[1];
        this.coord[1] = result.Placemark[0].Point.coordinates[0];
        window.alert("I am in geoCallback() lat: " + this.coord[0] + "; lon: " + this.coord[1]);
    }

    this.geo.getLocations(this.address, bind(this, geoCallback));                   
}
Location.prototype.getAddress = function() { return this.address; }
Location.prototype.getLat = function() { return this.coord[0] }
Location.prototype.getLng = function() { return this.coord[1] }

私の質問は、コンストラクターを終了する前にGoogleからの応答を待つことは可能ですか?

AJAXリクエストはGoogleAPIを介して作成されているため、制御できません。

this.coord[]Location objが作成されたら、それが正しく初期化されていることを確認したいと思います。

ありがとうございました!

4

2 に答える 2

3

いいえ、待つことはできません (読むべきではありません)。これが、そもそも AJAX ("Asynchronous Javascript ...") と呼ばれる理由です。;)

コールバック関数を自分で使用できます (未テストのコード)。

function Location(address, readyCallback) {
  this.geo = new GClientGeocoder();
  this.address = address;
  this.coord = [];
  this.onready = readyCallback;

  this.geo.getLocations(this.address, bind(this, function(result) {
    this.coord[0] = result.Placemark[0].Point.coordinates[1];
    this.coord[1] = result.Placemark[0].Point.coordinates[0];
    if (typeof this.onready == "function") this.onready.apply(this);
  }));
}
Location.prototype.getAddress = function() { return this.address; }
Location.prototype.getLat = function() { return this.coord[0] }
Location.prototype.getLng = function() { return this.coord[1] }

// ... later ...

var l = new Location("Googleplex, Mountain View", function() {
  alert(this.getLat());
});
于 2010-04-19T17:22:49.870 に答える
0

コンストラクターを終了する前にGoogleからの応答を待つことは可能ですか?

このアプローチはお勧めしません。JavaScriptオブジェクトを作成する場合、通常、Googleが応答するまで、数百ミリ秒の間ブロックされるとは思われません。

さらに、GClientGeocoder頻繁にリクエストを実行しようとすると、Googleはを抑制します(ソース)。クライアントが24時間に実行できるリクエスト数にも上限があります。これは、このアプローチを使用して体系的に処理するには複雑になります。ランダムに失敗するJavaScriptオブジェクトがある場合、デバッグの悪夢に簡単に陥る可能性があります。

于 2010-04-19T17:14:51.050 に答える