Geolocation API in Chrome: coord property of Position undefined - javascript

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:
<body onload="doStuff()">
Maybe you wanted something like this:
function init() {
navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);
}
...
<body onload="init()">

Related

TypeError: Functionname is not a function at HTMLButtonElement.onClick

I'm pretty new to Javascript and playing around with it at the moment. However, I can't actually test my code because I get the following error:
Uncaught TypeError: namecaller is not a function
at HTMLButtonElement.onclick (Tools.html:101)
Here is my code:
div id="content">
<script>
function namecaller(){
var a = "scurvy";
var b = "dog";
document.getElementById("namecaller").innerHTML = "You are a " + a + " " + b;
}
</script>
Namecaller</p>
<button type="button" onclick="namecaller()">
You are a...</button>
I have no clue why it doesn't work, looked at other StackOverflow questions and also at the W3 tutorials.
function namecaller() {
var a = "scurvy";
var b = "dog";
document.getElementById("content").innerHTML = "You are a " + a + " " + b;
}
<div id="content"></div>
<button type="button" onclick="namecaller()">
You are a...</button>
The code seems to have a lot of problems like your tags were not in properly written. The tags need to open closed properly. And your script should be in right place so that it gets compiled. Then you have not given an id to any of the elements and try calling them. So here is the working example of how the code should be properly written for bug-free compilation.
Sometimes, it is because your function name override some other functions, especially the system defined ones. For example, I once made a function named as "translate." Later, it reports the exactly same error like yours. The solution is quite simple: just change the function name. For me, I make it "function tranlateIt()" and hence the problem is gone forever.
This is not the solution to your particular problem (the accepted answer answers it neatly), but the following might be the useful reference to the future readers (it happened very often to me).
The same error you provided happened to me, when I first declared a variable and then the function with the same name. For example:
var example = 5;
function example() {
console.log("The function just got executed!");
}
<button onclick="example()">Click me!</button>
You have not defined the id of paragraph for which you are changing the value. Just define the Id of paragraph as namecaller and it will work.
See the code below:
<div id="content">
<script>
function namecaller(){
var a = "scurvy";
var b = "dog";
document.getElementById("namecaller").innerHTML = "You are a " + a + " " + b;
}
</script>
<p id = "namecaller">Namecaller</p>
<button type="button" onclick="namecaller()">
You are a...</button
// Write this function code in inside <script> tag or in index.js file
function namecaller() {
var a = "scurvy";
var b = "dog";
document.getElementById("content").innerHTML = "You are a " + a + " " + b;
}
.content{
background-color: bisque;
}
.button{
color: white;
background-color: blue;
}
<!-- Write this code in inside the <body> tag in your index.html file -->
<!-- I added little CSS -->
<div class="content" id="content"></div>
<button class="button" type="button" onclick="namecaller()">You are a...</button>
Your div tag is not properly written. all tags need to open and close properly. You have to give the proper id to any HTML element and then call the function. Run the code snippet.

Javascript: The value of the property is null or undefined, not a Function object

Okay, Stumped. I just use code to show possibilities to customers (am self-employed).
Trying to show get-selected-text-from-IE11-Browser. Don't need cross-Browser and expert stuff just yet (if customer goes ahead).
Have tried to write a javascript function to get the selected text from the browser. This has worked fine when called direct (put function into Console via F12 facility) and this returns the selection. But when calling from Context Menu HTM script it fails with the mentioned error. The code to get the selected text comes from another context menu script that works fine when all the code is in the one HTM script (cmGoogleMapSelection_1.htm). I was just trying to be a little more efficient with reuse and learn a little more myself. I will return to in-line code if I can't resolve the issue (with help from your marvellous selves).
Keep getting the following error reported in the HTM script :
The value of the property 'myGetSelectedText' is null or undefined, not a Function object.
Have read a number of posts and tried to ensure that I have covered their suggestions. Still stumped, any help appreciated.
The code, first the 'function', then the 'script'; both script file and function file are in the same local file folder (please excuse the Debug code - gulp):
fn_myGetSelectedText.js:
function myGetSelectedText(pDefault) {
var zDbug = 1;
var zDbugMsg = "Debug: ";
var zSelection = "";
if (zDbug) {alert(zDbugMsg + "Starting Function 'myGetSelectedText' from fn_myGetSelectedText.js");}
zSelection = "" + window.getSelection().toString();
if (zDbug) {alert(zDbugMsg + " Selection= '" + zSelection + "'");}
if (zSelection == "") {
zSelection = pDefault;
alert(zDbugMsg + "Null selection, using: " + zDefault + " !");
}
return zSelection;
}//EndOf: Function -----
cmGoogleMapSelection_2.htm:
<!-- saved from url=(0016)http://localhost -->
<script type="text/javascript" src="fn_myGetSelectedText.js"></script>
<script type="text/javascript">
//- zDbug: 0 = false = no messages; 1 = true = show messages -----
var zDbug = 1;
var zDbugMsg = "Debug: ";
if (zDbug) {alert(zDbugMsg + "Starting cmGoogleMap_Selection2.htm V14");}
//- Google Maps stem URL & default location -----
var zMaps = "http://maps.google.co.uk/maps?hl=en&q=";
var zDefault = "+London";
var zSelection = myGetSelectedText(zDefault); //- Error occurs here <<<<<<<<<<<
if (zDbug) {alert(zDbugMsg + " Selection= '" + zSelection + "'");}
//- Build Maps URL -----
var zGo = zMaps + zSelection;
//- Open new Maps window -----
if (zDbug) {alert(zDbugMsg + "Issuing Window.Open on URL: " + zGo);}
window.open(zGo, "_blank");
//- Close this window -----
window.close()
</script>
<!-- Just to put something into the main code window so I know which one it is -->
<style>
p {font-family: "Lucida Console"; color: Red; font-size: 16pt;}
</style>
<p> >>-- Map Selected Text Function --<< <br>
>>-- . . 'myGetSelectedText' . . --<< </p>
I am hoping like heck that I haven't missed a bracket somewhere - embarrassing!
Other stuff: Windows 10 Pro (fully updated); 64 bit IE11; just javascript; Compatibility View OFF; Registry Keys/Values pointing where they should (cloned from working version).
While browser downloads fn_myGetSelectedText.js file from the internet, it does not stop parsing other code in your HTML. There's concurrent downloading of assets going on while browser parses the DOM.
when browser reaches this line var zSelection = myGetSelectedText(); it does not see myGetSelectedText defined on the window object at that moment thus throws out error.
What you want to do is wrap your script/code in your HTML into DOMContentLoaded event and call it once page load completes.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
</script>
reference: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
My guess would be that in your called function, pDefault is undefined, because you aren't passing a variable when you do the call.
So, this line: var zSelection = myGetSelectedText();
Should become: var zSelection = myGetSelectedText(zDefault);
HTH,
Jim

