地理位置异步问题和react-google-maps

时间:2019-05-28 22:42:54

标签: javascript node.js reactjs async-await react-google-maps

我正在用react组件实现google maps方向,并使用navigator.geolocation作为起始位置而苦苦挣扎。警告:我是React和Node的新手。

我有两个在ComponentDidMount中调用的主要方法, setStartLoc(),它将起始位置设置为navigator.geolocation结果(如果用户允许,则默认为硬编码位置) ,以及 GetDirections(),该查询会在maps api中查询从开始位置到目标位置的方向(函数参数)。

componentDidMount() {
    //get geoLocation and print
    const startLoc = this.setStartLoc();
    console.log(startLoc);

    //set destination
    const destinationLoc =  "50.927884,  -1.299285";

    //get directions once start location returned
    startLoc.then(function(startLoc){
      this.getDirections(startLoc,destinationLoc).bind(this)
    })
  }

我在使用异步 getDirections 函数时遇到了问题,即在用户有机会允许其地理位置定位之前查询路线,这会导致api返回错误。

我尝试通过强制实现 setStartLoc 作为承诺并使用 .then

来强制 getDirections 等待
  setStartLoc = function() {
    return new Promise(function(resolve,reject){
        if (navigator && navigator.geolocation) {
            console.log("in navigator");
            //get browser geolocation:
            navigator.geolocation.getCurrentPosition(pos => {
                resolve(pos.coords.latitude + ", " + pos.coords.longitude);
            });
        }
        else{
            //hardcoded alternative start location
            resolve("50.927044, -1.299964");
        }
    })
  }

据我所知,这可以迫使 getDirections 等待,但确实会导致以下typeError。

“ TypeError:未定义”

所指的是 componentDidMount 中的以下代码。

  this.getDirections(startLoc,destinationLoc).bind(this)

我自然尝试添加/删除绑定,但是会发生相同的错误。

任何人都可以通过更正显示的代码或建议另一种方法来帮助解决此错误,该方法使 getDirection()函数在 setStartLoc()之后等待查询>已经回来了吗?

getDirections方法和其余组件代码均来自此guide,在其中可以看到组件的完整代码here-我在其中添加了 setStartLoc ,并如图所示更改了 componentDidMount

在此先感谢您的帮助!

最大

1 个答案:

答案 0 :(得分:0)

通过使用setStartLoc函数可以使您走上正确的轨道,但是,要解决范围问题,@ Jaromanda X绝对正确,这里需要一个箭头功能。

使用箭头功能,您可以在componentDidMount中执行以下操作:

startLoc.then(startLoc => {
   this.getDirections(startLoc, destinationLoc);
});

startLoc被定义的地方是这样的:

setStartLoc = () => {
    return new Promise(function(resolve, reject) {
      if (navigator && navigator.geolocation) {
        console.log("in navigator");
        //get browser geolocation:
        return navigator.geolocation.getCurrentPosition(
          pos => {
            return resolve(pos.coords.latitude + ", " + pos.coords.longitude);
          },
          err => resolve("50.927044, -1.299964") // if user refuses access, return with default
        );
      }
      return resolve("50.927044, -1.299964");
    });
  };

为完整起见,这里是codesanbox