Get User Location

I’d like to sort a list by distance to user location. I found how to do that in xano here:

Now, how do I get the lat and long coordinates? I followed these posts to use getCurrentPosition:

But I do not know enough Javascript to return the result in a workflow and use it in the next steps. Please help with this:

After getting the location, I will send the lat/long in a xano request and return a collection that updates the list below:

Thank you!

In your javascript action try something like this:

const options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

let success;
let error; 

const pos = new Promise((resolve, reject)=>{
success=(pos)=>{resolve(pos)}
error=(err)=>{reject(err)}
})

navigator.geolocation.getCurrentPosition(success, error, options);

return await pos

Thank you for replying. I vaguely remember learning promises in codecademy. Unfortunately, this returns an empty object. Based on your answer, I found another solution that works:

function getPosition() {
    "use strict";
    return new Promise(function(resolve, reject) {
      var coordinates = {
          lat: null,
          lng: null,
      }
      function success (pos) {
          coordinates.lat = pos.coords.latitude;
          coordinates.lng = pos.coords.longitude;
          resolve(coordinates);
      }

      function fail(error){
         reject(error);
      }
      navigator.geolocation.getCurrentPosition(success, fail);
    });
}

return getPosition()

In both cases, the Promise takes much longer to see the result than just using console.log in the getCurrentPosition function. Is that expected?

Thanks again!

It worked in a quick test I made. If in your case it is returning an empty object try returning a new object constructed with the values from the position (like you are doing in your code)

I agree that the call to the geolocation api could have been inside the promise.

It looks like that both codes are equivalent, the only difference is that you are returning a Promise instead of awaiting the value

Just saw that @weweb-team added a “get user location” action for workflows! Awesome to see how fast they can make a change that saves everyone hours of fiddling around. Thank you

1 Like