谷歌地图通话结束后运行一个功能

时间:2014-02-20 20:43:19

标签: javascript jquery forms google-maps google-maps-api-3

我正在尝试从用户那里收集位置数据,因为他们正在输入表单中的其他详细信息。所以我有一个谷歌地图,用户可以移动标记,但我也有一个输入,他们可以输入一个位置。

当他们点击提交表单时,我想首先对他们输入的位置进行地理编码,并在提交实际发生之前更新表单中隐藏的lat lng输入。

我知道网上有很多信息,但我已阅读大量的教程,但我很难理解或至少将教程应用于我的情况。

因此,当用户点击提交时,我想运行地理编码,只在地理编码完成时才提交表单。

$('.submitButton').click(function () {
    geocode();
            $("#searchForm").submit();//Then submit when geocode finishes
});

地理编码功能

function geocode(){
 geocoder.geocode({
        address: $('#address').val()
    }, function(results, status){
        if(status == google.maps.GeocoderStatus.OK){
         var geoPoint = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
            map.setCenter(geoPoint);
            circle.setCenter(geoPoint);
            marker.setPosition(geoPoint);
           $('#lat').val(geoPoint.lat());
           $('#lng').val(geoPoint.lng());
        } else{
            alert("Can not geolocate this address.");
        }
    });
}

有人可以用简单的javascript虚拟语言向我解释我需要做什么吗?感谢

2 个答案:

答案 0 :(得分:0)

由于地理编码服务是异步的,geocode()几乎会立即返回,$("#searchForm").submit()将提交可用的内容,这将是错误的(旧的或未定义的数据)。

您必须在设置lat / lng值后立即将表单提交调用移至geocode()函数:

    ...
        marker.setPosition(geoPoint);
       $('#lat').val(geoPoint.lat());
       $('#lng').val(geoPoint.lng());

       $("#searchForm").submit();
    } else{
    ...

正如你在评论中所说的,geocode()函数也在其他地方使用,那么你将不得不编写另一个具有类似功能的函数或准备两个不同的回调函数。

答案 1 :(得分:0)

您可以将可选参数传递给地理编码,例如一个将在成功时执行的函数:

$('.submitButton').click(function (e) {
    e.preventDefault();

    //call geocode and pass the desired function as argument
    geocode(function(){$("#searchForm").submit();});

    return false;        
});

function geocode(fnc){
 geocoder.geocode({
        address: $('#address').val()
    }, function(results, status){
        if(status == google.maps.GeocoderStatus.OK){
         var geoPoint = new google.maps.LatLng(results[0].geometry.location.lat(),
                                               results[0].geometry.location.lng());
            map.setCenter(geoPoint);
            circle.setCenter(geoPoint);
            marker.setPosition(geoPoint);
           $('#lat').val(geoPoint.lat());
           $('#lng').val(geoPoint.lng());

           //check  if the fnc-argument is a function, 
           //when it does, execute the function 
           if($.type(fnc)==='function'){
             fnc();
           }

        } else{
            alert("Can not geolocate this address.");
        }
    });
}
相关问题