在另一个函数中使用地理位置

时间:2013-12-23 22:56:39

标签: javascript jquery ajax google-maps

我有一个脚本,允许用户查看通信机柜的位置。我试图让html5将经度和经度传递给php脚本(geo.php),用地图坐标更新数据库中的记录,但不断出现错误:

  

ReferenceError:找不到变量:pos

这是我的代码。请帮助我获得由ajax调用的链接中出现的纬度和经度:

function getLocation() {
            navigator.geolocation.getCurrentPosition(function(pos)
            {
                var lat = pos.coords.latitude;
                var lng = pos.coords.longitude;

            });
 }

function saveLocation(building, commNo) {
            getLocation();
            var latitude = lat;
            var longitude = lng;
            alert(latitude + longitude);
            document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
            var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;

var req = getXMLHTTP();
            if (req) { 

                req.onreadystatechange = function() {
                    if (req.readyState == 4) {
                        // only if "OK"
                        if (req.status == 200) {
                            getMap(exchangeName, PCP);
                        } else {
                            alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                        }
                    }
                }
                req.open("GET", strURL, true);
                req.send(null);
            }

        }

1 个答案:

答案 0 :(得分:1)

地理位置API是异步的,就像你的ajax调用一样,所以你必须等待结果返回,即使你必须等待异步调用,变量只能在定义它们的范围内使用

function getLocation(callback) {
    navigator.geolocation.getCurrentPosition(function (pos) {
        callback(pos.coords.latitude, pos.coords.longitude);
    });
}

function saveLocation(building, commNo) {
    getLocation(function(latitude, longitude) {
        document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
        var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;

        var req = getXMLHTTP();
        if (req) {

            req.onreadystatechange = function () {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {
                        getMap(exchangeName, PCP);
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }
            }
            req.open("GET", strURL, true);
            req.send(null);
        }
    });
}