简体   繁体   English

从Google Maps回调函数返回值

[英]Returning value from a google maps callback function

Hi I am working with google maps API I have this huge code, so I dont want to scare away people with code Basically this is what I need to do 嗨,我正在使用google maps API,我有这么大的代码,所以我不想用代码吓people人基本上这是我需要做的

I have a javascript(1) function that I call from Html after someone clicks a button, from that function I do some processing to calculate the latitudes and longitudes and call a custom function which uses the latitudes and longitudes and calls a google maps function. 我有一个javascript(1)函数,当有人单击按钮后,我会从HTML调用它,从该函数中我进行一些处理以计算纬度和经度,并调用一个使用纬度和经度的自定义函数,并调用google maps函数。 I need to pass that the value from the google maps call back function back to the javascript function (1) 我需要将google maps回调函数的值传递回javascript函数(1)

here is how it goes 这是怎么回事

--------------File First.html---------------- --------------文件为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>

-------------------file functions.js---------------- -------------------文件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
}

Please help I am stuck here and could not find a solution even after 2 days of googling and trying everything I know. 请帮助我,我被困在这里,即使经过2天的谷歌搜索和尝试我所知道的一切,也找不到解决方案。

any help appreciated thanks 任何帮助表示感谢

The simplest solution that I am looking for would be some way to store the value of return_val into variable value 我正在寻找的最简单的解决方案是将return_val的值存储到变量值中的某种方法

Thanks 谢谢

That's because geocode() is asynchronous: it returns immediately but the callback function is invoked as soon as the response arrives. 这是因为geocode()是异步的:它立即返回,但响应到达后立即调用回调函数。 You need to accept a callback in get_val() and pass the value to this method instead of trying to return it (it's impossible): 您需要在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);
    });
}

Usage: 用法:

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

Here's how you could use ThiefMaster's answer to get multiple longitudes in one call. 这是您可以使用ThiefMaster的答案在一个呼叫中获得多个经度的方法。 Not for the faint of heart. 不是为了胆小的人。

/**
 * @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);
        });
    }
}

And you call it like this 你这样称呼它

// 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