将Geolocation的getCurrentPosition中的纬度和经度分配给变量

时间:2017-04-18 20:32:53

标签: javascript w3c-geolocation

我正在尝试将W3Schools上找到的此函数的经度和纬度设置为变量(让我们只说yz),然后我需要显示{{1 }}:

y

例如,如果我的经度(<script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script>)为10且纬度(y)为15,则会显示

z

2 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

<!DOCTYPE html>
<html>
<body>

<p>Coords will load momentarily.</p>



<p id="demo"></p>

<script>
var x = document.getElementById("demo");

var lat = '';
var lon = '';

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    lat = position.coords.latitude;
    lon = position.coords.longitude;
    x.innerHTML = lat + " " + lon;


}

getLocation();
</script>

</body>
</html>

您不必像我一样在全局级别声明值,但认为它可能有用,因此您可以在函数外部访问它。

答案 1 :(得分:0)

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "y= " + position.coords.latitude + 
    "<br>z= " + position.coords.longitude; 
}
</script>