2

ので、私は持っています

  function find_coord(lat, lng) {
              var smart_loc;
      var latlng = new google.maps.LatLng(lat, lng);
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'latLng': latlng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                smart_loc = new smart_loc_obj(results);
            } else {
                smart_loc = null;
            }
        });

        return smart_loc;
}

smart_loc変数/オブジェクトを返したいのですが、関数のスコープ(results、status)がfind_coord関数で宣言されたsmart_locに到達しないため、常にnullになります。では、関数内の変数(結果、ステータス)をどのように取得しますか?

4

1 に答える 1

0

できるよ:

var smart_loc;

function find_coord(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'latLng': latlng }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            smart_loc = new smart_loc_obj(results);
        } else {
            smart_loc = null;
        }
    });
}

または、 smart_loc が変更されたときに関数を実行する必要がある場合:

function find_coord(lat, lng, cb) {
          var smart_loc;
  var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'latLng': latlng }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            smart_loc = new smart_loc_obj(results);
        } else {
            smart_loc = null;
        }

        cb(smart_loc);
    });
}

次に呼び出します。

find_coord(lat, lng, function (smart_loc) {
    //
    // YOUR CODE WITH 'smart_loc' HERE
    //
});
于 2012-01-02T04:15:44.203 に答える