0

I'd like to get my current position with HTML5 and use it with javascript. I did some test, it works, but with my final version I have an undefined value.

function geolocError(dueToBrowser=true){
    if(dueToBrowser){
        alert('your browser does not support HTML5 geolocation');
    }else{
        alert('error with geolocation');
    }   
}



function getPositon(){
    return navigator.geolocation.getCurrentPosition(function(position){
        return position.coords;
    }, geolocError);
}

$(document).ready(function() {



    if(navigator.geolocation) {
        var pos = getPositon();

        console.log(pos)
}
});

My console.log(pos); returns me "undefined".

1 Answer 1

1

Geolocation is async, you cannot do that. You should set logic in getCurrentPosition callback or use a deferred object:

See e.g jsFiddle

var defer = $.Deferred();

function getPositon() {
    navigator.geolocation.getCurrentPosition(function (position) {
        defer.resolveWith(position.coords);
    }, geolocError);
    return defer;
}

$(document).ready(function () {
    if (navigator.geolocation) {
        getPositon().done(function () {
            console.log(this);
        });
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks it works but it's a bad new. I had as idea to have the position on each page when it's loaded. For example i would like to post a comment with my position but i don't want the user wait to post it request :( it is a solution to store to position in a cookie ?
I've used sessionStorage instead of cookie

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.