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]
}

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

  1. Hello! This post couldn’t be written any better! Reading this post reminds me of my
    old room mate! He always kept talking about this. I will forward this post
    to him. Fairly certain he will have a good read.
    Thanks for sharing!

    Reply
  2. With havin so much written content do you ever run into any issues of plagorism or copyright infringement?

    My blog has a lot of completely unique content I’ve either
    authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without
    my agreement. Do you know any methods to help protect against content from being
    ripped off? I’d truly appreciate it.

    Reply
  3. Hey! I know this is somewhat off topic but I was wondering which blog platform are you
    using for this website? I’m getting sick and tired
    of WordPress because I’ve had issues with hackers and I’m looking at alternatives for another platform.
    I would be awesome if you could point me in the direction of a good platform.

    Reply