browser feature detection error using (navigator.geoloction)

I have written a script to check if my browser has features. The following script is producing an error:
<!DOCTYPE HTML>
<html>
<head>
<title id="title"> code Issues </title>
</head>
<body>
//=================== testing the feature detection method by using geolocation =======================//
function geosuccess(position)
{
var cords = position.cords;
var latitude = position.latitude;
var longitude = postion.longitude;
var message = "You're at " + latitude + ", " + longitude
alert(message);
}
function geoError(errorObj)
{
alert(errorObj.message);
}
if(typeof navigator.geolocation != "undefined")
{
console.log("inside geolocation");
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
}
else
{
alert("thos page uses Geolocation and your browser doesn't support it");
}
//=================== End of testing the feature detection method by using geolocation =======================//
</script>
<h1>List Publishers Ltd.</h1>
<div class="book">
<h2>Sprout.</h2>
<p>A book by J. Daniel Bedford</p>
Read now.
</div>
</body>
</html>
If I run this I get an error that geosuccess isundefined.
I tried to debug the script and i can see it is not able to detect the function geoSuccess(position).
I hope I am not missing an object oriented concept and the error is something related to the browser maybe.
First, your code lacks an opening <script> tag but I'll assume that's just a mistake.
Second, your code defines the function as geosuccess but you pass geoSuccess to getCurrentPosition. Please check wheter the cases match in your code.

NaN error - Dealing with strings and integers

Making my own version of cookie clicker for the lols at school, having some problems;
<!DOCTYPE html>
<html>
<head>
<title>Patrick Clicker</title>
<script>
var patricks = parseInt(localStorage.getItem("patrickcount"));
function increment(n) {
localStorage.setItem("patrickcount", patricks + n);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
</script>
</head>
<body>
<img src="patrick.jpg" onclick="increment(1)">
<p id="patrickcounter">
Patricks: 0
</p>
</body>
</html>
When I click my face, it says "Patricks: NaN"
I know what NaN means, but I don't know why the error is being caused.
Any help would be appreciated.
It won't work initially because you don't have a value at first in localStorage.
You can do this :
var patricks = parseInt(localStorage.getItem("patrickcount"))||0;
Do you intentionally display the value before increment ? If that's not your intent, change your function to
function increment(n) {
patricks += n;
localStorage.setItem("patrickcount", patricks);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
If you want the page to show the right value right before you click, add this at the end of the body :
<script>increment(0)</script>

function write(message) not working

I'm doing the PluralSight JavaScript Fundamentals course and he enters this code into the JavaScript window of jsbin (jsbin.com)
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick";
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
and when he Previews it writes out the types and values. The video is a year old and now jsbin has a Render (not Preview) button. When I enter the above code and Render I get a blank screen.
I tried pasting the code into an .html file
<!DOCTYPE html>
<html>
<head>
<!--<meta charset=utf-8 />-->
<title>JS Test</title>
</head>
<body>
<p id="hello">Hello World</p>
<script>
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick"';
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
</script>
</body>
</html>
and then opened the file in IE9, and the latest version of Chrome, Firefox, Safari and Opera (my OS is Win7 Ult). They all display Hello World and nothing else. I'm probably missing something really simple here, can someone help me out?
You don't have a message element. Change the #hello element to #message.
<p id="hello">Hello World</p>
To this
<p id="message">Hello World</p>
This is what is needed for the getElementById code to have a place to print your output. Without an element having the requested ID, nothing will turn up, and hence nothing will be printed.
You have a syntax error as well:
/* v----- This little guy here doesn't belong. */
var streetName = "Brunswick"';
Note the umatched single quote at the end of this string. Remove that and you should be good to go:

Categories

Resources