如何在javascript操作中获取用户的当前位置?
当我尝试使用$user.currentLocation
时出现错误
答案 0 :(得分:2)
在您的操作文件中,包含以下代码以获取CurrentLocation对象,该对象是您必须导入的viv.geo库胶囊的一部分。有关如何导入胶囊库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) }
}
}
}
}
然后在您的JavaScript函数中,您可以以console.log(myLocation)
的身份访问CurrentLocation对象,结果将为
latitude:21.334342
longitude:-88.89106
$id:null
$type:viv.geo.CurrentLocation
答案 1 :(得分:0)
您可以使用此功能
此代码段不适用于stackOverflow,然后转到Codepen
尝试: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>