繁体   English   中英

javascript function 返回未定义

[英]javascript function is returning undefined

我正在尝试实现谷歌地图,我遇到的问题是,当我调用 function 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;
    }

在萤火虫控制台中,这是我按以下确切顺序获得的 output:

codedAddress 3 = undefined
myLatLng = undefined
codedAddress 1 = (44.0216306, -92.46989919999999)
codedAddress 2 = (44.0216306, -92.46989919999999)

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

geocode是异步的(即它向 Google 的服务器发送请求),因此您需要将回调 function 传递给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);
    });
}

您缺少用于初始化 function 的结束}

以下是我通过 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);
      }
    });
  }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM