1

How do I get user current location in javascript action? when I try to use $user.currentLocation I get an error

Lucas
  • 275
  • 8
  • 37
Itai
  • 11
  • 2
  • format your code section properly and try to provide your error logs if possible , also tag your question accurately. – shizhen Jan 22 '19 at 13:18

2 Answers2

1

In your Action file, include the following code to get the CurrentLocation object which is part of the viv.geo library capsule that you will have to import. Refer to this post for instructions on how to import capsule libraries https://stackoverflow.com/a/53747472/10409637

computed-input (myLocation) {
  min (Required) max(One)
  type (geo.CurrentLocation)

  compute {
    if ($user.currentLocation.$exists) {
      intent {
        goal: geo.CurrentLocation
        value-set: geo.CurrentLocation { $expr ($user.currentLocation) }
      } 
    }
  }
}

In your javascript function, you can then access the CurrentLocation object as console.log(myLocation), the result will be

latitude:21.334342
longitude:-88.89106
$id:null
$type:viv.geo.CurrentLocation
-1

You can use this function

this code snippet does not work for stackOverflow then go to Codepen

try on: https://codepen.io/lucassoomago/pen/YBzOoW

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

</body>
</html>
Lucas
  • 275
  • 8
  • 37