Hi. I’m trying to create an elevation widget, that shows your elevation in real-time when you tap it. But when I launch the script, navigator.geolocation
is just {}
. Here’s a screenshot.
This is my code:
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"/>
<style>
body {
font-family: -apple-system;
height: 100%;
width: 100%;
}
#container {
position: absolute;
top: 50%;
left: 50%;
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
#title {
text-align: center;
font-size: 70px;
}
#ele {
text-align: center;
font-size: 2em;
}
</style>
<body>
<div id="container">
<div id="title">Current Elevation:</div><br>
<b><div id="ele"></div></b>
</div>
<script>
document.getElementById('ele').innerHTML = JSON.stringify(navigator.geolocation)
</script>
</body>
</html>
I believe you need to call the getCurrentPosition
method of navigator.geolocation
. See this MDN page for example code.
getCurrentPosition
is undefined.
If I add .getCurrentPosition to the end, then I get this.
I don’t know how you added getCurrentPosition
, but it sounds like you are using it like a property. It’s not; it’s a function that takes two functions and an object as its arguments. Here’s an example that works for me:
<html>
<head>
<script>
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
var paragraph = document.getElementById("lat");
var addedText = document.createTextNode(`${crd.latitude}`);
paragraph.appendChild(addedText);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
</script>
<body>
<p id="lat">
Latitude is
</p>
<script>
navigator.geolocation.getCurrentPosition(success, error, options);
</script>
</body>
</html>
Much of the code is taken directly from the MSN I linked to above.
1 Like
I’m just trying to say that getCurrentPosition
doesn’t work because it’s undefined
This is what I get when I try your code.
It may be that getCurrentPosition
won’t work in a widget because it needs permission from the user (again, see the MDN page I linked to above), and I don’t know how widgets handle that.
But if it’s ever going to work, you have to call it as a function with the appropriate arguments. I suggest getting it working as an HTML page so you understand what comes out of the function before converting it to a widget.