2012-07-03 4 views
0

내 JavaScript 함수 인 getLatLng는 window.onload에서 호출 할 때 훌륭하게 작동합니다. 그러나 핸들러를 사용하여 호출하면 지오 코더에서 위치 (NaN, NaN)를 얻습니다.지오 코드는 두 번째 호출에서 (NaN, Nan)을 반환합니다.

제출 버튼을 클릭해도 작동하지 않지만 window.onload에서 훌륭하게 작동하는 이유는 무엇입니까? 고정 더 오타

편집 : 3 :

<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> 

편집 :

편집이 잘못된 형태를 가리키는 핸들러에 고정 오타 때문에 경고 변경은

+0

는 무엇 요소의 비수 (NaN, NaN의) 지시를 실행뿐만 아니라 반환합니다' 주소? 지오 코더로 전달할 값을 포함해야하지만 어디에도 표시되지 않습니다. –

+0

@AndrewLeach 죄송합니다. 방금 변경되었으므로 죄송합니다. 텍스트를 HTML 파일에 넣으면 api 키를 자신의 것으로 변경하여 작동시켜야하며 position 값을 팝업합니다. 감사! – ChickenFur

답변

2

getLatLng-function은 예상대로 작동하지 않습니다. geocoding은 비동기 요청이므로 r은 지오 코딩의 결과를 리턴합니다.

이 :

window.onload = getLatLng(); 

... 기능 (안 온로드, 즉시)를 호출하며, 함수가

0

당신이 할 수있는 위치의 값을 보여줍니다 시도해보십시오

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