无法 return 在来自 navigation.geolocation.getCurrentPosition() 的 react-native 中定位

Cannot return position in from navigation.geolocation.getCurrentPosition() in react-native

我正在尝试在 react-native 中拍摄图像后获取地理位置。用户拍摄图像,图像与地理位置一起存储在对象中,并通过 http 请求发送到服务器。

保存获取地理位置的功能工作正常,但我无法return将地理位置存储在对象中以进行 http 传输。我得到一个未定义的。

        console.log('getCoordinates run')
        await navigator.geolocation.getCurrentPosition(
            position => {
                let coordinates = `${position.coords.longitude}, 
                      ${position.coords.latitude}`

                return coordinates
            },
            error => Alert.alert(error.message),
            { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
        )

    }


captureImage = async () => {
        if (this.camera) {
            const options = { quality: 0.5, base64: true };
            const data = await this.camera.takePictureAsync(options);
            console.log(data);



            let postData = {
                user: 1,
                coordinates: this.getCoordinates(),
                image: `data:image/jpeg;base64${data.base64}`,
            }
            console.log(postData)

             axios.post('https://localhost:5000/api/posts', postData)
                 .then(post => res.json(post))
                 .catch(err => console.log(err))

        }
    }

预期结果是,当 captureImage 函数运行带有 postData 对象的 getCoordinates 函数时,returns 是数据传输到服务器之前的当前地理位置。

geolocation.getCurrentPosition函数在这里的工作原理是它设置一个回调,一旦它获取用户的位置就发送数据。获取和发送相关数据需要时间。这就是我们使用回调或承诺的原因。但是在您的代码中,您只需调用该函数而不等待其响应,只需执行 API 调用即可。

我假设您已经使用 Async 函数来执行此操作。但如果我是你,我会尝试在这里使用 Promises 来解决这个问题。简单的例子是,

captureImage = async () => {
    if (this.camera) {
        // ... do your camera tasks
    }

    this.sendImageData(data); // data is what you got from camera.
}

getGeoInfo = () => {
   return new Promise((resolve, reject) => {
       navigator.geolocation.getCurrentPosition(
        position => {
            let coordinates = `${position.coords.longitude}, 
                  ${position.coords.latitude}`

            resolve(coordinates);
        },
        error => reject(error),
        { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
      )
   })
}

sendImageData = (cameraData) => {
   let coordinates = '';
   getGeoInfo.then(crdnts => coordinates = crdnts );

   // now coordinates have all relevant data you wished.
   const data = { //... make the object as you want }
   // do the API call using axios as you've already done.
}