如何从地理编码调用中设置结果值?

时间:2018-02-13 17:49:53

标签: javascript geolocation

您好我试图将用户当前位置存储到MONGODB,但我无法将结果值设置为 global_variable

尝试以下代码

Var global_variable;

getCurrentAddress(location) {
    this.currgeocoder.geocode({
      'location': location
    }, function (results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        console.log("Results:::" + JSON.stringify(results[0]));
        **global_variable = results;**

      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

global_variable undefined

你可以请一位帮助我的人。在此先感谢!!

1 个答案:

答案 0 :(得分:0)

以下是一个使您的地址调用基于承诺的示例,以便您可以从API调用中获取数据,以便能够传递给MongoDB。当然另一个选择是让你的MongoDB调用回调到geocode函数本身:

getCurrentAddress = function(location, currgeocoder) {
    return new Promise(function(resolve, reject) {
        currgeocoder.geocode({
            'location': location
        }, function (results, status) {

            if (status == google.maps.GeocoderStatus.OK) {
                console.log("Results:::" + JSON.stringify(results[0]));
                resolve(results)

            } else {
                reject('Geocode was not successful for the following reason: ' 
                + status);
            }
        })
    });
};

getCurrentAddress(/*some location data*/, this.currgeocoder)
    .then(function(results) { console.log(results); //pass to MongoDB here})
    .catch(function(error) { console.error(error); //handle error})