将 Geolocation 的 getCurrentPosition 中的经纬度分配给变量
Assign the latitude and longitude from Geolocation's getCurrentPosition to variables
我正在尝试将在 W3Schools 上找到的此函数的经度和纬度设置为一个变量(我们只说 y
和 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
你的意思是这样?
<!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>
您不必像我一样在全局级别声明值,但认为它可能有用,因此您可以在函数外部访问它。
<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>
我正在尝试将在 W3Schools 上找到的此函数的经度和纬度设置为一个变量(我们只说 y
和 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
你的意思是这样?
<!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>
您不必像我一样在全局级别声明值,但认为它可能有用,因此您可以在函数外部访问它。
<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>