Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How geolocation.getCurrentPosition return value?

I am using getCurrentPosition to get local latitude and longitude. I know this function is asynchronous, just wondering how to return latitude and longitude value that can be accessed by other functions?

    function getGeo() {
        navigator.geolocation.getCurrentPosition(getCurrentLoc)
    }

    function getCurrentLoc(data) {
        var lat,lon;
        lat=data.coords.latitude;
        lon=data.coords.longitude;
        getLocalWeather(lat,lon)
        initMap(lat,lon)
    }
like image 299
hei Avatar asked Nov 29 '17 03:11

hei


People also ask

What does geolocation getCurrentPosition return?

Geolocation getCurrentPosition() Method The getCurrentPosition() method returns the current position of the device.

What does showPosition () in Geolocation API returns?

What does showPosition() returns? Explanation: showPosition() method returns both latitude and longitude of user.

Is Geolocation API accurate?

It has the highest accuracy; in most Android smartphones, the accuracy can be up to 10 metres. Mobile phone tracking is used if a cellphone or wireless modem is used without a GPS chip built in.

Which property returns a geolocation object in HTML?

The geolocation property returns a Geolocation object that can be used to locate the user's position. The geolocation property is read-only. The geolocation property is only available in secure contexts (HTTPS).


1 Answers

I would suggest you wrapping it in a promise:

function getPosition() {
    // Simple wrapper
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
}

async function main() {
    var position = await getPosition();  // wait for getPosition to complete
    console.log(position);
}

main();

https://jsfiddle.net/DerekL/zr8L57sL/

ES6 version:

function getPosition() {
    // Simple wrapper
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
}

function main() {
    getPosition().then(console.log); // wait for getPosition to complete
}

main();

https://jsfiddle.net/DerekL/90129LoL/

like image 171
Derek 朕會功夫 Avatar answered Sep 30 '22 03:09

Derek 朕會功夫