How store latitude and longitude from navigator.geolocation.getCurrentPosition() into a variable before returning them 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) {
        return 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]
}

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

  1. Since what I understood is that you wanna return the lat and long values from your function, you should just get rid of this "return" statement in the middle of the "if" statement.

    Reply

Leave a Comment