【问题标题】:Why I cannot access values in my object after navigator.geolocation.getCurrentPosition() assigning values to it and returns it?为什么在 navigator.geolocation.getCurrentPosition() 为其分配值并返回它之后我无法访问我的对象中的值?
【发布时间】:2019-11-01 21:24:41
【问题描述】:

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

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;
}

【问题讨论】:

    标签: javascript reactjs navigator react-google-maps


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 2023-01-15
      • 1970-01-01
      相关资源
      最近更新 更多