-1

我正在尝试将在W3Schools上找到的这个函数的经度和纬度设置为一个变量(我们只是说yand z),然后我需要显示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>

例如,如果我的经度 ( y) 是 10,纬度 ( z) 是 15,那么它会显示

y=10
z=15
4

2 回答 2

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>
于 2021-08-10T04:54:20.613 回答
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>

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

于 2017-04-18T20:39:44.343 回答