Search code examples
javascripthtmlvariablesgeolocationglobal-variables

Passing JS getCurrentPosition to global variable


I am building an app that requires user location, to achieve this i am using:

var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
};

function success(pos) {
    var crd = pos.coords;
    console.log('Your current position is:');
    console.log(`Latitude : ${crd.latitude}`);
    console.log(`Longitude: ${crd.longitude}`);
    console.log(`More or less ${crd.accuracy} meters.`);
    console.log(` ${crd.longitude}`);
 }

function error(err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
    console.log(`Latitude : 9`);
}

navigator.geolocation.getCurrentPosition(success, error, options);

How can i pass the user lattitude and longitude to a global variable?


Solution

  • You can use local storage for an optimize solution.

    var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };
    
    function success(pos) {
        var crd = pos.coords;
        console.log('Your current position is:');
        console.log(`Latitude : ${crd.latitude}`);
        console.log(`Longitude: ${crd.longitude}`);
        console.log(`More or less ${crd.accuracy} meters.`);
        let userLatitude = crd.latitude;
        let userLongitude = crd.longitude;
        localStorage.setItem("USER_LATITUDE", userLatitude);
        localStorage.setItem("USER_LONGITUDE", userLongitude);
        console.log(` ${crd.longitude}`);
     }
    
    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
        console.log(`Latitude : 9`);
    }
    
    navigator.geolocation.getCurrentPosition(success, error, options);
    

    If you want to use this location data;

    var latitude = localStorage.getItem('USER_LATITUDE');
    var longitude = localStorage.getItem('USER_LONGITUDE');