为什么在 navigator.geolocation.getCurrentPosition() 为它赋值和 returns 之后我无法访问对象中的值?

Why I cannot access values in my object after navigator.geolocation.getCurrentPosition() assigning values to it and returns it?

当我在函数 whereAmI 中使用 navigator.geolocation.getCurrentPosition() 为我的 pos 对象赋值时,我可以看到 lat 和 lng 在对象内部,但是当我尝试使用这些属性时,它们 return 未定义。非常感谢您的帮助!

import React, {useEffect, useState }  from 'react';

import { GoogleMap } from "react-google-maps"


import './Map.css';

function Map({mapsData}) {

  const myLocation = whereAmI();

  console.log(myLocation); // this returns object with values

  return (
      <GoogleMap 
      defaultZoom={12} 
      defaultCenter={{myLocation}}
      >
      { /* We will render our data here */ }
      </GoogleMap>
  )
}

export default Map;


// helper function to get my current location 
function whereAmI() {
  let pos = {};
  navigator.geolocation.getCurrentPosition((position)=> {
    pos.lat = position.coords.latitude;
    pos.lng = position.coords.longitude;
  })
  console.log(pos); // this returns an object as well with properties but pos.lat or pos.lng returns undefined
  return pos;
}

navigator.geolocation.getCurrentLocation() 是一个异步函数,因此您的 console.log 语句和 return 语句在 pos.lat 和 pos.lng 定义之前执行。这就是为什么 getCurrentLocation 接受一个在成功 returning 位置后执行的回调函数。