Confused with return in function

I tried to return longitude and latitude but I do not know where is the problem, can someone explain me.

function getLocation() {
    if (navigator.geolocation) {
        return navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        some function
    }
}

function showPosition(position){
    let lat = position.coords.latitude; 
    let long = position.coords.longitude;   
    return lat, long;
}

getLocation();
console.log(lat,long);

For one thing, you are trying to return two vars-- You can, but only if you combine them in a single array.

However even with a single var you have to give your function a return assignment. That is, the ‘return’ has to go somewhere not the ‘ether’.

I.e. var lat = getLatitude();

– Mainly because keep in mind the lat/long vars are now out of ‘scope’ as you have defined your function.

I will try to answer, you can try to pass the lat and long value to other function and do action inside the function

function showPosition(position){
    let lat = position.coords.latitude; 
    let long = position.coords.longitude;   
    // remove the return 
    //return lat, long;
  // make a object for passing data
  var cord={
     "lat":lat,
     "long": long 
  }
 // make a function 
 getData(cord);
}

and you can make getData function to execute the value

function getData(value){
        console.log("this is lat value "+value.lat+ " this is long value "+value.long);
}
1 Like

I find a better solution for my previous answer

// make a  function with parameter
function getLocation(success) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success);
    } else {
        console.log("else");
    }
}


getLocation(function(pos){
        let lat=pos.coords.latitude;
        let long=pos.coords.longitude;
        var coord={
                "lat":lat,
                "long":long
        };
        console.log("this is lat value"+coord.lat+" this is long value "+ coord.long);
});

sorry for my bad explanation english is not my first language :joy: