我想从函数中返回当前用户的纬度和经度,并且我编写了以下代码,但这段代码是" undefined"结果是。如果有人知道解决方案,请回答
<script>
function getLocation() {
if (navigator.geolocation) {
var lat_lng = navigator.geolocation.getCurrentPosition(showPosition);
console.log(lat_lng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var user_position = {};
user_position.lat = position.coords.latitude;
user_position.lng = position.coords.longitude;
return user_position;
}
getLocation()
</script>
答案 0 :(得分:0)
getCurrentPosition
正在执行异步,并且在您从follow函数获得结果之前执行console.log(lat_lng);
:
navigator.geolocation.getCurrentPosition(showPosition);
您必须使用callback
功能。
function getLocation(callback) {
if (navigator.geolocation) {
var lat_lng = navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
var user_position = {};
user_position.lat = position.coords.latitude;
user_position.lng = position.coords.longitude;
callback(user_position);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
getLocation(function(lat_lng){
console.log(lat_lng);
});