My javascript function getLatLng works great when called by the window.onload. But when I use the handler to call it I get a position (NaN, NaN) from the geocoder.
Why doesn’t it work when I click the submit button but works great from the 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>
EDIT: Fixed typo in the handler pointing to the wrong form
EDIT 2: Fixed more typos
EDIT 3: Changed so alert shows the value of position
your getLatLng-function will never work as expected, it will never return the result of the geocoding, because geocoding is an asynchronous request.
This:
…will call the function(not onload, immediately), and the function will execute the instructions, but will also return (NaN, NaN)