【问题标题】:Google Maps : function returns undefined value works fine in console.log谷歌地图:函数返回未定义的值在 console.log 中工作正常
【发布时间】:2016-05-11 07:50:11
【问题描述】:

我正在尝试返回 lat , lon 的地址,它在 console.log 上打印数组,但在函数 return 中不起作用

var markers = new Array();
var cityCircles = new Array();
var polycordinates = new Array();
var previousepolygones = new Array();
var infoxboxs = new Array();
function initialize() {
    var mapProp = {
        center:new google.maps.LatLng(44.03121020078675, 23.41763112193103),
        zoom: <?= (isset($zoom) and $zoom != '') ? $zoom : '7' ?>,
        mapTypeId:google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

    console.log(getcountrylatlng("Romania"));
}
function getcountrylatlng(countryname){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode(
        {'address': countryname}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    //var result = results[0].formatted_address;
                    //var city = result.split(" - ");
//console.log(results[0]);
                    return results[0];
                }
            }
        }
    );
}

在console.log 上它返回一个对象,但如果我在上面的函数中返回值,它返回undefined

需要帮助,

【问题讨论】:

标签: javascript google-maps geolocation


【解决方案1】:

您从错误的位置返回控制台日志的重新运行在内部函数中,因此不会返回给调用者函数。

    function getcountrylatlng(countryname){
    var geocoder = new google.maps.Geocoder();
    var myValue;
    geocoder.geocode(
      {'address': countryname}, 
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                //var result = results[0].formatted_address;
                //var city = result.split(" - ");
                //console.log(results[0]);
                //return results[0];
                myValue =  results[0];
            }
        }
    }
  );
    return myValue;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2012-11-08
    • 2016-09-28
    • 2019-01-16
    • 2018-01-02
    相关资源
    最近更新 更多