0

我正在尝试在我的网页中嵌入带有标记的谷歌地图。但是如果我使用以下代码,我会收到一条未定义的警报消息

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            //alert(results[0].geometry.location);
            return (results[0].geometry.location);
        } 
    });
}

function initialize() {
    default_location = codeAddress("<?php echo $location;?>");
    alert(default_location);
}

取而代之的是,如果我在下面的 codeAdress 函数中执行警报,则它正确显示了纬度和经度。

var infowindow = null;
var geocoder;
$(document).ready(function () { initialize();  });

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert(results[0].geometry.location);

        } 
    });
}

function initialize() {
    codeAddress("<?php echo $location;?>");
}

有人可以确定问题所在吗?我是 javascripts 的新手

4

3 回答 3

3

地理编码器调用是异步的,这意味着它需要一些时间才能返回,并且不遵循所写的顺序。这也意味着在第一位,函数在到达您的return (results[0].geometry.location)语句之前完成。所以alert没有什么可展示的。

除了在geocode请求中插入语句之外,您还可以编写回调模式来分离脚本逻辑。将位置作为参数传递的回调在geocode调用成功时执行。

http://jsfiddle.net/3KXKm/

  var infowindow = null;
  var geocoder = new google.maps.Geocoder();

  $(document).ready(function () { initialize();  });

  function codeAddress(address, callback) {
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        callback(results[0].geometry.location);
      } 
    });
  }

  function initialize() {
    codeAddress("Chicago, IL", function(default_location) {
      var map = new google.maps.Map(document.getElementById("map_canvas"),
        { center: default_location,
        zoom: 3, mapTypeId: google.maps.MapTypeId.ROADMAP });

      locations = ["Los Angeles", "Davis", "Truth or Consequences",
        "Ann Arbor", "Massachusetts"];

      for (var i = 0; i < locations.length; i++) {
        codeAddress(locations[i], function(latLng) {
          new google.maps.Marker({map:map, position:latLng});
        });
      }
    });
  }
于 2012-05-24T18:44:08.280 回答
0

地理编码不会立即返回结果。这就是为什么您在代码的第一个版本中什么也得不到。因此,如果您想对地理编码结果做一些事情,您应该在回调函数中进行,就像在您的代码的第二个版本中一样。

于 2012-05-24T18:34:43.730 回答
0

您的

return (results[0].geography.location);

只返回嵌套函数的值,不返回 codeAddress 函数的值。也许如果你告诉我们你想做什么,我们可以提供帮助。

于 2012-05-24T18:36:27.067 回答