skip to Main Content

You need to use the geodata in the tag, in the center attribute. But React prohibits the use of js code in a block with html. I tried to pull data from promise, but I always got undefined.

function App() {
  var lc;
    var getLocationPromise = new Promise((resolve) => {
          navigator.geolocation.getCurrentPosition(async function (position) {
              resolve([position.coords.latitude, position.coords.longitude])
          })
  })

  getLocationPromise.then((location) => {
    lc = location
    return lc
  }).catch((err) => {
      document.white("error")
  })

    return (
          <YMaps>
           <Map className="myMap" defaultState={{ center: [34, 55], zoom: 9 }}  ></Map>
          </YMaps>
        </div>
        )
    }
    export default App;

2

Answers


  1. You may use react local state as shown below

    const [lat, setLat] = React.useState(0);
    const [lng, setLng] = React.useState(0);
    
    getLocationPromise.then((location) => {
        setLat(location[0]);
        setLng(location[1]);
    }).catch((err) => {
        document.write("error")
    })
    
    <Map className="myMap" defaultState={{ center: [lat, lng], zoom: 9 }}  ></Map>
    
    Login or Signup to reply.
  2. Did you try useEffect hook ?
    You should be able to reference the object from anywhere (if thats what you want to do) with React’s "useEffect"and "useState" properties.

    For your usecase, you should do something like this:

    const [geoData, setGeoData] = useState(null)
    useEffect(async ()=>{
      const data = await YOUR_FUNCTION() / Promise
      setGeoData(data)
    },
    // This one should be empty
    [])
    

    and then in your code, you can access the geoData and use it as you want.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search