0

ウェブページにマーカー付きの Google マップを埋め込もうとしています。しかし、次のコードを使用すると、未定義の警告メッセージが表示されます

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //alert(results[0].geometry.location);
            return (results[0].geometry.location);
        } 
    });
}

function initialize() {
    default_location = codeAddress("<?php echo $location;?>");
    alert(default_location);
}

その代わりに、以下のように codeAdress 関数でアラートを実行している場合、緯度と経度が正しく表示されます。

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert(results[0].geometry.location);

        } 
    });
}

function initialize() {
    codeAddress("<?php echo $location;?>");
}

誰かが問題を特定できますか? 私はJavaScriptが初めてです

4

3 に答える 3

3

ジオコーダーの呼び出しは非同期です。つまり、戻るのに時間がかかり、記述された順序に従わないことを意味します。また、最初のビットでは、関数がreturn (results[0].geometry.location)ステートメントに到達する前に終了することも意味します。したがってalert、表示するものは何もありません。

リクエスト内にステートメントを挿入する以外geocodeに、スクリプトロジックを分離するためのコールバックパターンを記述できます。場所をパラメーターとして渡すコールバックは、geocode呼び出しが成功したときに実行されます。

http://jsfiddle.net/3KXKm/

  var infowindow = null;
  var geocoder = new google.maps.Geocoder();

  $(document).ready(function () { initialize();  });

  function codeAddress(address, callback) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        callback(results[0].geometry.location);
      } 
    });
  }

  function initialize() {
    codeAddress("Chicago, IL", function(default_location) {
      var map = new google.maps.Map(document.getElementById("map_canvas"),
        { center: default_location,
        zoom: 3, mapTypeId: google.maps.MapTypeId.ROADMAP });

      locations = ["Los Angeles", "Davis", "Truth or Consequences",
        "Ann Arbor", "Massachusetts"];

      for (var i = 0; i < locations.length; i++) {
        codeAddress(locations[i], function(latLng) {
          new google.maps.Marker({map:map, position:latLng});
        });
      }
    });
  }
于 2012-05-24T18:44:08.280 に答える
0

geocode はすぐに結果を返しません。これが、コードの最初のバージョンで何も得られない理由です。したがって、ジオコードの結果で何かをしたい場合は、コードの 2 番目のバージョンのように、コールバック関数で実行する必要があります。

于 2012-05-24T18:34:43.730 に答える
0

君の

return (results[0].geography.location);

codeAddress 関数の値ではなく、ネストされた関数の値のみを返します。何をしようとしているのか教えていただければ、私たちがお手伝いできるかもしれません。

于 2012-05-24T18:36:27.067 に答える