javascript函数返回undefined

Cat*_*ish 5 javascript google-maps

我正在尝试实现谷歌地图,我遇到的问题是,当我调用函数getLatLng时,它返回一个未定义的值,我无法弄清楚为什么.

    initialize();

    var map;
    var geocoder;   

    function initialize() {

        geocoder = new google.maps.Geocoder();
        var address = "Rochester, MN";
        var myLatLng = getLatLng(address);
        console.log("myLatLng = "+myLatLng);

    }

    function getLatLng(address) {

        var codedAddress;

        geocoder.geocode({'address': address}, function(results, status) {

            if(status == google.maps.GeocoderStatus.OK) {
                codedAddress = results[0].geometry.location;
                console.log("codedAddress 1 = "+codedAddress);
            } else {
                alert("There was a problem with the map");
            }
            console.log("codedAddress 2 = "+codedAddress);
        });

        console.log("codedAddress 3 = "+codedAddress);
        return codedAddress;
    }
Run Code Online (Sandbox Code Playgroud)

在firebug控制台中,这是我按照这个确切顺序得到的输出:

codedAddress 3 = undefined
myLatLng = undefined
codedAddress 1 = (44.0216306, -92.46989919999999)
codedAddress 2 = (44.0216306, -92.46989919999999)
Run Code Online (Sandbox Code Playgroud)

为什么codedAddress 3和myLatLng首先出现在控制台中?

Emm*_*ett 6

geocode是异步的(即它向Google的服务器发送请求),因此您需要将回调函数传递给getLatLng,而不是立即返回:

function getLatLng(address, callback) {
    var codedAddress;

    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            codedAddress = results[0].geometry.location;
            console.log("codedAddress 1 = "+codedAddress);
        } else {
            alert("There was a problem with the map");
        }
        console.log("codedAddress 2 = "+codedAddress);

        callback(codedAddress);
    });
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ick 1

以下是我通过 Google 地图文档进行的工作:

  var geocoder;
  var map;

  function initialize() {
    geocoder = new google.maps.Geocoder();
    var address = "Rochester, MN";
    var latlng = codeAddress(address);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

这是一个 jsFiddle 来查看它的实际情况。显然,如果需要,您可以更新它以使用 jQuery。