谷歌地图:函数返回未定义的值在console.log中正常工作

时间:2016-05-11 07:50:12

标签: javascript google-maps geolocation

我正在尝试返回lat,lon for address它在console.log上打印数组但在函数返回时不起作用

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

需要帮助,

1 个答案:

答案 0 :(得分:0)

从错误的位置返回控制台日志的重新启动是在内部函数内部,因此不会返回到调用函数。

    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;
}