How store latitude and longitude from navigator.geolocation.getCurrentPosition() into a variable before returning the variable in javascript

I have written the following JavaScript function to return latitude and longitude values so I am trying to store them into variables and return those variable, but since navigator.geolocation.getCurrentPosition() function is asynchronous return action happens before that and my function always returns undefined. Can anyone show me a way to return values after the asynchronous function?

function getLocation() {
    let lat = 0
    let long = 0
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( function(position) {
            console.log(position.coords.latitude, position.coords.longitude)
            lat = position.coords.latitude
            long = position.coords.longitude
      
            //console.log("LATLONG1: ", lat, long) //test..
        })
    }
  
    return [lat,long]
}

6 thoughts on “How store latitude and longitude from navigator.geolocation.getCurrentPosition() into a variable before returning the variable in javascript”

Leave a Comment