0

I'm really new to Javascript, and I'm trying to jump into it.

I want to have a script get geolocation data and pass it to a variable, and then have the information displayed in an alert.

I have a jsFiddle here: http://jsfiddle.net/yJrtR/

When I run it, I get an "undefined" in the alert box. Can someone help me with this?

Here is my code:

    function lat() {

navigator.geolocation.getCurrentPosition(function (position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
}, function (error) {
    console.log("Something went wrong: ", error);
});
    }

    function alert() {
var lat="";
var lon="";
lat();
alert("lat + lon");
    }

1 Answer 1

2

There are several weird things in your code. Your fiddle is set to run onLoad, which means the functions you defined in your JavaScript won't be available globally - they'll be defined in the window.onload handler...which doesn't code outside of that to access them (especially inline event handlers). This is a perfect example of why not to use inline event handlers (even though the problem is really because of the jsFiddle settings).

So that means, when you call alert(); in your button's inline click handler, it calls the native window.alert() function, which brings up a dialog window. Since you pass nothing to it, it shows undefined. It's not actually calling your created alert function.

Also, since the getCurrentPosition method seems to be asynchronous, you should pass a callback function to lat, so that you can call it when it gets position.

Try this:

function lat(callback) {
    navigator.geolocation.getCurrentPosition(function (position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        callback.call(null, lat, lon);
    }, function (error) {
        console.log("Something went wrong: ", error);
    });
}

function getPosition() {
    lat(function (latitude, longitude) {
        alert("lat: " + latitude + ", lon: " + longitude);
    });
}

http://jsfiddle.net/yJrtR/1/

UPDATE:

Per your comment, if you'd like it to be shown "live", you can use something like this:

window.onload = function () {
    var latElement = document.getElementById("lat"),
        lonElement = document.getElementById("lon"),
        lastUpdatedElement = document.getElementById("last_updated"),
        getPositionOptions = {
            enableHighAccuracy: false,
            timeout: 10000,
            maximumAge: 0
        },
        getPos = function () {
            console.log("getPos function called");
            navigator.geolocation.getCurrentPosition(function (position) {
                console.log("Successfully retrieved position: ", position);
                var coords = position.coords;

                latElement.innerHTML = coords.latitude;
                lonElement.innerHTML = coords.longitude;

                lastUpdatedElement.innerHTML = new Date(position.timestamp);
                setTimeout(getPos, 5000);
            }, function (error) {
                console.log("Something went wrong retrieving position: ", error);
                setTimeout(getPos, 5000);
            }, getPositionOptions);
        };

    getPos();
};

with the following HTML (just to "simulate" the dialog you speak of):

<div id="dialog">
    <div>Your latitude is: <span id="lat"></span></div>
    <div>Your longitude is: <span id="lon"></span></div>
    <div>Last Updated: <small id="last_updated"></small></div>
</div>

DEMO: http://jsfiddle.net/yJrtR/12/

So what this code does is from the time the window has loaded, it continually re-gets the geo position. There are special options you can pass to the getCurrentPosition, that I declared in getPositionOptions.

As I said before, the getCurrentPosition is asynchronous, so the position could be retrieved at any time after calling getCurrentPosition is called...that's what the callbacks are for. In the options object, I set a timeout - 10000 - that says "don't take any longer than 10 seconds to retrieve the position", and if it does, it will call the error callback. The maximumAge option makes sure it always tries to grab the current location (instead of using a cached version, within a certain period of time.

So when either callback is called (could be 1 second later, could be 20 seconds later...although we set a timeout of 10 seconds), it will update the HTML with the details, and then do it all again 5 seconds later - that's what the setTimeout is for. This is because if we continually tried to get the position (without any kind of delay), the page would be very busy getting the position. 5 second delays, or even up to 15, should be fine.

Reference:


UPDATE:

There is a specific method for the geolocation feature that lets you watch the position, called watchPosition, doing exactly what I was trying to emulate, but more efficiently. You could try this:

window.onload = function () {
    var latElement = document.getElementById("lat"),
        lonElement = document.getElementById("lon"),
        lastUpdatedElement = document.getElementById("last_updated"),
        watchPositionOptions = {
            enableHighAccuracy: false,
            timeout: 10000,
            maximumAge: 0
        };
    navigator.geolocation.watchPosition(function (position) {
        console.log("Successfully retrieved position: ", position);
        var coords = position.coords;

        latElement.innerHTML = coords.latitude;
        lonElement.innerHTML = coords.longitude;

        lastUpdatedElement.innerHTML = new Date(position.timestamp);
    }, function (error) {
        console.log("Something went wrong retrieving position: ", error);
    }, watchPositionOptions);
};

DEMO: http://jsfiddle.net/yJrtR/14/

Reference:

Sign up to request clarification or add additional context in comments.

6 Comments

OK, thanks for that. How would I make it so that it constantly "watches" the location of the device, continuously updating the variable and having it update in a dialog onscreen (without making an alert box)?
@goldage5 I updated my answer with how I'd handle what you're asking now. If you need to know how to make a dialog, you need to ask a new question on here. The demo I provided was just to pretend like a dialog. The important part is getting the geo location stuff working, which seems to be work correctly in the fiddle. Make sure you watch your browser's console to see events happening (since I log them)
Ok, thanks. That really helps me. Out of curiosity, what is the accuracy of the coordinates it gets?
@goldage5 If you look at the link at the end of my answer, it provides a lot of information about this feature, including accuracy. For example, you can look at position.coords.accuracy to see how accurate the coordinates (in meters). If you look at the getPositionOptions object I used in the second example, you'll see a enableHighAccuracy property - it can be set to true to try to make it more accurate (but consumes more power of your computer).
@goldage5 I honestly have no idea how it gets position for a non-GPS device, so in terms of that, I don't know :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.