地理编码在第二次调用时返回(NaN,Nan)

时间:2012-07-03 22:45:12

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

我的javascript函数getLatLng在window.onload调用时效果很好。但是当我使用处理程序调用它时,我从地理编码器获得一个位置(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:已更改,因此警报显示位置值

2 个答案:

答案 0 :(得分:2)

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

此:

window.onload = getLatLng();

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

答案 1 :(得分:0)

你可以试试这个

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