反应错误无法在“地理位置”上执行“getCurrentPosition”

问题描述 投票:0回答:1
import "./App.css";
import { useState, useEffect } from "react";

function App() {
  const [lat, setLat] = useState(null);
  const [long, setLong] = useState(null);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchLocation();
  }, []);

  async function fetchLocation() {
    try {
      const position = await navigator.geolocation.getCurrentPosition();
      setLat(position.coords.latitude);
      setLong(position.coords.longitude);
      fetchWeather();
    } catch (error) {
      // handle error
      console.error(error);
    }
  }

  async function fetchWeather() {
    try {
      const res = await fetch(
        `${
          import.meta.env.VITE_WEATHER_API_URL
        }/weather/?lat=${lat}&lon=${long}&units=metric&APPID=${
          import.meta.env.VITE_API_KEY
        }`
      );
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      const result = await res.json();
      setData(result);
      console.log(result);
      setLoading(false);
    } catch (error) {
      // handle error
      console.error(error);
      setError(error.message);
      setLoading(false);
    }
  }

  return (
    <>
      <h1>Weather App</h1>
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>{error}</p>
      ) : data ? (
        <div>
          <p>Location: {data.name}</p>
          <p>Temperature: {data.main.temp} °C</p>
          <p>Humidity: {data.main.humidity} %</p>
          <p>Wind: {data.wind.speed} m/s</p>
        </div>
      ) : null}
    </>
  );
}

export default App;

我是新来的反应。运行此代码时,我收到 (无法在“地理位置”上执行“getCurrentPosition”:需要 1 个参数,但仅存在 0 个)错误。 我不知道我做错了什么。如果您知道导致该问题的原因,请提供帮助。

我希望将 Openweathermap api 中的所有数据通过 geoLocation 获取到浏览器中

javascript html reactjs npm openweathermap
1个回答
0
投票

错误消息“无法在‘地理位置’上执行‘getCurrentPosition’:需要 1 个参数,但仅存在 0 个”表示 getCurrentPosition 函数需要一个参数,但您的代码在不提供任何参数的情况下调用它。该函数需要一个成功回调函数和一个可选的错误回调函数。
要解决此问题,您应该修改 fetchLocation 函数以提供成功回调函数。您可以通过将函数作为参数传递给 getCurrentPosition 来完成此操作,成功检索地理位置数据时将调用该函数。以下是您可以尝试修改代码的方法:

async function fetchLocation() {
  try {
    navigator.geolocation.getCurrentPosition(successCallback);
  } catch (error) {
    // handle error
    console.error(error);
  }
}

function successCallback(position) {
  setLat(position.coords.latitude);
  setLong(position.coords.longitude);
  fetchWeather();
}


在此修改后的代码中,我添加了一个 successCallback 函数,该函数将位置作为参数并设置纬度和经度状态。此回调提供给 getCurrentPosition。当成功获取地理位置数据时,将调用 successCallback 函数,并设置纬度和经度状态,然后调用 fetchWeather。
© www.soinside.com 2019 - 2024. All rights reserved.