I’m experimenting with the Geolocation API in Google Chrome (v13). I’ve produced a simple HTML page to get to grips with the basics:
<html>
<head>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);
function setOptions(geoLoc) {
geoLoc.enableHighAccuracy = true;
geoLoc.timeout = 30;
geoLoc.maximumAge = 0;
}
function doStuff(geoLoc) {
document.getElementById("refreshTimestamp").innerHTML = "Last refresh: " + Date.now();
document.getElementById("latitude").innerHTML = "Latitude: " + geoLoc.coords.latitude;
document.getElementById("longitude").innerHTML = "Longitude: " + geoLoc.coords.longitude;
document.getElementById("altitude").innerHTML = "Altitude: " + geoLoc.coords.altitude;
document.getElementById("accuracy").innerHTML = "Accuracy: " + geoLoc.coords.accuracy;
document.getElementById("altitudeAccuracy").innerHTML = "Altitude Accuracy: " + geoLoc.coords.altitudeAccuracy;
document.getElementById("heading").innerHTML = "Heading: " + geoLoc.coords.heading;
document.getElementById("speed").innerHTML = "Speed: " + geoLoc.coords.speed;
}
function error(geoLoc) {
document.getElementById("error").innerHTML = "ERROR! Code: " + geoLoc.code + "; Message: " + geoLoc.message;
}
</script>
</head>
<body onload="doStuff()">
<p id="refreshTimestamp"></p>
<p id="latitude"></p>
<p id="longitude"></p>
<p id="altitude"></p>
<p id="accuracy"></p>
<p id="altitudeAccuracy"></p>
<p id="heading"></p>
<p id="speed"></p>
<p id="error"></p>
</body>
</html>
Running this page, everything appears fine – the latitude, longitude and accuracy are displayed as expected. However, looking at the Developer Tools Console, I’m presented with an error:
Uncaught TypeError: Cannot read property 'coords' of undefined (geo.html:14)
Debugging it looks like the Position object is undefined at it’s first call – the line dealing with latitude. Yet, there are no errors for any of the further lines. In fact, after the latitude line the Postition object comes into existence.
Things I’ve tried to prevent this error include:
- Moving the getCurrentPosition call to after the callback function declarations
- assign geoLoc.coords to an XY variable as the first line of the doStuff() function (after doing this, it was this part of the code that caused the error)
Am I calling the Position object incorrectly? Is the a Chrome quirk? Is this something to do with the time it’s taking to determine the position?
Thanks,
Chris.
It is undefined because of this:
Maybe you wanted something like this: