我试着尽可能简单地描述我的问题。 当我提交表单时,我需要调用另一个函数。我试过onSubmit,但遗憾的是它无法正常工作,因为我需要调用的功能是Google Maps API从文本框中获取坐标,用户正在选择位置..函数永远不会被调用,或者看起来它也被调用了晚了..所以我试过了:
<input type="button" value="Search" name="submitBtn" id="subBtn1" onclick="onSubmit1();">
和onSubmit1()函数如下:
function onSubmit1 () {
codeAddress();
// document.forms["searchForm"].submit();
}
单击按钮后,该功能正常工作.. codeAddress从谷歌服务器获取经度和经度,并将它们预填充到我的searchForm文本框中。
但是,如果我删除doble斜杠并想要提交表单,则会发生以下情况:
表单已提交,但纬度和经度始终为空字符串..
任何想法..是否有可能,onSubmit1函数中的第二行不等待goole完成它的工作?
感谢您的任何提示..
请知道,如果我自己设置坐标并提交表格,那么表格及其所有功能都能完美运作..没有问题
修改
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode(
{ 'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
document.getElementById("my-lat").value = lat;
document.getElementById("my-lng").value = lng;
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
答案 0 :(得分:0)
您的问题是codeAddress是异步的(以及地理编码器对象的地理编码方法),因此立即返回。
您必须做的只是在异步回调中提交表单:
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode(
{ 'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
document.getElementById("my-lat").value = lat;
document.getElementById("my-lng").value = lng;
//now submit form
document.forms["searchForm"].submit();
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}