Javascript JS-当前位置返回未定义
我尝试获取当前浏览器位置并在变量中设置它。如果浏览器未激活地理位置,请设置默认纬度和经度Javascript JS-当前位置返回未定义,javascript,geolocation,Javascript,Geolocation,我尝试获取当前浏览器位置并在变量中设置它。如果浏览器未激活地理位置,请设置默认纬度和经度 if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(location) { this.latitude = location.coords.latitude; this.longitude = location.coords.longi
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(location) {
this.latitude = location.coords.latitude;
this.longitude = location.coords.longitude;
});
}else{
this.latitude = 43.318820;
this.longitude = -3.004561
}
console.log(this.latitude); //Undefinied
console.log(this.longitude);//Undefinied
问题是:在任何情况下,变量都返回未定义。那么,这个代码怎么了
编辑
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(location => {
this.latitude = location.coords.latitude;
this.longitude = location.coords.longitude;
});
}else{
this.latitude = 43.318820;
this.longitude = -3.004561
}
console.log(this.latitude);
console.log(this.longitude);
1) 这是一个异步函数。您可以在回调中使用
console.log
2)您需要使用箭头函数在回调中使用正确的this
:getCurrentPosition(location=>{})
I使用回调编辑问题,但没有按预期工作。调用回调之前执行console.log
行。您可以在回调中使用console.log(this.latitude)
。回调不会与代码同步运行。您可以在开发工具中添加调试器并验证这一点。