Javascript getCurrentPosition()跨平台项目
早上好, 对于我的大学跨平台项目,我需要使用navigator.geolocation.getCurrentPosition()JS函数来检测和处理位置。 在互联网上阅读(以及在老师的幻灯片上),我理解这个函数调用回调函数,所以我尝试使用一些console.logJavascript getCurrentPosition()跨平台项目,javascript,position,positioning,Javascript,Position,Positioning,早上好, 对于我的大学跨平台项目,我需要使用navigator.geolocation.getCurrentPosition()JS函数来检测和处理位置。 在互联网上阅读(以及在老师的幻灯片上),我理解这个函数调用回调函数,所以我尝试使用一些console.log $("#update").click(function() { console.log(navigator.geolocation.getCurrentPosition(function(position) {do_some
$("#update").click(function() {
console.log(navigator.geolocation.getCurrentPosition(function(position) {do_something(position.coords.latitude, position.coords.longitude);}));
});
结果是:未定义。我做错了什么
已解决
问题出在我的浏览器上:我不知道为什么,但它等了几秒钟才问我“允许位置”,这导致了这些问题。
navigator.geolocation.getCurrentPosition(fx)
将回调fx
作为参数,在位置可用时执行
to simplify your mistake:
function f(g) {
var x = 10, y = 10;
setTimeout(function () {
g(x,y)
}, 100);
};
//what you are doing
console.log(f(function (x,y) { })) //undefined
//what you should do
f(function (x,y) { console.log(x,y) }) //wait a bit, than 10, 10
//summary
console.log(f(function (x,y) { console.log(x,y) })) //undefined
//~100ms later: 10 10
我也读过:点击“显示我的位置”的“实时结果”是“无法检索你的位置”。我的浏览器有问题吗?问题是没有打印坐标?@Leo什么都没有打印!只有“无法检索您的位置”!您是否已检查是否未阻止访问您的位置?您的代码:“navigator.geolocation.getCurrentPosition(function(position){console.log(position.coords.latitude,position.coords.longitude);”,如果我在控制台中启动它,它可以工作,但我已经授权浏览器使用我的位置。@MattiaPuntarello您不能强制位置授权,这取决于用户允许