Google map 集成中的 Javascript 错误

标签 javascript google-maps

我正在尝试让以下代码工作(看起来非常简单,但它并不像预期的那样工作)

请帮助我:

function findLocationAddress(myLatLng)
    {
        var formattedAddress='MY HOUSE ADDRESS';

        geocoder.geocode({'latLng': myLatLng},function(results, status) 
        {
            if (status == google.maps.GeocoderStatus.OK) 
            {
                if (results[1]) 
                {
                    formattedAddress = results[1].formatted_address;
                }
            } 
        });

        alert(formattedAddress);
        return formattedAddress;
    }

上面的函数应该返回formattedAddress的新值,但它仍然返回“MY HOUSE ADDRESS”

非常感谢任何帮助。

最佳答案

这里的问题是 geocoder.geocode 请求是异步的,而您正在同步返回您的值。尝试这样的事情:

function findLocationAddress(myLatLng)
    {
    var formattedAddress='MY HOUSE ADDRESS';

      geocoder.geocode({'latLng': myLatLng},function(results, status) 
      {
        if (status == google.maps.GeocoderStatus.OK) 
        {
          if (results[1]) 
          {
          formattedAddress = results[1].formatted_address;
          alert(formattedAddress);
          // then do what you want (e.g. call a function) here
          // e.g. doMyNextThing(formattedAddress);
          }
        } 
      });
    }

以上代码示例已测试且正常工作。

如果您愿意,您还可以使用回调函数来定义找到地址后会发生什么(这将使该函数更加可重用)

function findLocationAddress(myLatLng, callback)
    {
    var formattedAddress='MY HOUSE ADDRESS';

      geocoder.geocode({'latLng': myLatLng},function(results, status) 
      {
        if (status == google.maps.GeocoderStatus.OK) 
        {
          if (results[1]) 
          {
          formattedAddress = results[1].formatted_address;
          callback(formattedAddress);
          }
        } 
      });
    }

findLocationAddress(myLatLng, function(formattedAddress){
  // Do what you want with the result here
});

这可能是显而易见的,但还要注意 results[1] 将为您提供第二个结果,因为数组索引从 0 开始(这可能是预期的行为)

关于Google map 集成中的 Javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4143049/

相关文章:

javascript - 谷歌放置自动完成小部件为每个请求生成一个新的 session key

Android:谷歌地图 - 始终在 map 加载时显示 map 工具栏

javascript - 删除 iframe 链接中的目标属性

javascript - 在 JS 对象中异步加载数据

javascript - 使用正则表达式替换javascript中字符串中的多个值

javascript - html中的隐藏文本框

angularjs - 根据AngularJS中选择框中选定的城市绘制 map

javascript - jQuery first() 未按预期工作 - 返回容器

google-maps - 相机动画和用户相机移动之间的区别

node.js - google api获取特定用户的google页面评论