簡體   English   中英

從Google Maps回調函數返回值

[英]Returning value from a google maps callback function

嗨,我正在使用google maps API,我有這么大的代碼,所以我不想用代碼嚇people人基本上這是我需要做的

我有一個javascript(1)函數,當有人單擊按鈕后,我會從HTML調用它,從該函數中我進行一些處理以計算緯度和經度,並調用一個使用緯度和經度的自定義函數,並調用google maps函數。 我需要將google maps回調函數的值傳遞回javascript函數(1)

這是怎么回事

--------------文件為First.html ----------------

<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript">
function docalculation
{
  .....some calculations for latlng......
  var value = get_value(latlng);
}
</script>
<html>
  .....html file....
  <input type="button" value="Create Directions" onClick="docalculation()">
</html>

-------------------文件functions.js ----------------

var return_val;
function get_val(latlng)
{
  geocoder = new google.maps.Geocoder();
  geocoder.geocode({'latLng': latlng}, function(results, status) {

  return_val = (results[0].address_components[i].long_name);
  alert(return_val); //here I get the value that I need in alert
  }

alert (return_val); // here the value suddenly becomes undefined
return val; // hence returns undefined
}

請幫助我,我被困在這里,即使經過2天的谷歌搜索和嘗試我所知道的一切,也找不到解決方案。

任何幫助表示感謝

我正在尋找的最簡單的解決方案是將return_val的值存儲到變量值中的某種方法

謝謝

這是因為geocode()是異步的:它立即返回,但響應到達后立即調用回調函數。 您需要在get_val()接受回調並將值傳遞給此方法,而不是嘗試返回它(這是不可能的):

function get_val(latlng, cb) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        cb(results[0].address_components[i].long_name);
    });
}

用法:

get_value(latlng, function(longName) {
    /* do something */
});

這是您可以使用ThiefMaster的答案在一個呼叫中獲得多個經度的方法。 不是為了膽小的人。

/**
 * @param {string[]} values longitude strings
 * @param cb {function} The callback that will be passed a 
 *        map keyed by latlng strings where each value
 *        is the long name of the street
 */
function getLongNames(values, cb) {
    var returnValues = {};
    var responseCount = 0;
    var geocoder = new google.maps.Geocoder();

    for (var i =0; i < values.length; i++) {
        getSingleName(values[i], function(latLng, longName) {
            returnValues[latLng] = longName;
            responseCount++;
            if (responseCount == values.length) {
                cb(returnValues);
            }
        });
    }

    function getSingleName(latlng, cb) {
        geocoder.geocode({
            'latLng': latlng
        }, function (results, status) {
            cb(latlng, results[0].address_components[i].long_name);
        });
    }
}

你這樣稱呼它

// The callback is the code that is run once all the latLng have been processed
getLongNames(["latLng1", "latLng2","latLng2"], function (valueMap) {
  for (var latLng in valueMap) {
    console.log("Latitude Longitude:" + latLng + " Long Name " + valueMap[latLng]);
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM