0

我在一个表单上有一个提交按钮,上面写着:

<input type="submit" name="add_submit" onclick="return getCoord()" value="Add Location" />

像这样的两个隐藏输入字段:

<input id="long" name="long" type="hidden"  value=""  />
<input id="lat" name="lat" type="hidden"  value="" />

脚本如下所示:

<script type="text/javascript">
    function getCoord() {

        address = document.getElementById('street').value + " " + document.getElementById('city').value + " " + document.getElementById('state').value + " " + document.getElementById('zip').value;
        console.log(address);
        var geocoder = new google.maps.Geocoder();

        geocoder.geocode( { 'address': address}, function(results, status) {

            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();

                document.getElementById('lat').value = latitude;
                document.getElementById('long').value = longitude;


            } 
        });

    } 
</script>

php帖子上:

        $new_long = $database -> escape_value($_POST['long']);
        $new_lat = $database -> escape_value($_POST['lat']);

我希望 JS 函数在表单提交之前填写long和字段的值;lat然后在php帖子上我想获取输入字段——但它返回空白。有错别字,逻辑有问题吗?

注意:我确认该地址已正确记录在 JS 控制台中。

编辑:我实际上得到了一个数据库查询失败错误,但它似乎结果是空白 long lat条目。这些坐标被放入数据库中。

4

1 回答 1

1

Google API 地图是异步的,因此在完成之前您已经提交了表单。在服务器上执行或尝试使用 Observer。

编辑

var geoCompleted = false;

function getCoord() {

    address = document.getElementById('street').value + " " + document.getElementById('city').value + " " + document.getElementById('state').value + " " + document.getElementById('zip').value;
    console.log(address);
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();

            document.getElementById('lat').value = latitude;
            document.getElementById('long').value = longitude;
            geoCompleted = true
            $('#form-id').submit();

        } 
    });
   return geoCompleted
} 
于 2013-08-05T21:11:08.303 回答