How can I understand the code of geolocaion.getCurrentLocation(function)

As you can see the following, the geolocation.get current location has a function to be an argument, and the usage of the function is to return position and show the position, so what is the usage of getCurrentLocation while the function finished the job? I hope I’ve made me clear, I’m confused about this, anybody can help me with this?

  **Your code so far**

// Add your code below this line
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    document.getElementById('data').innerHTML = "latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude;

// Add your code above this line
<h4>You are here:</h4>
<div id="data">

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Get Geolocation Data to Find A User’s GPS Coordinates

Link to the challenge:

1 Like

This is an example of a “higher-order function,” a function that either takes in or returns back a function.

Much like or HTMLElement.addEventListener(), we can pass in functions that will be run for us. immediately runs the callback function against each thing in an array. HTMLElement.addEventListener() waits until the given event is triggered, and then runs the callback function.

And getCurrentPosition() is asynchronous, meaning we don’t know how long it might take, but when its Promise resolves, it will run the associated callback function, passing in that position data.

You could simply run your callback function, but to do so with the relevant data gathered when the browser can… We need an asynchronous handler, and a callback function.

1 Like

Thanks, you made it very clear :+1: :+1: :+1:

1 Like

Great question, though - asynchronous functions and callbacks can be confusing. Glad I helped clear things up some.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.