0

我是一个完全的 JS 新手,并尝试构建我的简单 JS 代码。目标是获取用户位置。

它可以工作,但是 getUserCoordinates 函数没有返回值?我认为这只是初学者的逻辑失败?

var app = {

geocoder: null,

init: function() {
    this.geocoder = new google.maps.Geocoder();
    coordinates = this.getUserCoordinates();
    console.log(coordinates); // empty??
    return;
},

getUserCoordinates: function() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( 

            function (coords) { 
                console.log(coords); // works Geocoder Object!
                return coords; // the problem 
            }, // more code
4

1 回答 1

2

不,对于初学者来说这是一个很常见的错误。该getCurrentPosition方法是异步的(确定位置需要一些时间)并且不返回任何内容。完成后,它将调用callback您传递给它的函数 - 将来的某个时候。该值仅在该回调内可用,或对从那里调用的函数可用。

于 2012-10-09T15:51:18.677 回答