当前坐标返回undefined

时间:2014-10-23 18:38:49

标签: javascript

我尝试使用getLocation函数获取当前位置坐标,并在将来使用它们进行距离计算。运行以下代码后,我得到了未定义。

<script type="text/javascript">
var currentLatitude;
var currentLongitude;

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getCoordinates);
    } else { 
        document.getElementById("asdfsdafsdaf").innerHTML = "Geolocation is not supported by this browser.";
    }
}

function getCoordinates(position) {
    currentLatitude = position.coords.latitude;
    currentLongitude = position.coords.longitude;   
}

var xhr = new XMLHttpRequest();
xhr.open("POST", "rsvpButton.php", true);
var formData = new FormData();
    formData.append("userID", 100100);
xhr.send(formData);

xhr.onload=function(){
    getLocation();
    alert("1"+currentLongitude+" and "+currentLatitude);
    //some other codes to display the page
    //...
}
</script>

我以为我把这两个变量放在了错误的地方,但经过多次尝试后它仍无法正常工作。有什么帮助吗?提前谢谢。

更新:我试图将底部代码放入回调函数中,但整个页面都消失了。

2 个答案:

答案 0 :(得分:0)

getCurrentPosition接受回调,因为它是异步的。在此处阅读更多内容:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition

尝试将alert放入回调中:

<script type="text/javascript">
var currentLatitude;
var currentLongitude;

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(callback);
    } else { 
        document.getElementById("asdfsdafsdaf").innerHTML = "Geolocation is not supported by this browser.";
    }
}

var xhr = new XMLHttpRequest();
xhr.open("POST", "rsvpButton.php", true);
var formData = new FormData();
    formData.append("userID", 100100);
xhr.send(formData);

xhr.onload=function(){
    getLocation(function (position) {
        var currentLatitude = position.coords.latitude;
        var currentLongitude = position.coords.longitude;   

        alert("1"+currentLongitude+" and "+currentLatitude);
        //some other codes to display the page
        //...
    });

}
</script>

答案 1 :(得分:-1)

试试这个:

var currentLatitude;
var currentLongitude;

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getCoordinates);
    } else { 
        alert("4");
    }
}

function getCoordinates(position) {
    currentLatitude = position.coords.latitude;
    currentLongitude = position.coords.longitude; 

    // now latitude and longitude are available
    alert(currentLongitude+" and "+currentLatitude);
}

// actually call the function getLocation
getLocation();


这是 DEMO