I am “attempting” to use JavaScript’s geolocation functions, but I am having issues with, I assume, the way JavaScript works. I have found many examples on how to use the geolocation functions and they all, basically, look like this:
navigator.geolocation.getCurrentPosition(function(position){alert("Your Coordinates:\nLatitude: " + position.coords.latitude + "\nLongitude: " + position.coords.longitude);});
The above code works, but I am trying to do is something like this:
function geoMe(){
var position = navigator.geolocation.getCurrentPosition();
var geoLocationDiv = document.getElementById('geoLocationDiv');
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
geoLocationDiv.innerHTML = latitude + "," + longitude;
}
As you can probably guess, it isn’t working. I have never been good at interpreting code that is all “jammed” together like the example, so I am VERY confused.
In looking at the example code, it looks like there is a function called “getCurrentPosition”. Now, here is where I get lost. It looks like there is a function being passed in as a parameter to getCurrentPosition that has [as a parameter] a parameter called “position”. Where did the “position” parameter come from??? I have seen where a function (without an actual function name) is used as a parameter, but it is REALLY confusing to me. Typically, I do something like:
function functionName(parameter1, parameter2, parameterN){
function body
}
I know it is supposed to be advanced to do stuff like this, but I am a simple man, and I like my code simple, and I like my functions to have names.
So, can anybody out there help me with getting this GeoLocation stuff to work the way I want it to work? And, maybe along the way, explain this bizarre method of JavaScript functions?
Thank you, and have a great day. 🙂
This:
Live demo: http://jsfiddle.net/K6sKe/1/
You have to pass a function object to the
getCurrentPositionmethod. That function acts as the callback function, and is invoked when the user gives permission to access its location. In our case, our callback function is a anonymous function expression. ThegetCurrentPositionmethod is designed to call the callback passing the Position object to it. So, our function expression defines one formal argument (pos) which represents the Position object. Within the callback, we can access that Position object.