【问题标题】:geocode returns (NaN, Nan) on the second call地理编码在第二次调用时返回 (NaN, Nan)
【发布时间】:2012-07-03 22:45:12
【问题描述】:

当被 window.onload 调用时,我的 javascript 函数 getLatLng 工作得很好。但是当我使用处理程序调用它时,我会从地理编码器中获得一个位置 (NaN, NaN)。

为什么当我点击提交按钮时它不起作用,但在 window.onload 中却很好用?

<script type="text/javascript"
  src="http://maps.googleapis.com/maps/api/js?key=MYSECRETKEYHERE&sensor=false">
</script>    

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>


<form id="update_info" method="post" action="{{upload_url}}" enctyp="multipart/form-data">
<input name="address" id="address" type="text" value="100 W Main St Lehi, UT"/>
<input name="latlng" id = "latlng" type="text" value=""/>
<input name="update_reseller_button" id="update_reseller_button" type="submit">
</form>


<script>

function getLatLng()
{
    var geocoder = new google.maps.Geocoder();

    var theaddress = document.getElementById('address').value;
    var position = new google.maps.LatLng();

    geocoder.geocode({'address': theaddress}, function(results, status
      )
    {                       
        position = results[0].geometry.location;                  
        document.getElementById('latlng').value = position.toString();
    });
    return position;
}

$('#update_info').submit(function()

  {
    alert('The Position is: ' +  getLatLng().toString());
    return true;
  });

  window.onload = getLatLng();

</script>

编辑:修复了处理程序中指向错误表单的错字

编辑 2:修正了更多错别字

编辑 3:已更改,因此警报显示位置的值

【问题讨论】:

  • address 是什么元素?它应该包含要传递给地理编码器的值,但不会出现在任何地方。
  • @AndrewLeach 抱歉,我刚刚更改了它,所以它现在可以正常工作了。如果您将文本放在 html 文件中,请将 api 键更改为您自己的,它应该可以工作并弹出位置的值。谢谢!

标签: javascript html google-app-engine google-maps-api-3


【解决方案1】:

您的 getLatLng 函数永远不会按预期工作,它永远不会返回地理编码的结果,因为地理编码是一个异步请求。

这个:

window.onload = getLatLng();

...将调用函数(不是onload,立即),函数将执行指令,但也会返回(NaN,NaN)

【讨论】:

    【解决方案2】:

    你可以试试这个

    if (status == google.maps.GeocoderStatus.OK) {
        document.getElementById('latlng').value=results[0].geometry.location.lat()+", "+results[0].geometry.location.lng();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 2017-08-12
      • 1970-01-01
      • 2019-01-17
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 2020-10-01
      相关资源
      最近更新 更多